pax_global_header 0000666 0000000 0000000 00000000064 14747113137 0014522 g ustar 00root root 0000000 0000000 52 comment=a51ebdefdc36f04e7cf2151d3a4ae7dd60365644
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/ 0000775 0000000 0000000 00000000000 14747113137 0022244 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/ 0000775 0000000 0000000 00000000000 14747113137 0023604 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/CODEOWNERS 0000664 0000000 0000000 00000001572 14747113137 0025204 0 ustar 00root root 0000000 0000000 # These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
* @remyleone
/api/account/ @tbellavia
/api/applesilicon/ @Laure-di
/api/baremetal/ @Laure-di
/api/billing/ @tbellavia
/api/block/ @Codelax
/api/cockpit/ @jremy42
/api/container/ @Codelax
/api/dedibox/ @Laure-di
/api/documentdb/ @jremy42
/api/domain/ @jremy42
/api/edge_services @yfodil
/api/flexibleip/ @yfodil
/api/function/ @Codelax
/api/iam/ @tbellavia
/api/inference/ @Laure-di
/api/instance/ @Codelax
/api/iot/ @jremy42
/api/ipam/ @yfodil
/api/jobs/ @Codelax
/api/k8s/ @Codelax
/api/key_manager/ @tbellavia
/api/lb/ @yfodil
/api/marketplace/ @Codelax
/api/mnq/ @jremy42
/api/rdb/ @jremy42
/api/redis/ @jremy42
/api/registry/ @Codelax
/api/secret/ @tbellavia
/api/serverless_sqldb/ @jremy42
/api/tem/ @jremy42
/api/vpc/ @yfodil
/api/vpcgw/ @yfodil
/api/webhosting/ @jremy42
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/dependabot.yml 0000664 0000000 0000000 00000001037 14747113137 0026435 0 ustar 00root root 0000000 0000000 # To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: gomod
directory: "/"
schedule:
interval: daily
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: monthly
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/labeler.yml 0000664 0000000 0000000 00000003752 14747113137 0025744 0 ustar 00root root 0000000 0000000 account:
- changed-files:
- any-glob-to-any-file:
- api/account/**
apple-silicon:
- changed-files:
- any-glob-to-any-file:
- api/applesilicon/**
baremetal:
- changed-files:
- any-glob-to-any-file:
- api/baremetal/**
billing:
- changed-files:
- any-glob-to-any-file:
- api/billing/**
container:
- changed-files:
- any-glob-to-any-file:
- api/container/**
dedibox:
- changed-files:
- any-glob-to-any-file:
- api/dedibox/**
domain:
- changed-files:
- any-glob-to-any-file:
- api/domain/**
flexible-ip:
- changed-files:
- any-glob-to-any-file:
- api/flexibleip/**
function:
- changed-files:
- any-glob-to-any-file:
- api/function/**
iam:
- changed-files:
- any-glob-to-any-file:
- api/iam/**
instance:
- changed-files:
- any-glob-to-any-file:
- api/instance/**
iot:
- changed-files:
- any-glob-to-any-file:
- api/iot/**
k8s:
- changed-files:
- any-glob-to-any-file:
- api/k8s/**
load-balancer:
- changed-files:
- any-glob-to-any-file:
- api/lb/**
mnq:
- changed-files:
- any-glob-to-any-file:
- api/mnq/**
rdb:
- changed-files:
- any-glob-to-any-file:
- api/rdb/**
redis:
- changed-files:
- any-glob-to-any-file:
- api/redis/**
registry:
- changed-files:
- any-glob-to-any-file:
- api/registry/**
sdb:
- changed-files:
- any-glob-to-any-file:
- api/sdb/**
secret:
- changed-files:
- any-glob-to-any-file:
- api/secret/**
tem:
- changed-files:
- any-glob-to-any-file:
- api/tem/**
vpc:
- changed-files:
- any-glob-to-any-file:
- api/vpc/**
vpcgw:
- changed-files:
- any-glob-to-any-file:
- api/vpcgw/**
webhosting:
- changed-files:
- any-glob-to-any-file:
- api/webhosting/**
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/ 0000775 0000000 0000000 00000000000 14747113137 0025641 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/codeql-analysis.yml 0000664 0000000 0000000 00000004436 14747113137 0031463 0 ustar 00root root 0000000 0000000 # For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '26 20 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'go' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3
# âšī¸ Command-line programs to run using the OS shell.
# đ https://git.io/JvXDl
# âī¸ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/golangci-lint.yml 0000664 0000000 0000000 00000001010 14747113137 0031103 0 ustar 00root root 0000000 0000000 name: golangci-lint
on:
merge_group:
pull_request:
permissions:
contents: read
checks: write
pull-requests: read
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: latest
args: --timeout 5m
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/labeler.yml 0000664 0000000 0000000 00000000513 14747113137 0027771 0 ustar 00root root 0000000 0000000 name: "Pull Request Labeler"
on:
- pull_request_target
jobs:
triage:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Labeler
uses: actions/labeler@v5
with:
sync-labels: true
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/pull-request.yaml 0000664 0000000 0000000 00000003147 14747113137 0031174 0 ustar 00root root 0000000 0000000 name: pull-request
on:
- pull_request
- merge_group
jobs:
unit-test:
strategy:
matrix:
go-version: [1.17.x, 1.18.x]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
# Checkout should always be before setup-go to ensure caching is working
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Run unit tests
run: go test -v ./...
build-arch-test:
strategy:
matrix:
go-version: [1.17.x, 1.18.x]
platform: [ubuntu-latest]
arch: [386, amd64, arm, arm64]
runs-on: ${{ matrix.platform }}
steps:
# Checkout should always be before setup-go to ensure caching is working
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Test to build binary
run: GOARCH=${{ matrix.arch }} go build ./...
build-platform-test:
strategy:
matrix:
go-version: [1.17.x, 1.18.x]
platform: [windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
# Checkout should always be before setup-go to ensure caching is working
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Test to build binary
run: go build ./...
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.github/workflows/release.yaml 0000664 0000000 0000000 00000001131 14747113137 0030141 0 ustar 00root root 0000000 0000000 name: goreleaser
on:
push:
tags:
- '*'
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.17
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: latest
args: release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.gitignore 0000664 0000000 0000000 00000000033 14747113137 0024230 0 ustar 00root root 0000000 0000000 .idea
.vscode
node_modules
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.golangci.yml 0000664 0000000 0000000 00000017003 14747113137 0024631 0 ustar 00root root 0000000 0000000 #
# Golang CI pipeline configuration
#
# To execute linters in local the ./scripts/lint.sh script can be used.
linters:
disable-all: true
# Run golangci-lint linters to see
enable:
- asasalint # check for pass []any as any in variadic func(...any) [fast: false, auto-fix: false]
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]
- bidichk # Checks for dangerous unicode character sequences [fast: true, auto-fix: false]
- bodyclose # checks whether HTTP response body is closed successfully [fast: false, auto-fix: false]
- canonicalheader # canonicalheader checks whether net/http.Header uses canonical header [fast: false, auto-fix: false]
- contextcheck # check the function whether use a non-inherited context [fast: false, auto-fix: false]
- decorder # check declaration order and count of types, constants, variables and functions [fast: true, auto-fix: false]
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false]
- dupword # checks for duplicate words in the source code [fast: true, auto-fix: true]
- durationcheck # check for two durations multiplied together [fast: false, auto-fix: false]
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false]
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false]
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false]
- gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false]
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. [fast: true, auto-fix: false]
- gochecksumtype # Run exhaustiveness checks on Go "sum types" [fast: false, auto-fix: false]
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
- goheader # Checks is file header matches to pattern [fast: true, auto-fix: false]
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true]
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false]
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false]
- goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false]
- gosimple #(megacheck): Linter for Go source code that specializes in simplifying a code [fast: false, auto-fix: false]
- grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false]
- importas # Enforces consistent import aliases [fast: false, auto-fix: false]
- ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
- ireturn # Accept Interfaces, Return Concrete Types [fast: false, auto-fix: false]
- loggercheck # (logrlint): Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). [fast: false, auto-fix: false]
- makezero # Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]
- mirror # reports wrong mirror patterns of bytes/strings usage [fast: false, auto-fix: false]
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
- nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
- noctx # noctx finds sending http request without context.Context [fast: false, auto-fix: false]
- nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false]
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. [fast: true, auto-fix: false]
- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false]
- prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false]
- predeclared # find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false]
- promlinter # Check Prometheus metrics naming via promlint [fast: true, auto-fix: false]
- protogetter # Reports direct reads from proto message fields when getters should be used [fast: false, auto-fix: true]
- reassign # Checks that package variables are not reassigned [fast: false, auto-fix: false]
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false]
- rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false]
- sloglint # ensure consistent code style when using log/slog [fast: false, auto-fix: false]
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false]
- staticcheck #(megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false]
- testifylint # Checks usage of github.com/stretchr/testify. [fast: false, auto-fix: false]
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false]
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false]
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: false, auto-fix: false]
- unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false]
- unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. [fast: true, auto-fix: false]
- wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
- zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false]
issues:
max-issues-per-linter: 0
max-same-issues: 0
exclude-rules:
- path: _test\.go
linters:
- stylecheck
- gosec
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/.goreleaser.yml 0000664 0000000 0000000 00000001377 14747113137 0025205 0 ustar 00root root 0000000 0000000 # Visit https://goreleaser.com for documentation on how to customize this
# behavior.
version: 2
before:
hooks:
- go mod tidy
builds:
- skip: true
source:
enabled: true
name_template: '{{ .ProjectName }}-{{ .Version }}'
format: 'tar.gz'
prefix_template: '{{ .ProjectName }}-{{ .Version }}/'
checksum:
name_template: '{{ .ProjectName }}_{{ .Version }}_SHA256SUMS'
algorithm: sha256
release:
# Manually examine the release before it's live
draft: true
changelog:
use: github-native
groups:
- title: Features
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 0
- title: Bug fixes
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
order: 1
- title: Documentation
regexp: '^.*?docs(\([[:word:]]+\))??!?:.+$'
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/CHANGELOG.md 0000664 0000000 0000000 00000052467 14747113137 0024073 0 ustar 00root root 0000000 0000000 # Changelog
## v1.0.0-beta.7 (2020-10-07)
### Features
* **account**: add project id to ssh key object ([#447](https://github.com/scaleway/scaleway-sdk-go/pull/447))
* **account**: add project_id in ssh-key ([#438](https://github.com/scaleway/scaleway-sdk-go/pull/438))
* **baremetal**: add RetryInterval variable ([#357](https://github.com/scaleway/scaleway-sdk-go/pull/357))
* **baremetal**: add boot type in start server ([#500](https://github.com/scaleway/scaleway-sdk-go/pull/500))
* **baremetal**: add install in create server ([#499](https://github.com/scaleway/scaleway-sdk-go/pull/499))
* **baremetal**: add ping status in server ([#390](https://github.com/scaleway/scaleway-sdk-go/pull/390))
* **baremetal**: add project-id to ipfailover v1alpha1 ([#559](https://github.com/scaleway/scaleway-sdk-go/pull/559))
* **baremetal**: add server helpers func in v1 ([#397](https://github.com/scaleway/scaleway-sdk-go/pull/397))
* **baremetal**: add support for projects ([#535](https://github.com/scaleway/scaleway-sdk-go/pull/535))
* **baremetal**: add v1 ([#396](https://github.com/scaleway/scaleway-sdk-go/pull/396))
* **config**: add support for default profile ([#478](https://github.com/scaleway/scaleway-sdk-go/pull/478))
* **config**: move telemetry config in profile ([#427](https://github.com/scaleway/scaleway-sdk-go/pull/427))
* **core**: add GetSecretKey and GetAccessKey ([#386](https://github.com/scaleway/scaleway-sdk-go/pull/386))
* **domain**: add domain registration process on DomainSummary ([#560](https://github.com/scaleway/scaleway-sdk-go/pull/560))
* **domain**: add external domain support ([#401](https://github.com/scaleway/scaleway-sdk-go/pull/401))
* **domain**: add new task types ([#415](https://github.com/scaleway/scaleway-sdk-go/pull/415))
* **domain**: add new types in messages and email validated in domain contact ([#423](https://github.com/scaleway/scaleway-sdk-go/pull/423))
* **domain**: add organization_id filter ([#424](https://github.com/scaleway/scaleway-sdk-go/pull/424))
* **domain**: add registration process and is_external filter ([#507](https://github.com/scaleway/scaleway-sdk-go/pull/507))
* **error**: add resource locked error ([#361](https://github.com/scaleway/scaleway-sdk-go/pull/361))
* **errors**: handle instance unknown resource ([#374](https://github.com/scaleway/scaleway-sdk-go/pull/374))
* **instance**: Add private_network filter on ListServers ([#567](https://github.com/scaleway/scaleway-sdk-go/pull/567))
* **instance**: Remove private_networks in CreateServerRequest ([#572](https://github.com/scaleway/scaleway-sdk-go/pull/572))
* **instance**: add a WaitForImage method ([#381](https://github.com/scaleway/scaleway-sdk-go/pull/381))
* **instance**: add a wait on volume ([#418](https://github.com/scaleway/scaleway-sdk-go/pull/418))
* **instance**: add project to others resources ([#519](https://github.com/scaleway/scaleway-sdk-go/pull/519))
* **instance**: add project to resource IP ([#460](https://github.com/scaleway/scaleway-sdk-go/pull/460))
* **instance**: add snapshot wait utils ([#398](https://github.com/scaleway/scaleway-sdk-go/pull/398))
* **instance**: add support for name in backup action ([#383](https://github.com/scaleway/scaleway-sdk-go/pull/383))
* **instance**: add tags to IP ([#344](https://github.com/scaleway/scaleway-sdk-go/pull/344))
* **instance**: add volume type endpoint ([#440](https://github.com/scaleway/scaleway-sdk-go/pull/440))
* **instance**: allow filter by tags in server list ([#373](https://github.com/scaleway/scaleway-sdk-go/pull/373))
* **instance**: exclude SetIp of the SDK ([#461](https://github.com/scaleway/scaleway-sdk-go/pull/461))
* **instance**: fix volume template project oneof ([#561](https://github.com/scaleway/scaleway-sdk-go/pull/561))
* **instance**: fix volume type endpoint ([#441](https://github.com/scaleway/scaleway-sdk-go/pull/441))
* **instance**: update metadata struct ([#541](https://github.com/scaleway/scaleway-sdk-go/pull/541))
* **instance**: use generated UpdateVolume ([#417](https://github.com/scaleway/scaleway-sdk-go/pull/417))
* **iot**: add REST network type ([#505](https://github.com/scaleway/scaleway-sdk-go/pull/505))
* **iot**: add WaitForHub IoT helper ([#445](https://github.com/scaleway/scaleway-sdk-go/pull/445))
* **iot**: add hub events settings ([#476](https://github.com/scaleway/scaleway-sdk-go/pull/476))
* **iot**: add name generation on hub network and device ([#526](https://github.com/scaleway/scaleway-sdk-go/pull/526))
* **iot**: add product plan in UpdateHubRequest ([#513](https://github.com/scaleway/scaleway-sdk-go/pull/513))
* **iot**: add support for hub-id in an UpdateDeviceRequest #554
* **iot**: enable sdk generation ([#444](https://github.com/scaleway/scaleway-sdk-go/pull/444))
* **k8s**: add kubeconfig and helpers ([#364](https://github.com/scaleway/scaleway-sdk-go/pull/364))
* **k8s**: add project support ([#517](https://github.com/scaleway/scaleway-sdk-go/pull/517))
* **k8s**: add scaledown unneeded time ([#385](https://github.com/scaleway/scaleway-sdk-go/pull/385))
* **k8s**: add traefik2 ingress ([#443](https://github.com/scaleway/scaleway-sdk-go/pull/443))
* **k8s**: add v1 api
* **k8s**: add wait for node method ([#352](https://github.com/scaleway/scaleway-sdk-go/pull/352))
* **k8s**: flag to delete block and pvc with kapsule ([#416](https://github.com/scaleway/scaleway-sdk-go/pull/416))
* **lb**: add SSL compatibility level ([#343](https://github.com/scaleway/scaleway-sdk-go/pull/343))
* **lb**: multi-certificacte in frontend ([#492](https://github.com/scaleway/scaleway-sdk-go/pull/492))
* **lb**: add default on the lb name generation ([#493](https://github.com/scaleway/scaleway-sdk-go/pull/493))
* **lb**: add private network ([#402](https://github.com/scaleway/scaleway-sdk-go/pull/402))
* **lb**: add support for multiple certificates in frontend ([#479](https://github.com/scaleway/scaleway-sdk-go/pull/479))
* **lb**: remove subscriber from cli generation ([#490](https://github.com/scaleway/scaleway-sdk-go/pull/490))
* **lb**: support projects ([#504](https://github.com/scaleway/scaleway-sdk-go/pull/504))
* **rdb**: add GetInstanceLogs method ([#484](https://github.com/scaleway/scaleway-sdk-go/pull/484))
* **rdb**: add beta flags ([#411](https://github.com/scaleway/scaleway-sdk-go/pull/411))
* **rdb**: add generated prefix ([#558](https://github.com/scaleway/scaleway-sdk-go/pull/558))
* **rdb**: add project_id to resources ([#571](https://github.com/scaleway/scaleway-sdk-go/pull/571))
* **rdb**: allow setting initial settings while creating an RDB instance. ([#536](https://github.com/scaleway/scaleway-sdk-go/pull/536))
* **rdb**: update upgrade call to add non-ha to ha upgrade ([#451](https://github.com/scaleway/scaleway-sdk-go/pull/451))
* **registry**: add wait functions on image and tag ([#426](https://github.com/scaleway/scaleway-sdk-go/pull/426))
* **registry**: support projects ([#506](https://github.com/scaleway/scaleway-sdk-go/pull/506))
* **vpc**: add support for project ([#565](https://github.com/scaleway/scaleway-sdk-go/pull/565))
* **vpc**: generate doc/cli/sdk ([#532](https://github.com/scaleway/scaleway-sdk-go/pull/532))
* add configurable retryInterval and timeout ([#428](https://github.com/scaleway/scaleway-sdk-go/pull/428))
* add projects ([#452](https://github.com/scaleway/scaleway-sdk-go/pull/452))
* add support for pl-waw-1 zone and pl-waw region ([#557](https://github.com/scaleway/scaleway-sdk-go/pull/557))
* set default project client value when request is empty ([#457](https://github.com/scaleway/scaleway-sdk-go/pull/457))
* use pointer to time.Time to allow null value ([#523](https://github.com/scaleway/scaleway-sdk-go/pull/523))
### Fixes
* **config**: LoadConfigFromPath better handle cross platform error ([#395](https://github.com/scaleway/scaleway-sdk-go/pull/395))
* **config**: debug level when reading env ([#349](https://github.com/scaleway/scaleway-sdk-go/pull/349))
* **errors**: handle all instance not found return messages ([#432](https://github.com/scaleway/scaleway-sdk-go/pull/432))
* **instance**: GetServerTypesAvailabilityResponse nested object
* **instance**: volume listing return all types by default
* **k8s**: add global retry interval for wait func ([#354](https://github.com/scaleway/scaleway-sdk-go/pull/354))
* **k8s**: change type for kubeconfig certificates ([#362](https://github.com/scaleway/scaleway-sdk-go/pull/362))
* **k8s**: panic on helpers timeout ([#369](https://github.com/scaleway/scaleway-sdk-go/pull/369))
* **k8s**: remove oldbinpacking from autoscaler estimator ([#389](https://github.com/scaleway/scaleway-sdk-go/pull/389))
* **rdb**: switch from ip to ipnet in ACL ([#482](https://github.com/scaleway/scaleway-sdk-go/pull/482))
* **registry**: use scw.Size ([#391](https://github.com/scaleway/scaleway-sdk-go/pull/391))
* date format in query parameters ([#471](https://github.com/scaleway/scaleway-sdk-go/pull/471))
* handle additional non standards errors ([#525](https://github.com/scaleway/scaleway-sdk-go/pull/525))
### Others
* **chore - baremetal**: rename to GetOfferFromOfferNameRequest ([#353](https://github.com/scaleway/scaleway-sdk-go/pull/353))
* **chore - config**: use os.UserHomeDir
* **chore - iot**: deprecate organization ID in CreateNetworkRequest ([#501](https://github.com/scaleway/scaleway-sdk-go/pull/501))
* **chore - locality**: small fixes ([#455](https://github.com/scaleway/scaleway-sdk-go/pull/455))
* **chore - rdb**: add locked status ([#568](https://github.com/scaleway/scaleway-sdk-go/pull/568))
* **chore - sdk_compilation_test**: add missing api packages in test ([#446](https://github.com/scaleway/scaleway-sdk-go/pull/446))
* **chore - vendor**: remove vendor folder and rely on go module instead ([#469](https://github.com/scaleway/scaleway-sdk-go/pull/469))
* **chore**: export Scaleway environment variable constants ([#400](https://github.com/scaleway/scaleway-sdk-go/pull/400))
* **chore**: export scw.getScwConfigDir ([#514](https://github.com/scaleway/scaleway-sdk-go/pull/514))
* **chore**: use focal fossa as an example ([#408](https://github.com/scaleway/scaleway-sdk-go/pull/408))
* **doc - account**: improve ssh-key documentation ([#375](https://github.com/scaleway/scaleway-sdk-go/pull/375))
* **doc - config**: add project_id ([#543](https://github.com/scaleway/scaleway-sdk-go/pull/543))
* **doc - core**: update credentials links ([#564](https://github.com/scaleway/scaleway-sdk-go/pull/564))
* **doc - instance**: documentation improvments ([#563](https://github.com/scaleway/scaleway-sdk-go/pull/563))
* **doc - instance**: fix project documentation ([#551](https://github.com/scaleway/scaleway-sdk-go/pull/551))
* **doc - rdb**: add go doc ([#465](https://github.com/scaleway/scaleway-sdk-go/pull/465))
* **doc - rdb**: remove dev1-s mention ([#472](https://github.com/scaleway/scaleway-sdk-go/pull/472))
* **docs**: add deprecation notices ([#570](https://github.com/scaleway/scaleway-sdk-go/pull/570))
* **docs**: improve API documentations ([#345](https://github.com/scaleway/scaleway-sdk-go/pull/345))
* **docs**: update generated godoc ([#481](https://github.com/scaleway/scaleway-sdk-go/pull/481))
* **docs - account**: comment few fields #380
* **docs - baremetal**: update comment ([#503](https://github.com/scaleway/scaleway-sdk-go/pull/503))
* **docs**: fix badges and update godoc links ([#520](https://github.com/scaleway/scaleway-sdk-go/pull/520))
* **rdb**: add support for wait on backup resource ([#474](https://github.com/scaleway/scaleway-sdk-go/pull/474))
* **rdb**: add wait function for instance logs ([#485](https://github.com/scaleway/scaleway-sdk-go/pull/485))
* **refactor**: rename method DurationPtr
## v1.0.0-beta.6 (2020-02-28)
### Features
* **baremetal**: add zone in primary resource ([#305](https://github.com/scaleway/scaleway-sdk-go/pull/305))
* **baremetal**: add get metrics method ([#298](https://github.com/scaleway/scaleway-sdk-go/pull/298))
* **core**: add String method to scw.Money ([#284](https://github.com/scaleway/scaleway-sdk-go/pull/284))
* **core**: add send_telemetry setting in the config ([#273](https://github.com/scaleway/scaleway-sdk-go/pull/273))
* **core**: add custom duration type ([#291](https://github.com/scaleway/scaleway-sdk-go/pull/291))
* **core**: handle instance quota exceeded error ([#287](https://github.com/scaleway/scaleway-sdk-go/pull/287))
* **core**: handle non standard errors ([#274](https://github.com/scaleway/scaleway-sdk-go/pull/274))
* **core**: support more instance error types ([#278](https://github.com/scaleway/scaleway-sdk-go/pull/278))
* **core**: Add ResourceExpiredError ([#280](https://github.com/scaleway/scaleway-sdk-go/pull/280))
* **core**: add GetCacheDirectory method ([#304](https://github.com/scaleway/scaleway-sdk-go/pull/304))
* **domain**: first release of the API ([#297](https://github.com/scaleway/scaleway-sdk-go/pull/297))
* **instance**: add OrganizationDefault to UpdateSecurityGroup ([#279](https://github.com/scaleway/scaleway-sdk-go/pull/279))
* **instance**: add zone field in instance resources response ([#331](https://github.com/scaleway/scaleway-sdk-go/pull/331))
* **instance**: allow empty boot type on create server [#325](https://github.com/scaleway/scaleway-sdk-go/pull/325))
* **k8s**: add FeatureGates and AdmissionPlugins ([#289](https://github.com/scaleway/scaleway-sdk-go/pull/289))
* **k8s**: add WaitForPoolNodesReady and WaitForClusterNodesReady helper methods ([#312](https://github.com/scaleway/scaleway-sdk-go/pull/312))
* **k8s**: add creation_error node status ([#328](https://github.com/scaleway/scaleway-sdk-go/pull/328))
* **k8s**: add upgrading pool status ([#319](https://github.com/scaleway/scaleway-sdk-go/pull/319))
* **k8s**: add UpgradeAvailable in pool ([#276](https://github.com/scaleway/scaleway-sdk-go/pull/276))
* **k8s**: add a field to rename Cluster ([#285](https://github.com/scaleway/scaleway-sdk-go/pull/285))
* **k8s**: add v1beta4 version ([#276](https://github.com/scaleway/scaleway-sdk-go/pull/276))
* **lb**: add CreateIP method ([#290](https://github.com/scaleway/scaleway-sdk-go/pull/290))
* **lb**: add support for proxy protocol ([#299](https://github.com/scaleway/scaleway-sdk-go/pull/299))
* **lb**: add Subscriber related methods ([#276](https://github.com/scaleway/scaleway-sdk-go/pull/276))
* **rdb**: add ExportDatabaseBackup method ([#292](https://github.com/scaleway/scaleway-sdk-go/pull/292))
* **rdb**: add OrganizationID field to ListDatabaseBackups ([#321](https://github.com/scaleway/scaleway-sdk-go/pull/321))
* **strcase**: add functions ([#275](https://github.com/scaleway/scaleway-sdk-go/pull/275))
### Fixes
* **core**: doc typo ([#293](https://github.com/scaleway/scaleway-sdk-go/pull/293))
* **core**: do not omit empty Money fields ([#288](https://github.com/scaleway/scaleway-sdk-go/pull/288))
* **core**: handle content-types in ResponseError ([#315](https://github.com/scaleway/scaleway-sdk-go/pull/315))
* **core**: handle precision and clean rounding of Money ([#286](https://github.com/scaleway/scaleway-sdk-go/pull/286))
* **instance**: set all server user data stop deleting all keys ([#281](https://github.com/scaleway/scaleway-sdk-go/pull/281))
* **instance**: properly convert ipId to ip-id, rename field of DeleteIpRequest ([#272](https://github.com/scaleway/scaleway-sdk-go/pull/272))
* **lb**: UpdateIP method reverse field ([#320](https://github.com/scaleway/scaleway-sdk-go/pull/320))
* **scripts**: golangci-lint binary installation test ([#301](https://github.com/scaleway/scaleway-sdk-go/pull/301))
## v1.0.0-beta.5 (2019-12-09)
### Features
* **baremetal**: add ListOffers and ListOs methods ([#259](https://github.com/scaleway/scaleway-sdk-go/pull/259))
* **config**: add a typed error on config file not found ([#264](https://github.com/scaleway/scaleway-sdk-go/pull/264))
* **config**: add a commented configuration file ([#231](https://github.com/scaleway/scaleway-sdk-go/pull/231))
* **core**: get Region from Zone ([#255](https://github.com/scaleway/scaleway-sdk-go/pull/255))
* **core**: client validation ([#238](https://github.com/scaleway/scaleway-sdk-go/pull/238))
* **core**: IPNet type ([#236](https://github.com/scaleway/scaleway-sdk-go/pull/236))
* **core**: introduce format validation in locality parsing ([#237](https://github.com/scaleway/scaleway-sdk-go/pull/237))
* **core**: add scw.MergeProfiles command ([#234](https://github.com/scaleway/scaleway-sdk-go/pull/234))
* **core**: add ClientCredentialError ([#228](https://github.com/scaleway/scaleway-sdk-go/pull/228))
* **core**: client without auth by default ([#233](https://github.com/scaleway/scaleway-sdk-go/pull/233))
* **k8s**: add maintenance and upgrade features ([#258](https://github.com/scaleway/scaleway-sdk-go/pull/258))
* **k8s**: add Pool.PlacementGroupID field ([#246](https://github.com/scaleway/scaleway-sdk-go/pull/246))
* **lb**: custom certificate ([#262](https://github.com/scaleway/scaleway-sdk-go/pull/262))
* **lb**: add ListBackendStats method ([#252](https://github.com/scaleway/scaleway-sdk-go/pull/252))
* **instance**: publish WaitForServer ([#244](https://github.com/scaleway/scaleway-sdk-go/pull/244))
* **instance**: generate name for new snapshot or image ([#230](https://github.com/scaleway/scaleway-sdk-go/pull/230))
* **strcase**: add strcase lib ([#229](https://github.com/scaleway/scaleway-sdk-go/pull/229))
* **rdb**: wait for Instance ([#249](https://github.com/scaleway/scaleway-sdk-go/pull/249))
* **rdb**: add rdb API ([#247](https://github.com/scaleway/scaleway-sdk-go/pull/247))
* **registry**: add WaitForNamespace method ([#253](https://github.com/scaleway/scaleway-sdk-go/pull/253))
* **validation**: add IsEmail ([#242](https://github.com/scaleway/scaleway-sdk-go/pull/242))
* **validation**: make validation package public ([#241](https://github.com/scaleway/scaleway-sdk-go/pull/241))
### Fixes
* **baremetal**: fix WaitForServer and add WaitForServerInstall ([#263](https://github.com/scaleway/scaleway-sdk-go/pull/263))
* **baremetal**: add Undelivered and Locked to terminalStatus ([#260](https://github.com/scaleway/scaleway-sdk-go/pull/260))
* **config**: merge selected profile on top of default profile ([#243](https://github.com/scaleway/scaleway-sdk-go/pull/243))
* **instance**: WaitForServer returns an error interface ([#245](https://github.com/scaleway/scaleway-sdk-go/pull/245))
* **instance**: use IPNet type for security group rule ip_range ([#240](https://github.com/scaleway/scaleway-sdk-go/pull/240))
* **instance**: update placement-group now works ([#224](https://github.com/scaleway/scaleway-sdk-go/pull/224))
## v1.0.0-beta.4 (2019-10-25)
### Breaking Changes
* use uint32 for page_size ([#210](https://github.com/scaleway/scaleway-sdk-go/pull/210))
### Features
* update generated apis ([#218](https://github.com/scaleway/scaleway-sdk-go/pull/218))
* update generated apis ([#216](https://github.com/scaleway/scaleway-sdk-go/pull/216))
* **lb**: add WaitForLb method ([#212](https://github.com/scaleway/scaleway-sdk-go/pull/212))
* update generated apis ([#213](https://github.com/scaleway/scaleway-sdk-go/pull/213))
* update generated apis ([#208](https://github.com/scaleway/scaleway-sdk-go/pull/208))
* **marketplace**: uppercase commercial type in GetLocalImageIDByLabel ([#205](https://github.com/scaleway/scaleway-sdk-go/pull/205))
* add kubeconfig helpers for k8s ([#204](https://github.com/scaleway/scaleway-sdk-go/pull/204))
* update generated apis ([#203](https://github.com/scaleway/scaleway-sdk-go/pull/203))
* add k8s WaitForCluster method ([#202](https://github.com/scaleway/scaleway-sdk-go/pull/202))
* add scw.IPPtr ([#200](https://github.com/scaleway/scaleway-sdk-go/pull/200))
* add k8s v1beta3 ([#198](https://github.com/scaleway/scaleway-sdk-go/pull/198))
### Fixes
* **instance**: update generated apis ([#219](https://github.com/scaleway/scaleway-sdk-go/pull/219))
* **instance**: ListImage total count ([#209](https://github.com/scaleway/scaleway-sdk-go/pull/209))
* cleanup unused code ([#217](https://github.com/scaleway/scaleway-sdk-go/pull/217))
* **scw.File**: add unmarshal ([#201](https://github.com/scaleway/scaleway-sdk-go/pull/201))
### Documentation
* fix examples ([#215](https://github.com/scaleway/scaleway-sdk-go/pull/215))
## v1.0.0-beta.3 (2019-10-01)
### Features
* add interface body getter to std err ([#192](https://github.com/scaleway/scaleway-sdk-go/pull/192))
* add support for out of stock error ([#190](https://github.com/scaleway/scaleway-sdk-go/pull/190))
* use uint32 for page count ([#193](https://github.com/scaleway/scaleway-sdk-go/pull/193))
* add raw body to standard errors ([#191](https://github.com/scaleway/scaleway-sdk-go/pull/191))
* update generated apis ([#188](https://github.com/scaleway/scaleway-sdk-go/pull/188))
### Fixes
* e2e tests project ([#195](https://github.com/scaleway/scaleway-sdk-go/pull/195))
* **instance**: allow image to be empty in CreateServer ([#189](https://github.com/scaleway/scaleway-sdk-go/pull/189))
## v1.0.0-beta.2 (2019-09-16)
### Features
* test standard errors ([#183](https://github.com/scaleway/scaleway-sdk-go/pull/183))
* update generated apis ([#182](https://github.com/scaleway/scaleway-sdk-go/pull/182))
* standard error structures ([#177](https://github.com/scaleway/scaleway-sdk-go/pull/177))
### Fixes
* attach volume key choice ([#184](https://github.com/scaleway/scaleway-sdk-go/pull/184))
* add user agent to e2e tests ([#181](https://github.com/scaleway/scaleway-sdk-go/pull/181))
* update version ([#180](https://github.com/scaleway/scaleway-sdk-go/pull/180))
* UpdateSecurityGroupRule can now remove DestPortFrom and DestPortTo ([#179](https://github.com/scaleway/scaleway-sdk-go/pull/179))
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006456 14747113137 0025056 0 ustar 00root root 0000000 0000000 # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at opensource@scaleway.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/CONTRIBUTING.md 0000664 0000000 0000000 00000011154 14747113137 0024477 0 ustar 00root root 0000000 0000000 # Contribute to `scaleway-sdk-go`
`scaleway-sdk-go` is Apache 2.0 licensed and accepts contributions via GitHub.
This document will cover how to contribute to the project and report issues.

## Topics
- [Reporting Security Issues](#reporting-security-issues)
- [Reporting Issues](#reporting-issues)
- [Suggesting feature](#suggesting-feature)
- [Contributing Code](#contributing-code)
- [Community Guidelines](#community-guidelines)
## Reporting security issues
At Scaleway we take security seriously.
If you have any issue regarding security, please notify us by sending an email to [security@scaleway.com](mailto:security@scaleway.com).
Please _DO NOT_ create a GitHub issue.
We will follow up with you promptly with more information and a plan for remediation.
We currently do not offer a paid security bounty program, but we would love to send some Scaleway swag your way along with our deepest gratitude for your assistance in making Scaleway a more secure Cloud ecosystem.
## Reporting issues
A great way to contribute to the project is to send a detailed report when you encounter a bug.
We always appreciate a well-written, thorough bug report, and will thank you for it!
Before opening a new issue, we appreciate you reviewing open issues to see if there are any similar requests.
If there is a match, thumbs up the issue with a đ and leave a comment if you have additional information.
When reporting an issue, include the following:
- The version of `scaleway-sdk-go` you are using (v2.0.0-beta1, v2.0.0, master,...)
- Go version
- GOOS
- GOARCH
## Suggesting a feature
When requesting a feature, some of the questions we want to answer are:
- What value does this feature bring to end users?
- How urgent is the need (nice to have feature or need to have)?
- Does this align with the goals of `scaleway-sdk-go`?
## Contributing code
Before contributing to the code, make sure you have read about the [continuous code deployment](docs/CONTINUOUS_CODE_DEPLOYMENT.md) process we are using on this repo.
### Submit code
To submit code:
- Create a fork of the project
- Create a topic branch from where you want to base your work (usually master)
- Add tests to cover contributed code
- Push your commit(s) to your topic branch on your fork
- Open a pull request against `scaleway-sdk-go` master branch that follows [PR guidelines](#pull-request-guidelines)
The [maintainers](MAINTAINERS.md) of `scaleway-sdk-go` use a "Let's Get This Merged" (LGTM) message in the pull request to note that the commits are ready to merge.
After one or more maintainer states LGTM, we will merge.
If you have questions or comments on your code, feel free to correct these in your branch through new commits.
### Pull Request Guidelines
The goal of the following guidelines is to have Pull Requests (PRs) that are fairly easy to review and comprehend, and code that is easy to maintain in the future.
- **Pull Request title should be clear** on what is being fixed or added to the code base.
If you are addressing an open issue, please start the title with "fix: #XXX" or "feature: #XXX"
- **Keep it readable for human reviewers** and prefer a subset of functionality (code) with tests and documentation over delivering them separately
- **Don't forget commenting code** to help reviewers understand and to keep [our Go Report Card](https://goreportcard.com/report/github.com/scaleway/scaleway-sdk-go) at A+
- **Notify Work In Progress PRs** by prefixing the title with `[WIP]`
- **Please, keep us updated.**
We will try our best to merge your PR, but please notice that PRs may be closed after 30 days of inactivity.
Your pull request should be rebased against the current master branch. Please do not merge
the current master branch in with your topic branch, nor use the Update Branch button provided
by GitHub on the pull request page.
Keep in mind only the **Pull Request Title** will be used as commit message as we stash all commits on merge.
## Community guidelines
See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
Thank you for reading through all of this, if you have any question feel free to [reach us](README.md#reach-us)!
## Developer documentation
### Namespaces
Namespaces SHOULD only be written using lowercase letters. No dash are allowed.
Example: `accountprivate` is a valid Go namespace.
### Validation
Some validation is done internally on Scaleway's side: see [scaleway-sdk-go/docs/CONTINUOUS_CODE_DEPLOYMENT.md](https://github.com/scaleway/scaleway-sdk-go/blob/master/docs/CONTINUOUS_CODE_DEPLOYMENT.md)
This is true for:
- package namespaces.
The rest is manually checked for now.
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/LICENSE 0000664 0000000 0000000 00000025005 14747113137 0023253 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2019 Scaleway.
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
https://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.
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/MAINTAINERS.md 0000664 0000000 0000000 00000000756 14747113137 0024350 0 ustar 00root root 0000000 0000000 This page lists all active maintainers of `scaleway-sdk-go`. This can be used for
routing PRs, questions, etc. to the right place.
- See [CONTRIBUTING.md](CONTRIBUTING.md) for general contribution guidelines.
### Maintainers
| Name | Tag |
| :------------- | :-------------- |
| JÊrôme QuÊrÊ | @jerome-quere |
| Quentin Brosse | @QuentinBrosse |
| Loïc Bourgois | @loicbourgois |
| Olivier Cano | @kindermoumoute |
| RÊmy LÊone | @remyleone |
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/README.md 0000664 0000000 0000000 00000006015 14747113137 0023525 0 ustar 00root root 0000000 0000000 
# Scaleway GO SDK
**:warning: This is an early release, keep in mind that the API can break**
Scaleway is a single way to create, deploy and scale your infrastructure in the cloud. We help thousands of businesses to run their infrastructures easily.
## Documentation
- [Godoc](https://pkg.go.dev/github.com/scaleway/scaleway-sdk-go?tab=doc)
- [Developers website](https://www.scaleway.com/en/developers/) (API documentation)
- [Products availability guide](https://www.scaleway.com/en/docs/console/my-account/reference-content/products-availability/)
- [The community tools](https://www.scaleway.com/en/developers/#official-repos)
## Installation
```bash
go get github.com/scaleway/scaleway-sdk-go
```
## Getting Started
```go
package main
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/instance/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/scaleway-sdk-go/utils"
)
func main() {
// Create a Scaleway client
client, err := scw.NewClient(
// Get your organization ID at https://console.scaleway.com/organization/settings
scw.WithDefaultOrganizationID("SCW_DEFAULT_ORGANIZATION_ID"),
// Get your credentials at https://console.scaleway.com/iam/api-keys
scw.WithAuth("SCW_ACCESS_KEY", "SCW_SECRET_KEY"),
// Get more about our availability zones at https://www.scaleway.com/en/docs/console/my-account/reference-content/products-availability/
scw.WithDefaultRegion("SCW_REGION"),
)
if err != nil {
panic(err)
}
// Create SDK objects for Scaleway Instance product
instanceApi := instance.NewAPI(client)
// Call the ListServers method on the Instance SDK
response, err := instanceApi.ListServers(&instance.ListServersRequest{
Zone: scw.ZoneFrPar1,
})
if err != nil {
panic(err)
}
// Do something with the response...
for _, server := range response.Servers {
fmt.Println("Server", server.ID, server.Name)
}
}
```
## Examples
You can find additional examples in the [GoDoc](https://pkg.go.dev/github.com/scaleway/scaleway-sdk-go?tab=doc).
## Development
This repository is at its early stage and is still in active development.
If you are looking for a way to contribute please read [CONTRIBUTING.md](CONTRIBUTING.md).
## Reach us
We love feedback.
Feel free to reach us on [Scaleway Slack community](https://slack.scaleway.com/), we are waiting for you on [#opensource](https://scaleway-community.slack.com/app_redirect?channel=opensource).
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ 0000775 0000000 0000000 00000000000 14747113137 0023015 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/account/ 0000775 0000000 0000000 00000000000 14747113137 0024451 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/account/v3/ 0000775 0000000 0000000 00000000000 14747113137 0025001 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/account/v3/account_sdk.go 0000664 0000000 0000000 00000052511 14747113137 0027631 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package account provides methods and message types of the account v3 API.
package account
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
std "github.com/scaleway/scaleway-sdk-go/api/std"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ContractType string
const (
// Unknown type.
ContractTypeUnknownType = ContractType("unknown_type")
// A global contract.
ContractTypeGlobal = ContractType("global")
// Deprecated. A contract specific to the Kubernetes product.
ContractTypeK8s = ContractType("k8s")
// A contract specific to the Instance product.
ContractTypeInstance = ContractType("instance")
// A contract specific to Container products.
ContractTypeContainer = ContractType("container")
// A contract specific to Baremetal products.
ContractTypeBaremetal = ContractType("baremetal")
)
func (enum ContractType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ContractType) Values() []ContractType {
return []ContractType{
"unknown_type",
"global",
"k8s",
"instance",
"container",
"baremetal",
}
}
func (enum ContractType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContractType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContractType(ContractType(tmp).String())
return nil
}
type ListContractSignaturesRequestOrderBy string
const (
// Signing date ascending.
ListContractSignaturesRequestOrderBySignedAtAsc = ListContractSignaturesRequestOrderBy("signed_at_asc")
// Signing date descending.
ListContractSignaturesRequestOrderBySignedAtDesc = ListContractSignaturesRequestOrderBy("signed_at_desc")
// Expiration date ascending.
ListContractSignaturesRequestOrderByExpiresAtAsc = ListContractSignaturesRequestOrderBy("expires_at_asc")
// Expiration date descending.
ListContractSignaturesRequestOrderByExpiresAtDesc = ListContractSignaturesRequestOrderBy("expires_at_desc")
// Name ascending.
ListContractSignaturesRequestOrderByNameAsc = ListContractSignaturesRequestOrderBy("name_asc")
// Name descending.
ListContractSignaturesRequestOrderByNameDesc = ListContractSignaturesRequestOrderBy("name_desc")
)
func (enum ListContractSignaturesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "signed_at_asc"
}
return string(enum)
}
func (enum ListContractSignaturesRequestOrderBy) Values() []ListContractSignaturesRequestOrderBy {
return []ListContractSignaturesRequestOrderBy{
"signed_at_asc",
"signed_at_desc",
"expires_at_asc",
"expires_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListContractSignaturesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListContractSignaturesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListContractSignaturesRequestOrderBy(ListContractSignaturesRequestOrderBy(tmp).String())
return nil
}
type ListProjectsRequestOrderBy string
const (
// Creation date ascending.
ListProjectsRequestOrderByCreatedAtAsc = ListProjectsRequestOrderBy("created_at_asc")
// Creation date descending.
ListProjectsRequestOrderByCreatedAtDesc = ListProjectsRequestOrderBy("created_at_desc")
// Name ascending.
ListProjectsRequestOrderByNameAsc = ListProjectsRequestOrderBy("name_asc")
// Name descending.
ListProjectsRequestOrderByNameDesc = ListProjectsRequestOrderBy("name_desc")
)
func (enum ListProjectsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListProjectsRequestOrderBy) Values() []ListProjectsRequestOrderBy {
return []ListProjectsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListProjectsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListProjectsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListProjectsRequestOrderBy(ListProjectsRequestOrderBy(tmp).String())
return nil
}
// Contract: contract.
type Contract struct {
// ID: ID of the contract.
ID string `json:"id"`
// Type: the type of the contract.
// Default value: unknown_type
Type ContractType `json:"type"`
// Name: the name of the contract.
Name string `json:"name"`
// Version: the version of the contract.
Version uint32 `json:"version"`
// CreatedAt: the creation date of the contract.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: the last modification date of the contract.
UpdatedAt *time.Time `json:"updated_at"`
}
// ContractSignature: contract signature.
type ContractSignature struct {
// ID: ID of the contract signature.
ID string `json:"id"`
// OrganizationID: the Organization ID which signed the contract.
OrganizationID string `json:"organization_id"`
// CreatedAt: the creation date of the contract signature.
CreatedAt *time.Time `json:"created_at"`
// SignedAt: the signing date of the contract signature.
SignedAt *time.Time `json:"signed_at"`
// ExpiresAt: the expiration date of the contract signature.
ExpiresAt *time.Time `json:"expires_at"`
// Contract: the contract signed.
Contract *Contract `json:"contract"`
}
// Project: project.
type Project struct {
// ID: ID of the Project.
ID string `json:"id"`
// Name: name of the Project.
Name string `json:"name"`
// OrganizationID: organization ID of the Project.
OrganizationID string `json:"organization_id"`
// CreatedAt: creation date of the Project.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: update date of the Project.
UpdatedAt *time.Time `json:"updated_at"`
// Description: description of the Project.
Description string `json:"description"`
}
// CheckContractSignatureResponse: check contract signature response.
type CheckContractSignatureResponse struct {
// Created: whether a signature has been requested for this contract.
Created bool `json:"created"`
// Validated: whether the signature for this contract has been validated.
Validated bool `json:"validated"`
}
// ContractAPICheckContractSignatureRequest: contract api check contract signature request.
type ContractAPICheckContractSignatureRequest struct {
// OrganizationID: ID of the Organization to check the contract signature for.
OrganizationID string `json:"organization_id"`
// ContractType: filter on contract type.
// Default value: unknown_type
ContractType ContractType `json:"contract_type"`
// ContractName: filter on contract name.
ContractName string `json:"contract_name"`
}
// ContractAPICreateContractSignatureRequest: contract api create contract signature request.
type ContractAPICreateContractSignatureRequest struct {
// ContractType: the type of the contract.
// Default value: unknown_type
ContractType ContractType `json:"contract_type"`
// ContractName: the name of the contract.
ContractName string `json:"contract_name"`
// Validated: whether the contract is validated at creation.
Validated bool `json:"validated"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
}
// ContractAPIDownloadContractSignatureRequest: contract api download contract signature request.
type ContractAPIDownloadContractSignatureRequest struct {
// ContractSignatureID: the contract signature ID.
ContractSignatureID string `json:"-"`
// Locale: the locale requested for the content of the contract.
// Default value: unknown_language_code
Locale std.LanguageCode `json:"-"`
}
// ContractAPIListContractSignaturesRequest: contract api list contract signatures request.
type ContractAPIListContractSignaturesRequest struct {
// Page: the page number for the returned contracts.
Page *int32 `json:"-"`
// PageSize: the maximum number of contracts per page.
PageSize *uint32 `json:"-"`
// OrderBy: how the contracts are ordered in the response.
// Default value: signed_at_asc
OrderBy ListContractSignaturesRequestOrderBy `json:"-"`
// OrganizationID: filter on Organization ID.
OrganizationID string `json:"-"`
}
// ContractAPIValidateContractSignatureRequest: contract api validate contract signature request.
type ContractAPIValidateContractSignatureRequest struct {
// ContractSignatureID: the contract linked to your Organization you want to sign.
ContractSignatureID string `json:"-"`
}
// ListContractSignaturesResponse: list contract signatures response.
type ListContractSignaturesResponse struct {
// TotalCount: the total number of contract signatures.
TotalCount uint64 `json:"total_count"`
// ContractSignatures: the paginated returned contract signatures.
ContractSignatures []*ContractSignature `json:"contract_signatures"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListContractSignaturesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListContractSignaturesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListContractSignaturesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ContractSignatures = append(r.ContractSignatures, results.ContractSignatures...)
r.TotalCount += uint64(len(results.ContractSignatures))
return uint64(len(results.ContractSignatures)), nil
}
// ListProjectsResponse: list projects response.
type ListProjectsResponse struct {
// TotalCount: total number of Projects.
TotalCount uint64 `json:"total_count"`
// Projects: paginated returned Projects.
Projects []*Project `json:"projects"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListProjectsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListProjectsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListProjectsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Projects = append(r.Projects, results.Projects...)
r.TotalCount += uint64(len(results.Projects))
return uint64(len(results.Projects)), nil
}
// ProjectAPICreateProjectRequest: project api create project request.
type ProjectAPICreateProjectRequest struct {
// Name: name of the Project.
Name string `json:"name"`
// OrganizationID: organization ID of the Project.
OrganizationID string `json:"organization_id"`
// Description: description of the Project.
Description string `json:"description"`
}
// ProjectAPIDeleteProjectRequest: project api delete project request.
type ProjectAPIDeleteProjectRequest struct {
// ProjectID: project ID of the Project.
ProjectID string `json:"-"`
}
// ProjectAPIGetProjectRequest: project api get project request.
type ProjectAPIGetProjectRequest struct {
// ProjectID: project ID of the Project.
ProjectID string `json:"-"`
}
// ProjectAPIListProjectsRequest: project api list projects request.
type ProjectAPIListProjectsRequest struct {
// OrganizationID: organization ID of the Project.
OrganizationID string `json:"-"`
// Name: name of the Project.
Name *string `json:"-"`
// Page: page number for the returned Projects.
Page *int32 `json:"-"`
// PageSize: maximum number of Project per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned Projects.
// Default value: created_at_asc
OrderBy ListProjectsRequestOrderBy `json:"-"`
// ProjectIDs: project IDs to filter for. The results will be limited to any Projects with an ID in this array.
ProjectIDs []string `json:"-"`
}
// ProjectAPIUpdateProjectRequest: project api update project request.
type ProjectAPIUpdateProjectRequest struct {
// ProjectID: project ID of the Project.
ProjectID string `json:"-"`
// Name: name of the Project.
Name *string `json:"name,omitempty"`
// Description: description of the Project.
Description *string `json:"description,omitempty"`
}
// The Contract API allows you to manage contracts.
type ContractAPI struct {
client *scw.Client
}
// NewContractAPI returns a ContractAPI object from a Scaleway client.
func NewContractAPI(client *scw.Client) *ContractAPI {
return &ContractAPI{
client: client,
}
}
// DownloadContractSignature: Download a contract content.
func (s *ContractAPI) DownloadContractSignature(req *ContractAPIDownloadContractSignatureRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "locale", req.Locale)
if fmt.Sprint(req.ContractSignatureID) == "" {
return nil, errors.New("field ContractSignatureID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/account/v3/contract-signatures/" + fmt.Sprint(req.ContractSignatureID) + "/download",
Query: query,
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateContractSignature: Create a signature for your Organization for the latest version of the requested contract.
func (s *ContractAPI) CreateContractSignature(req *ContractAPICreateContractSignatureRequest, opts ...scw.RequestOption) (*ContractSignature, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/account/v3/contract-signatures",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ContractSignature
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ValidateContractSignature: Sign a contract for your Organization.
func (s *ContractAPI) ValidateContractSignature(req *ContractAPIValidateContractSignatureRequest, opts ...scw.RequestOption) (*ContractSignature, error) {
var err error
if fmt.Sprint(req.ContractSignatureID) == "" {
return nil, errors.New("field ContractSignatureID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/account/v3/contract-signatures/" + fmt.Sprint(req.ContractSignatureID) + "/validate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ContractSignature
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckContractSignature: Check if a contract is signed for your Organization.
func (s *ContractAPI) CheckContractSignature(req *ContractAPICheckContractSignatureRequest, opts ...scw.RequestOption) (*CheckContractSignatureResponse, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/account/v3/contract-signatures/check",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckContractSignatureResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListContractSignatures: List contract signatures for an Organization.
func (s *ContractAPI) ListContractSignatures(req *ContractAPIListContractSignaturesRequest, opts ...scw.RequestOption) (*ListContractSignaturesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/account/v3/contract-signatures",
Query: query,
}
var resp ListContractSignaturesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your Scaleway Projects.
type ProjectAPI struct {
client *scw.Client
}
// NewProjectAPI returns a ProjectAPI object from a Scaleway client.
func NewProjectAPI(client *scw.Client) *ProjectAPI {
return &ProjectAPI{
client: client,
}
}
// CreateProject: Generate a new Project for an Organization, specifying its configuration including name and description.
func (s *ProjectAPI) CreateProject(req *ProjectAPICreateProjectRequest, opts ...scw.RequestOption) (*Project, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("proj")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/account/v3/projects",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Project
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListProjects: List all Projects of an Organization. The response will include the total number of Projects as well as their associated Organizations, names, and IDs. Other information includes the creation and update date of the Project.
func (s *ProjectAPI) ListProjects(req *ProjectAPIListProjectsRequest, opts ...scw.RequestOption) (*ListProjectsResponse, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_ids", req.ProjectIDs)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/account/v3/projects",
Query: query,
}
var resp ListProjectsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetProject: Retrieve information about an existing Project, specified by its Project ID. Its full details, including ID, name and description, are returned in the response object.
func (s *ProjectAPI) GetProject(req *ProjectAPIGetProjectRequest, opts ...scw.RequestOption) (*Project, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/account/v3/projects/" + fmt.Sprint(req.ProjectID) + "",
}
var resp Project
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteProject: Delete an existing Project, specified by its Project ID. The Project needs to be empty (meaning there are no resources left in it) to be deleted effectively. Note that deleting a Project is permanent, and cannot be undone.
func (s *ProjectAPI) DeleteProject(req *ProjectAPIDeleteProjectRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/account/v3/projects/" + fmt.Sprint(req.ProjectID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateProject: Update the parameters of an existing Project, specified by its Project ID. These parameters include the name and description.
func (s *ProjectAPI) UpdateProject(req *ProjectAPIUpdateProjectRequest, opts ...scw.RequestOption) (*Project, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/account/v3/projects/" + fmt.Sprint(req.ProjectID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Project
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/account/v3/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026636 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/account/v3/sweepers/sweepers.go 0000664 0000000 0000000 00000001753 14747113137 0031030 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/account/v3"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepProjects(scwClient *scw.Client) error {
accountAPI := account.NewProjectAPI(scwClient)
req := &account.ProjectAPIListProjectsRequest{}
listProjects, err := accountAPI.ListProjects(req, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
// Do not delete default project
if project.ID == req.OrganizationID || !testhelpers.IsTestResource(project.Name) {
continue
}
err = accountAPI.DeleteProject(&account.ProjectAPIDeleteProjectRequest{
ProjectID: project.ID,
})
if err != nil {
return fmt.Errorf("failed to delete project: %w", err)
}
}
return nil
}
func SweepAll(scwClient *scw.Client) error {
if err := SweepProjects(scwClient); err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/ 0000775 0000000 0000000 00000000000 14747113137 0025477 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0027114 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/v1alpha1/apple_silicon_utils.go0000664 0000000 0000000 00000007021 14747113137 0033504 0 ustar 00root root 0000000 0000000 package applesilicon
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 60 * time.Minute
)
// WaitForInstanceRequest is used by WaitForServer method.
type WaitForServerRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServer waits for the instance to be in a "terminal state" before returning.
// This function can be used to wait for an instance to be ready for example.
func (s *API) WaitForServer(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerStatus]struct{}{
ServerStatusReady: {},
ServerStatusError: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
func (s *API) WaitForPossibleDeletion(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
server, err := s.WaitForServer(&WaitForServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
Timeout: scw.TimeDurationPtr(defaultTimeout),
RetryInterval: scw.TimeDurationPtr(defaultRetryInterval),
}, opts...,
)
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
timeToDelete := *server.DeletableAt
time.Sleep(time.Until(timeToDelete))
return server, nil
}
func (s *PrivateNetworkAPI) WaitForServerPrivateNetworks(req *WaitForServerRequest, opts ...scw.RequestOption) ([]*ServerPrivateNetwork, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerPrivateNetworkServerStatus]struct{}{
ServerPrivateNetworkServerStatusAttached: {},
ServerPrivateNetworkServerStatusError: {},
ServerPrivateNetworkServerStatusUnknownStatus: {},
ServerPrivateNetworkServerStatusLocked: {},
}
serverPrivateNetworks, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.ListServerPrivateNetworks(&PrivateNetworkAPIListServerPrivateNetworksRequest{
Zone: req.Zone,
ServerID: &req.ServerID,
}, opts...)
if err != nil {
return nil, false, err
}
for _, serverPrivateNetwork := range res.ServerPrivateNetworks {
_, isTerminal := terminalStatus[serverPrivateNetwork.Status]
if !isTerminal {
return res.ServerPrivateNetworks, isTerminal, err
}
}
return res.ServerPrivateNetworks, true, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server private network failed")
}
return serverPrivateNetworks.([]*ServerPrivateNetwork), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/v1alpha1/applesilicon_sdk.go 0000664 0000000 0000000 00000132057 14747113137 0032776 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package applesilicon provides methods and message types of the applesilicon v1alpha1 API.
package applesilicon
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ConnectivityDiagnosticActionType string
const (
ConnectivityDiagnosticActionTypeRebootServer = ConnectivityDiagnosticActionType("reboot_server")
ConnectivityDiagnosticActionTypeReinstallServer = ConnectivityDiagnosticActionType("reinstall_server")
)
func (enum ConnectivityDiagnosticActionType) String() string {
if enum == "" {
// return default value if empty
return "reboot_server"
}
return string(enum)
}
func (enum ConnectivityDiagnosticActionType) Values() []ConnectivityDiagnosticActionType {
return []ConnectivityDiagnosticActionType{
"reboot_server",
"reinstall_server",
}
}
func (enum ConnectivityDiagnosticActionType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ConnectivityDiagnosticActionType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ConnectivityDiagnosticActionType(ConnectivityDiagnosticActionType(tmp).String())
return nil
}
type ConnectivityDiagnosticDiagnosticStatus string
const (
ConnectivityDiagnosticDiagnosticStatusUnknownStatus = ConnectivityDiagnosticDiagnosticStatus("unknown_status")
ConnectivityDiagnosticDiagnosticStatusProcessing = ConnectivityDiagnosticDiagnosticStatus("processing")
ConnectivityDiagnosticDiagnosticStatusError = ConnectivityDiagnosticDiagnosticStatus("error")
ConnectivityDiagnosticDiagnosticStatusCompleted = ConnectivityDiagnosticDiagnosticStatus("completed")
)
func (enum ConnectivityDiagnosticDiagnosticStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ConnectivityDiagnosticDiagnosticStatus) Values() []ConnectivityDiagnosticDiagnosticStatus {
return []ConnectivityDiagnosticDiagnosticStatus{
"unknown_status",
"processing",
"error",
"completed",
}
}
func (enum ConnectivityDiagnosticDiagnosticStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ConnectivityDiagnosticDiagnosticStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ConnectivityDiagnosticDiagnosticStatus(ConnectivityDiagnosticDiagnosticStatus(tmp).String())
return nil
}
type ListServerPrivateNetworksRequestOrderBy string
const (
ListServerPrivateNetworksRequestOrderByCreatedAtAsc = ListServerPrivateNetworksRequestOrderBy("created_at_asc")
ListServerPrivateNetworksRequestOrderByCreatedAtDesc = ListServerPrivateNetworksRequestOrderBy("created_at_desc")
ListServerPrivateNetworksRequestOrderByUpdatedAtAsc = ListServerPrivateNetworksRequestOrderBy("updated_at_asc")
ListServerPrivateNetworksRequestOrderByUpdatedAtDesc = ListServerPrivateNetworksRequestOrderBy("updated_at_desc")
)
func (enum ListServerPrivateNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerPrivateNetworksRequestOrderBy) Values() []ListServerPrivateNetworksRequestOrderBy {
return []ListServerPrivateNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListServerPrivateNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerPrivateNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerPrivateNetworksRequestOrderBy(ListServerPrivateNetworksRequestOrderBy(tmp).String())
return nil
}
type ListServersRequestOrderBy string
const (
ListServersRequestOrderByCreatedAtAsc = ListServersRequestOrderBy("created_at_asc")
ListServersRequestOrderByCreatedAtDesc = ListServersRequestOrderBy("created_at_desc")
)
func (enum ListServersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServersRequestOrderBy) Values() []ListServersRequestOrderBy {
return []ListServersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServersRequestOrderBy(ListServersRequestOrderBy(tmp).String())
return nil
}
type ServerPrivateNetworkServerStatus string
const (
ServerPrivateNetworkServerStatusUnknownStatus = ServerPrivateNetworkServerStatus("unknown_status")
ServerPrivateNetworkServerStatusAttaching = ServerPrivateNetworkServerStatus("attaching")
ServerPrivateNetworkServerStatusAttached = ServerPrivateNetworkServerStatus("attached")
ServerPrivateNetworkServerStatusError = ServerPrivateNetworkServerStatus("error")
ServerPrivateNetworkServerStatusDetaching = ServerPrivateNetworkServerStatus("detaching")
ServerPrivateNetworkServerStatusLocked = ServerPrivateNetworkServerStatus("locked")
)
func (enum ServerPrivateNetworkServerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ServerPrivateNetworkServerStatus) Values() []ServerPrivateNetworkServerStatus {
return []ServerPrivateNetworkServerStatus{
"unknown_status",
"attaching",
"attached",
"error",
"detaching",
"locked",
}
}
func (enum ServerPrivateNetworkServerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerPrivateNetworkServerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerPrivateNetworkServerStatus(ServerPrivateNetworkServerStatus(tmp).String())
return nil
}
type ServerPrivateNetworkStatus string
const (
ServerPrivateNetworkStatusVpcUnknownStatus = ServerPrivateNetworkStatus("vpc_unknown_status")
ServerPrivateNetworkStatusVpcEnabled = ServerPrivateNetworkStatus("vpc_enabled")
ServerPrivateNetworkStatusVpcUpdating = ServerPrivateNetworkStatus("vpc_updating")
ServerPrivateNetworkStatusVpcDisabled = ServerPrivateNetworkStatus("vpc_disabled")
)
func (enum ServerPrivateNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "vpc_unknown_status"
}
return string(enum)
}
func (enum ServerPrivateNetworkStatus) Values() []ServerPrivateNetworkStatus {
return []ServerPrivateNetworkStatus{
"vpc_unknown_status",
"vpc_enabled",
"vpc_updating",
"vpc_disabled",
}
}
func (enum ServerPrivateNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerPrivateNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerPrivateNetworkStatus(ServerPrivateNetworkStatus(tmp).String())
return nil
}
type ServerStatus string
const (
ServerStatusUnknownStatus = ServerStatus("unknown_status")
ServerStatusStarting = ServerStatus("starting")
ServerStatusReady = ServerStatus("ready")
ServerStatusError = ServerStatus("error")
ServerStatusRebooting = ServerStatus("rebooting")
ServerStatusUpdating = ServerStatus("updating")
ServerStatusLocking = ServerStatus("locking")
ServerStatusLocked = ServerStatus("locked")
ServerStatusUnlocking = ServerStatus("unlocking")
ServerStatusReinstalling = ServerStatus("reinstalling")
ServerStatusBusy = ServerStatus("busy")
)
func (enum ServerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ServerStatus) Values() []ServerStatus {
return []ServerStatus{
"unknown_status",
"starting",
"ready",
"error",
"rebooting",
"updating",
"locking",
"locked",
"unlocking",
"reinstalling",
"busy",
}
}
func (enum ServerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerStatus(ServerStatus(tmp).String())
return nil
}
type ServerTypeStock string
const (
ServerTypeStockUnknownStock = ServerTypeStock("unknown_stock")
ServerTypeStockNoStock = ServerTypeStock("no_stock")
ServerTypeStockLowStock = ServerTypeStock("low_stock")
ServerTypeStockHighStock = ServerTypeStock("high_stock")
)
func (enum ServerTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown_stock"
}
return string(enum)
}
func (enum ServerTypeStock) Values() []ServerTypeStock {
return []ServerTypeStock{
"unknown_stock",
"no_stock",
"low_stock",
"high_stock",
}
}
func (enum ServerTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerTypeStock(ServerTypeStock(tmp).String())
return nil
}
// OS: os.
type OS struct {
// ID: unique ID of the OS.
ID string `json:"id"`
// Name: oS name.
Name string `json:"name"`
// Label: oS name as it should be displayed.
Label string `json:"label"`
// ImageURL: URL of the image.
ImageURL string `json:"image_url"`
// Family: the OS family to which this OS belongs, eg. 13 or 14.
Family string `json:"family"`
// IsBeta: describes if the OS is in beta.
IsBeta bool `json:"is_beta"`
// Version: the OS version number, eg. Sonoma has version number 14.3.
Version string `json:"version"`
// XcodeVersion: the current xcode version for this OS.
XcodeVersion string `json:"xcode_version"`
// CompatibleServerTypes: list of compatible server types.
CompatibleServerTypes []string `json:"compatible_server_types"`
}
// ServerTypeCPU: server type cpu.
type ServerTypeCPU struct {
Name string `json:"name"`
CoreCount uint32 `json:"core_count"`
Frequency uint64 `json:"frequency"`
}
// ServerTypeDisk: server type disk.
type ServerTypeDisk struct {
Capacity scw.Size `json:"capacity"`
Type string `json:"type"`
}
// ServerTypeGPU: server type gpu.
type ServerTypeGPU struct {
Count uint64 `json:"count"`
}
// ServerTypeMemory: server type memory.
type ServerTypeMemory struct {
Capacity scw.Size `json:"capacity"`
Type string `json:"type"`
}
// ServerTypeNetwork: server type network.
type ServerTypeNetwork struct {
PublicBandwidthBps uint64 `json:"public_bandwidth_bps"`
}
// ConnectivityDiagnosticServerHealth: connectivity diagnostic server health.
type ConnectivityDiagnosticServerHealth struct {
LastCheckinDate *time.Time `json:"last_checkin_date"`
IsServerAlive bool `json:"is_server_alive"`
IsAgentAlive bool `json:"is_agent_alive"`
IsMdmAlive bool `json:"is_mdm_alive"`
IsSSHPortUp bool `json:"is_ssh_port_up"`
IsVncPortUp bool `json:"is_vnc_port_up"`
}
// ServerPrivateNetwork: server private network.
type ServerPrivateNetwork struct {
// ID: ID of the Server-to-Private Network mapping.
ID string `json:"id"`
// ProjectID: private Network Project ID.
ProjectID string `json:"project_id"`
// ServerID: apple silicon server ID.
ServerID string `json:"server_id"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"private_network_id"`
// Vlan: ID of the VLAN associated with the Private Network.
Vlan *uint32 `json:"vlan"`
// Status: configuration status of the Private Network.
// Default value: unknown_status
Status ServerPrivateNetworkServerStatus `json:"status"`
// CreatedAt: private Network creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the Private Network was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// IpamIPIDs: iPAM IP IDs of the server, if it has any.
IpamIPIDs []string `json:"ipam_ip_ids"`
}
// ServerType: server type.
type ServerType struct {
// CPU: CPU description.
CPU *ServerTypeCPU `json:"cpu"`
// Disk: size of the local disk of the server.
Disk *ServerTypeDisk `json:"disk"`
// Name: name of the type.
Name string `json:"name"`
// Memory: size of memory available.
Memory *ServerTypeMemory `json:"memory"`
// Stock: current stock.
// Default value: unknown_stock
Stock ServerTypeStock `json:"stock"`
// MinimumLeaseDuration: minimum duration of the lease in seconds (example. 3.4s).
MinimumLeaseDuration *scw.Duration `json:"minimum_lease_duration"`
// Gpu: gPU description.
Gpu *ServerTypeGPU `json:"gpu"`
// Network: network description.
Network *ServerTypeNetwork `json:"network"`
// DefaultOs: the default OS for this server type.
DefaultOs *OS `json:"default_os"`
}
// Server: server.
type Server struct {
// ID: UUID of the server.
ID string `json:"id"`
// Type: type of the server.
Type string `json:"type"`
// Name: name of the server.
Name string `json:"name"`
// ProjectID: project this server is associated with.
ProjectID string `json:"project_id"`
// OrganizationID: organization this server is associated with.
OrganizationID string `json:"organization_id"`
// IP: iPv4 address of the server.
IP net.IP `json:"ip"`
// VncURL: vnc:// URL to access Apple Remote Desktop.
VncURL string `json:"vnc_url"`
// SSHUsername: SSH Username for remote shell.
SSHUsername string `json:"ssh_username"`
// SudoPassword: admin password required to execute commands.
SudoPassword string `json:"sudo_password"`
// VncPort: vNC port to use for remote desktop connection.
VncPort uint32 `json:"vnc_port"`
// Os: initially installed OS, this does not necessarily reflect the current OS version.
Os *OS `json:"os"`
// Status: current status of the server.
// Default value: unknown_status
Status ServerStatus `json:"status"`
// CreatedAt: date on which the server was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the server was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// DeletableAt: date from which the server can be deleted.
DeletableAt *time.Time `json:"deletable_at"`
// DeletionScheduled: set to true to mark the server for automatic deletion depending on `deletable_at` date. Set to false to cancel an existing deletion schedule. Leave unset otherwise.
DeletionScheduled bool `json:"deletion_scheduled"`
// Zone: zone of the server.
Zone scw.Zone `json:"zone"`
// Delivered: set to true once the server has completed its provisioning steps and is ready to use. Some OS configurations might require a reinstallation of the server before delivery depending on the available stock. A reinstallation after the initial delivery will not change this flag and can be tracked using the server status.
Delivered bool `json:"delivered"`
// VpcStatus: activation status of optional Private Network feature support for this server.
// Default value: vpc_unknown_status
VpcStatus ServerPrivateNetworkStatus `json:"vpc_status"`
}
// ConnectivityDiagnostic: connectivity diagnostic.
type ConnectivityDiagnostic struct {
ID string `json:"id"`
// Status: default value: unknown_status
Status ConnectivityDiagnosticDiagnosticStatus `json:"status"`
IsHealthy bool `json:"is_healthy"`
HealthDetails *ConnectivityDiagnosticServerHealth `json:"health_details"`
SupportedActions []ConnectivityDiagnosticActionType `json:"supported_actions"`
ErrorMessage string `json:"error_message"`
}
// CreateServerRequest: create server request.
type CreateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: create a server with this given name.
Name string `json:"name"`
// ProjectID: create a server in the given project ID.
ProjectID string `json:"project_id"`
// Type: create a server of the given type.
Type string `json:"type"`
// OsID: create a server & install the given os_id, when no os_id provided the default OS for this server type is chosen. Requesting a non-default OS will induce an extended delivery time.
OsID *string `json:"os_id,omitempty"`
// EnableVpc: activate the Private Network feature for this server. This feature is configured through the Apple Silicon - Private Networks API.
EnableVpc bool `json:"enable_vpc"`
}
// DeleteServerRequest: delete server request.
type DeleteServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server you want to delete.
ServerID string `json:"-"`
}
// GetConnectivityDiagnosticRequest: get connectivity diagnostic request.
type GetConnectivityDiagnosticRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
DiagnosticID string `json:"-"`
}
// GetOSRequest: get os request.
type GetOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OsID: UUID of the OS you want to get.
OsID string `json:"-"`
}
// GetServerRequest: get server request.
type GetServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server you want to get.
ServerID string `json:"-"`
}
// GetServerTypeRequest: get server type request.
type GetServerTypeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerType: server type identifier.
ServerType string `json:"-"`
}
// ListOSRequest: list os request.
type ListOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: positive integer to choose the page to return.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// ServerType: list of compatible server types.
ServerType *string `json:"-"`
// Name: filter OS by name (note that "11.1" will return "11.1.2" and "11.1" but not "12")).
Name *string `json:"-"`
}
// ListOSResponse: list os response.
type ListOSResponse struct {
// TotalCount: total number of OS.
TotalCount uint32 `json:"total_count"`
// Os: list of OS.
Os []*OS `json:"os"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOSResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Os = append(r.Os, results.Os...)
r.TotalCount += uint32(len(results.Os))
return uint32(len(results.Os)), nil
}
// ListServerPrivateNetworksResponse: list server private networks response.
type ListServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListServerPrivateNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ServerPrivateNetworks = append(r.ServerPrivateNetworks, results.ServerPrivateNetworks...)
r.TotalCount += uint64(len(results.ServerPrivateNetworks))
return uint64(len(results.ServerPrivateNetworks)), nil
}
// ListServerTypesRequest: list server types request.
type ListServerTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
}
// ListServerTypesResponse: list server types response.
type ListServerTypesResponse struct {
// ServerTypes: available server types.
ServerTypes []*ServerType `json:"server_types"`
}
// ListServersRequest: list servers request.
type ListServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order of the returned servers.
// Default value: created_at_asc
OrderBy ListServersRequestOrderBy `json:"-"`
// ProjectID: only list servers of this project ID.
ProjectID *string `json:"-"`
// OrganizationID: only list servers of this Organization ID.
OrganizationID *string `json:"-"`
// Page: positive integer to choose the page to return.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
}
// ListServersResponse: list servers response.
type ListServersResponse struct {
// TotalCount: total number of servers.
TotalCount uint32 `json:"total_count"`
// Servers: paginated returned servers.
Servers []*Server `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// PrivateNetworkAPIAddServerPrivateNetworkRequest: private network api add server private network request.
type PrivateNetworkAPIAddServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: ID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
// IpamIPIDs: iPAM IDs of IPs to attach to the server.
IpamIPIDs []string `json:"ipam_ip_ids"`
}
// PrivateNetworkAPIDeleteServerPrivateNetworkRequest: private network api delete server private network request.
type PrivateNetworkAPIDeleteServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: ID of the Private Network.
PrivateNetworkID string `json:"-"`
}
// PrivateNetworkAPIGetServerPrivateNetworkRequest: private network api get server private network request.
type PrivateNetworkAPIGetServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
PrivateNetworkID string `json:"-"`
}
// PrivateNetworkAPIListServerPrivateNetworksRequest: private network api list server private networks request.
type PrivateNetworkAPIListServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order for the returned Private Networks.
// Default value: created_at_asc
OrderBy ListServerPrivateNetworksRequestOrderBy `json:"-"`
// Page: page number for the returned Private Networks.
Page *int32 `json:"-"`
// PageSize: maximum number of Private Networks per page.
PageSize *uint32 `json:"-"`
// ServerID: filter Private Networks by server ID.
ServerID *string `json:"-"`
// PrivateNetworkID: filter Private Networks by Private Network ID.
PrivateNetworkID *string `json:"-"`
// OrganizationID: filter Private Networks by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter Private Networks by Project ID.
ProjectID *string `json:"-"`
// IpamIPIDs: filter Private Networks by IPAM IP IDs.
IpamIPIDs []string `json:"-"`
}
// PrivateNetworkAPISetServerPrivateNetworksRequest: private network api set server private networks request.
type PrivateNetworkAPISetServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// PerPrivateNetworkIpamIPIDs: object where the keys are the IDs of Private Networks and the values are arrays of IPAM IDs representing the IPs to assign to this Apple silicon server on the Private Network. If the array supplied for a Private Network is empty, the next available IP from the Private Network's CIDR block will automatically be used for attachment.
PerPrivateNetworkIpamIPIDs map[string]*[]string `json:"per_private_network_ipam_ip_ids"`
}
// RebootServerRequest: reboot server request.
type RebootServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server you want to reboot.
ServerID string `json:"-"`
}
// ReinstallServerRequest: reinstall server request.
type ReinstallServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server you want to reinstall.
ServerID string `json:"-"`
// OsID: reinstall the server with the target OS, when no os_id provided the default OS for the server type is used.
OsID *string `json:"os_id,omitempty"`
}
// SetServerPrivateNetworksResponse: set server private networks response.
type SetServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
}
// StartConnectivityDiagnosticRequest: start connectivity diagnostic request.
type StartConnectivityDiagnosticRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"server_id"`
}
// StartConnectivityDiagnosticResponse: start connectivity diagnostic response.
type StartConnectivityDiagnosticResponse struct {
DiagnosticID string `json:"diagnostic_id"`
}
// UpdateServerRequest: update server request.
type UpdateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server you want to update.
ServerID string `json:"-"`
// Name: updated name for your server.
Name *string `json:"name,omitempty"`
// ScheduleDeletion: specify whether the server should be flagged for automatic deletion.
ScheduleDeletion *bool `json:"schedule_deletion,omitempty"`
// EnableVpc: activate or deactivate Private Network support for this server.
EnableVpc *bool `json:"enable_vpc,omitempty"`
}
// This API allows you to manage your Apple silicon machines.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar3}
}
// ListServerTypes: List all technical details about Apple silicon server types available in the specified zone. Since there is only one Availability Zone for Apple silicon servers, the targeted value is `fr-par-3`.
func (s *API) ListServerTypes(req *ListServerTypesRequest, opts ...scw.RequestOption) (*ListServerTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/server-types",
}
var resp ListServerTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServerType: Get technical details (CPU, disk size etc.) of a server type.
func (s *API) GetServerType(req *GetServerTypeRequest, opts ...scw.RequestOption) (*ServerType, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerType) == "" {
return nil, errors.New("field ServerType cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/server-type/" + fmt.Sprint(req.ServerType) + "",
}
var resp ServerType
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateServer: Create a new server in the targeted zone, specifying its configuration including name and type.
func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("as")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServers: List all servers in the specified zone. By default, returned servers in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers",
Query: query,
}
var resp ListServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOS: List all Operating Systems (OS). The response will include the total number of OS as well as their associated IDs, names and labels.
func (s *API) ListOS(req *ListOSRequest, opts ...scw.RequestOption) (*ListOSResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "server_type", req.ServerType)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/os",
Query: query,
}
var resp ListOSResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOS: Get an Operating System (OS). The response will include the OS's unique ID as well as its name and label.
func (s *API) GetOS(req *GetOSRequest, opts ...scw.RequestOption) (*OS, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OsID) == "" {
return nil, errors.New("field OsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/os/" + fmt.Sprint(req.OsID) + "",
}
var resp OS
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServer: Retrieve information about an existing Apple silicon server, specified by its server ID. Its full details, including name, status and IP address, are returned in the response object.
func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateServer: Update the parameters of an existing Apple silicon server, specified by its server ID.
func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServer: Delete an existing Apple silicon server, specified by its server ID. Deleting a server is permanent, and cannot be undone. Note that the minimum allocation period for Apple silicon-as-a-service is 24 hours, meaning you cannot delete your server prior to that.
func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RebootServer: Reboot an existing Apple silicon server, specified by its server ID.
func (s *API) RebootServer(req *RebootServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/reboot",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ReinstallServer: Reinstall an existing Apple silicon server (specified by its server ID) from a new image (OS). All the data on the disk is deleted and all configuration is reset to the defailt configuration values of the image (OS).
func (s *API) ReinstallServer(req *ReinstallServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/reinstall",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StartConnectivityDiagnostic:
func (s *API) StartConnectivityDiagnostic(req *StartConnectivityDiagnosticRequest, opts ...scw.RequestOption) (*StartConnectivityDiagnosticResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/connectivity-diagnostics",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp StartConnectivityDiagnosticResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetConnectivityDiagnostic:
func (s *API) GetConnectivityDiagnostic(req *GetConnectivityDiagnosticRequest, opts ...scw.RequestOption) (*ConnectivityDiagnostic, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DiagnosticID) == "" {
return nil, errors.New("field DiagnosticID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/connectivity-diagnostics/" + fmt.Sprint(req.DiagnosticID) + "",
}
var resp ConnectivityDiagnostic
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Apple silicon - Private Networks API.
type PrivateNetworkAPI struct {
client *scw.Client
}
// NewPrivateNetworkAPI returns a PrivateNetworkAPI object from a Scaleway client.
func NewPrivateNetworkAPI(client *scw.Client) *PrivateNetworkAPI {
return &PrivateNetworkAPI{
client: client,
}
}
func (s *PrivateNetworkAPI) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar3}
}
// GetServerPrivateNetwork:
func (s *PrivateNetworkAPI) GetServerPrivateNetwork(req *PrivateNetworkAPIGetServerPrivateNetworkRequest, opts ...scw.RequestOption) (*ServerPrivateNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
var resp ServerPrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddServerPrivateNetwork: Add an Apple silicon server to a Private Network.
func (s *PrivateNetworkAPI) AddServerPrivateNetwork(req *PrivateNetworkAPIAddServerPrivateNetworkRequest, opts ...scw.RequestOption) (*ServerPrivateNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ServerPrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetServerPrivateNetworks: Configure multiple Private Networks on an Apple silicon server.
func (s *PrivateNetworkAPI) SetServerPrivateNetworks(req *PrivateNetworkAPISetServerPrivateNetworksRequest, opts ...scw.RequestOption) (*SetServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerPrivateNetworks: List the Private Networks of an Apple silicon server.
func (s *PrivateNetworkAPI) ListServerPrivateNetworks(req *PrivateNetworkAPIListServerPrivateNetworksRequest, opts ...scw.RequestOption) (*ListServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "server_id", req.ServerID)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "ipam_ip_ids", req.IpamIPIDs)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/server-private-networks",
Query: query,
}
var resp ListServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServerPrivateNetwork: Delete a Private Network.
func (s *PrivateNetworkAPI) DeleteServerPrivateNetwork(req *PrivateNetworkAPIDeleteServerPrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/apple-silicon/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0030751 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/applesilicon/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000001716 14747113137 0033142 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
applesilicon "github.com/scaleway/scaleway-sdk-go/api/applesilicon/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepServer(scwClient *scw.Client, zone scw.Zone) error {
asAPI := applesilicon.NewAPI(scwClient)
listServers, err := asAPI.ListServers(&applesilicon.ListServersRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing apple silicon servers in (%s) in sweeper: %s", zone, err)
}
for _, server := range listServers.Servers {
errDelete := asAPI.DeleteServer(&applesilicon.DeleteServerRequest{
ServerID: server.ID,
Zone: zone,
})
if errDelete != nil {
return fmt.Errorf("error deleting apple silicon server in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&applesilicon.API{}).Zones() {
err := SweepServer(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/audit_trail/ 0000775 0000000 0000000 00000000000 14747113137 0025316 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/audit_trail/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0026733 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/audit_trail/v1alpha1/audit_trail_sdk.go 0000664 0000000 0000000 00000031276 14747113137 0032435 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package audit_trail provides methods and message types of the audit_trail v1alpha1 API.
package audit_trail
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListEventsRequestOrderBy string
const (
ListEventsRequestOrderByRecordedAtDesc = ListEventsRequestOrderBy("recorded_at_desc")
ListEventsRequestOrderByRecordedAtAsc = ListEventsRequestOrderBy("recorded_at_asc")
)
func (enum ListEventsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "recorded_at_desc"
}
return string(enum)
}
func (enum ListEventsRequestOrderBy) Values() []ListEventsRequestOrderBy {
return []ListEventsRequestOrderBy{
"recorded_at_desc",
"recorded_at_asc",
}
}
func (enum ListEventsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListEventsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListEventsRequestOrderBy(ListEventsRequestOrderBy(tmp).String())
return nil
}
type ResourceType string
const (
ResourceTypeUnknownType = ResourceType("unknown_type")
ResourceTypeSecmSecret = ResourceType("secm_secret")
ResourceTypeSecmSecretVersion = ResourceType("secm_secret_version")
ResourceTypeKubeCluster = ResourceType("kube_cluster")
ResourceTypeKubePool = ResourceType("kube_pool")
ResourceTypeKubeNode = ResourceType("kube_node")
ResourceTypeKubeACL = ResourceType("kube_acl")
)
func (enum ResourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ResourceType) Values() []ResourceType {
return []ResourceType{
"unknown_type",
"secm_secret",
"secm_secret_version",
"kube_cluster",
"kube_pool",
"kube_node",
"kube_acl",
}
}
func (enum ResourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ResourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ResourceType(ResourceType(tmp).String())
return nil
}
// KubernetesACLInfo: kubernetes acl info.
type KubernetesACLInfo struct {
}
// KubernetesClusterInfo: kubernetes cluster info.
type KubernetesClusterInfo struct {
}
// KubernetesNodeInfo: kubernetes node info.
type KubernetesNodeInfo struct {
ID string `json:"id"`
Name string `json:"name"`
}
// KubernetesPoolInfo: kubernetes pool info.
type KubernetesPoolInfo struct {
ID string `json:"id"`
Name string `json:"name"`
}
// SecretManagerSecretInfo: secret manager secret info.
type SecretManagerSecretInfo struct {
Path string `json:"path"`
}
// SecretManagerSecretVersionInfo: secret manager secret version info.
type SecretManagerSecretVersionInfo struct {
Revision uint32 `json:"revision"`
}
// EventPrincipal: event principal.
type EventPrincipal struct {
ID string `json:"id"`
}
// Resource: resource.
type Resource struct {
ID string `json:"id"`
// Type: default value: unknown_type
Type ResourceType `json:"type"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Name *string `json:"name"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
SecmSecretInfo *SecretManagerSecretInfo `json:"secm_secret_info,omitempty"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
SecmSecretVersionInfo *SecretManagerSecretVersionInfo `json:"secm_secret_version_info,omitempty"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
KubeClusterInfo *KubernetesClusterInfo `json:"kube_cluster_info,omitempty"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
KubePoolInfo *KubernetesPoolInfo `json:"kube_pool_info,omitempty"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
KubeNodeInfo *KubernetesNodeInfo `json:"kube_node_info,omitempty"`
// Precisely one of SecmSecretInfo, SecmSecretVersionInfo, KubeClusterInfo, KubePoolInfo, KubeNodeInfo, KubeACLInfo must be set.
KubeACLInfo *KubernetesACLInfo `json:"kube_acl_info,omitempty"`
}
// ProductService: product service.
type ProductService struct {
Name string `json:"name"`
Methods []string `json:"methods"`
}
// Event: event.
type Event struct {
// ID: ID of the event.
ID string `json:"id"`
// RecordedAt: timestamp of the event.
RecordedAt *time.Time `json:"recorded_at"`
// Locality: locality of the resource attached to the event.
Locality string `json:"locality"`
// Principal: user or IAM application at the origin of the event.
Principal *EventPrincipal `json:"principal"`
// OrganizationID: organization ID containing the event.
OrganizationID string `json:"organization_id"`
// ProjectID: (Optional) Project of the resource attached to the event.
ProjectID *string `json:"project_id"`
// SourceIP: IP address at the origin of the event.
SourceIP net.IP `json:"source_ip"`
// UserAgent: user Agent at the origin of the event.
UserAgent *string `json:"user_agent"`
// ProductName: product name of the resource attached to the event.
ProductName string `json:"product_name"`
// ServiceName: API name called to trigger the event.
ServiceName string `json:"service_name"`
// MethodName: API method called to trigger the event.
MethodName string `json:"method_name"`
// Resource: resource attached to the event.
Resource *Resource `json:"resource"`
// RequestID: unique identifier of the request at the origin of the event.
RequestID string `json:"request_id"`
// RequestBody: request at the origin of the event.
RequestBody *scw.JSONObject `json:"request_body"`
// StatusCode: HTTP status code resulting of the API call.
StatusCode uint32 `json:"status_code"`
}
// Product: product.
type Product struct {
// Title: product title.
Title string `json:"title"`
// Name: product name.
Name string `json:"name"`
// Services: specifies the API versions of the products integrated with Audit Trail. Each version defines the methods logged by Audit Trail.
Services []*ProductService `json:"services"`
}
// ListEventsRequest: list events request.
type ListEventsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: (Optional) ID of the Project containing the Audit Trail events.
ProjectID *string `json:"-"`
// OrganizationID: ID of the Organization containing the Audit Trail events.
OrganizationID string `json:"-"`
// ResourceType: (Optional) Returns a paginated list of Scaleway resources' features.
// Default value: unknown_type
ResourceType ResourceType `json:"-"`
// MethodName: (Optional) Name of the method or the API call performed.
MethodName *string `json:"-"`
// Status: (Optional) HTTP status code of the request. Returns either `200` if the request was successful or `403` if the permission was denied.
Status *uint32 `json:"-"`
// RecordedAfter: (Optional) The `recorded_after` parameter defines the earliest timestamp from which Audit Trail events are retrieved. Returns `one hour ago` by default.
RecordedAfter *time.Time `json:"-"`
// RecordedBefore: (Optional) The `recorded_before` parameter defines the latest timestamp up to which Audit Trail events are retrieved. Returns `now` by default.
RecordedBefore *time.Time `json:"-"`
// OrderBy: default value: recorded_at_desc
OrderBy ListEventsRequestOrderBy `json:"-"`
PageSize *uint32 `json:"-"`
PageToken *string `json:"-"`
// ProductName: (Optional) Name of the Scaleway resource in a hyphenated format.
ProductName *string `json:"-"`
}
// ListEventsResponse: list events response.
type ListEventsResponse struct {
// Events: single page of events matching the requested criteria.
Events []*Event `json:"events"`
// NextPageToken: page token to use in following calls to keep listing.
NextPageToken *string `json:"next_page_token"`
}
// ListProductsRequest: list products request.
type ListProductsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// ListProductsResponse: list products response.
type ListProductsResponse struct {
// Products: list of all products integrated with Audit Trail.
Products []*Product `json:"products"`
// TotalCount: number of integrated products.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListProductsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListProductsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListProductsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Products = append(r.Products, results.Products...)
r.TotalCount += uint64(len(results.Products))
return uint64(len(results.Products)), nil
}
// This API allows you to ensure accountability and security by recording events and changes performed within your Scaleway Organization.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms}
}
// ListEvents: Retrieve the list of Audit Trail events for a Scaleway Organization and/or Project. You must specify the `organization_id` and optionally, the `project_id`.
func (s *API) ListEvents(req *ListEventsRequest, opts ...scw.RequestOption) (*ListEventsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "resource_type", req.ResourceType)
parameter.AddToQuery(query, "method_name", req.MethodName)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "recorded_after", req.RecordedAfter)
parameter.AddToQuery(query, "recorded_before", req.RecordedBefore)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page_token", req.PageToken)
parameter.AddToQuery(query, "product_name", req.ProductName)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/audit-trail/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/events",
Query: query,
}
var resp ListEventsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListProducts: Retrieve the list of Scaleway resources for which you have Audit Trail events.
func (s *API) ListProducts(req *ListProductsRequest, opts ...scw.RequestOption) (*ListProductsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/audit-trail/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/products",
}
var resp ListProductsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/ 0000775 0000000 0000000 00000000000 14747113137 0024751 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v1/ 0000775 0000000 0000000 00000000000 14747113137 0025277 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v1/baremetal_sdk.go 0000664 0000000 0000000 00000260304 14747113137 0030430 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package baremetal provides methods and message types of the baremetal v1 API.
package baremetal
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type IPReverseStatus string
const (
IPReverseStatusUnknown = IPReverseStatus("unknown")
IPReverseStatusPending = IPReverseStatus("pending")
IPReverseStatusActive = IPReverseStatus("active")
IPReverseStatusError = IPReverseStatus("error")
)
func (enum IPReverseStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum IPReverseStatus) Values() []IPReverseStatus {
return []IPReverseStatus{
"unknown",
"pending",
"active",
"error",
}
}
func (enum IPReverseStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPReverseStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPReverseStatus(IPReverseStatus(tmp).String())
return nil
}
type IPVersion string
const (
IPVersionIPv4 = IPVersion("IPv4")
IPVersionIPv6 = IPVersion("IPv6")
)
func (enum IPVersion) String() string {
if enum == "" {
// return default value if empty
return "IPv4"
}
return string(enum)
}
func (enum IPVersion) Values() []IPVersion {
return []IPVersion{
"IPv4",
"IPv6",
}
}
func (enum IPVersion) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPVersion) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPVersion(IPVersion(tmp).String())
return nil
}
type ListServerEventsRequestOrderBy string
const (
ListServerEventsRequestOrderByCreatedAtAsc = ListServerEventsRequestOrderBy("created_at_asc")
ListServerEventsRequestOrderByCreatedAtDesc = ListServerEventsRequestOrderBy("created_at_desc")
)
func (enum ListServerEventsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerEventsRequestOrderBy) Values() []ListServerEventsRequestOrderBy {
return []ListServerEventsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServerEventsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerEventsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerEventsRequestOrderBy(ListServerEventsRequestOrderBy(tmp).String())
return nil
}
type ListServerPrivateNetworksRequestOrderBy string
const (
ListServerPrivateNetworksRequestOrderByCreatedAtAsc = ListServerPrivateNetworksRequestOrderBy("created_at_asc")
ListServerPrivateNetworksRequestOrderByCreatedAtDesc = ListServerPrivateNetworksRequestOrderBy("created_at_desc")
ListServerPrivateNetworksRequestOrderByUpdatedAtAsc = ListServerPrivateNetworksRequestOrderBy("updated_at_asc")
ListServerPrivateNetworksRequestOrderByUpdatedAtDesc = ListServerPrivateNetworksRequestOrderBy("updated_at_desc")
)
func (enum ListServerPrivateNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerPrivateNetworksRequestOrderBy) Values() []ListServerPrivateNetworksRequestOrderBy {
return []ListServerPrivateNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListServerPrivateNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerPrivateNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerPrivateNetworksRequestOrderBy(ListServerPrivateNetworksRequestOrderBy(tmp).String())
return nil
}
type ListServersRequestOrderBy string
const (
ListServersRequestOrderByCreatedAtAsc = ListServersRequestOrderBy("created_at_asc")
ListServersRequestOrderByCreatedAtDesc = ListServersRequestOrderBy("created_at_desc")
)
func (enum ListServersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServersRequestOrderBy) Values() []ListServersRequestOrderBy {
return []ListServersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServersRequestOrderBy(ListServersRequestOrderBy(tmp).String())
return nil
}
type ListSettingsRequestOrderBy string
const (
ListSettingsRequestOrderByCreatedAtAsc = ListSettingsRequestOrderBy("created_at_asc")
ListSettingsRequestOrderByCreatedAtDesc = ListSettingsRequestOrderBy("created_at_desc")
)
func (enum ListSettingsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSettingsRequestOrderBy) Values() []ListSettingsRequestOrderBy {
return []ListSettingsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListSettingsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSettingsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSettingsRequestOrderBy(ListSettingsRequestOrderBy(tmp).String())
return nil
}
type OfferStock string
const (
OfferStockEmpty = OfferStock("empty")
OfferStockLow = OfferStock("low")
OfferStockAvailable = OfferStock("available")
)
func (enum OfferStock) String() string {
if enum == "" {
// return default value if empty
return "empty"
}
return string(enum)
}
func (enum OfferStock) Values() []OfferStock {
return []OfferStock{
"empty",
"low",
"available",
}
}
func (enum OfferStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferStock(OfferStock(tmp).String())
return nil
}
type OfferSubscriptionPeriod string
const (
OfferSubscriptionPeriodUnknownSubscriptionPeriod = OfferSubscriptionPeriod("unknown_subscription_period")
OfferSubscriptionPeriodHourly = OfferSubscriptionPeriod("hourly")
OfferSubscriptionPeriodMonthly = OfferSubscriptionPeriod("monthly")
)
func (enum OfferSubscriptionPeriod) String() string {
if enum == "" {
// return default value if empty
return "unknown_subscription_period"
}
return string(enum)
}
func (enum OfferSubscriptionPeriod) Values() []OfferSubscriptionPeriod {
return []OfferSubscriptionPeriod{
"unknown_subscription_period",
"hourly",
"monthly",
}
}
func (enum OfferSubscriptionPeriod) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferSubscriptionPeriod) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferSubscriptionPeriod(OfferSubscriptionPeriod(tmp).String())
return nil
}
type SchemaFilesystemFormat string
const (
SchemaFilesystemFormatUnknownFormat = SchemaFilesystemFormat("unknown_format")
SchemaFilesystemFormatFat32 = SchemaFilesystemFormat("fat32")
SchemaFilesystemFormatExt4 = SchemaFilesystemFormat("ext4")
SchemaFilesystemFormatSwap = SchemaFilesystemFormat("swap")
SchemaFilesystemFormatZfs = SchemaFilesystemFormat("zfs")
SchemaFilesystemFormatXfs = SchemaFilesystemFormat("xfs")
)
func (enum SchemaFilesystemFormat) String() string {
if enum == "" {
// return default value if empty
return "unknown_format"
}
return string(enum)
}
func (enum SchemaFilesystemFormat) Values() []SchemaFilesystemFormat {
return []SchemaFilesystemFormat{
"unknown_format",
"fat32",
"ext4",
"swap",
"zfs",
"xfs",
}
}
func (enum SchemaFilesystemFormat) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SchemaFilesystemFormat) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SchemaFilesystemFormat(SchemaFilesystemFormat(tmp).String())
return nil
}
type SchemaPartitionLabel string
const (
SchemaPartitionLabelUnknownPartitionLabel = SchemaPartitionLabel("unknown_partition_label")
SchemaPartitionLabelUefi = SchemaPartitionLabel("uefi")
SchemaPartitionLabelLegacy = SchemaPartitionLabel("legacy")
SchemaPartitionLabelRoot = SchemaPartitionLabel("root")
SchemaPartitionLabelBoot = SchemaPartitionLabel("boot")
SchemaPartitionLabelSwap = SchemaPartitionLabel("swap")
SchemaPartitionLabelData = SchemaPartitionLabel("data")
SchemaPartitionLabelHome = SchemaPartitionLabel("home")
SchemaPartitionLabelRaid = SchemaPartitionLabel("raid")
SchemaPartitionLabelZfs = SchemaPartitionLabel("zfs")
)
func (enum SchemaPartitionLabel) String() string {
if enum == "" {
// return default value if empty
return "unknown_partition_label"
}
return string(enum)
}
func (enum SchemaPartitionLabel) Values() []SchemaPartitionLabel {
return []SchemaPartitionLabel{
"unknown_partition_label",
"uefi",
"legacy",
"root",
"boot",
"swap",
"data",
"home",
"raid",
"zfs",
}
}
func (enum SchemaPartitionLabel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SchemaPartitionLabel) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SchemaPartitionLabel(SchemaPartitionLabel(tmp).String())
return nil
}
type SchemaPoolType string
const (
SchemaPoolTypeUnknownType = SchemaPoolType("unknown_type")
SchemaPoolTypeNoRaid = SchemaPoolType("no_raid")
SchemaPoolTypeMirror = SchemaPoolType("mirror")
SchemaPoolTypeRaidz1 = SchemaPoolType("raidz1")
SchemaPoolTypeRaidz2 = SchemaPoolType("raidz2")
)
func (enum SchemaPoolType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum SchemaPoolType) Values() []SchemaPoolType {
return []SchemaPoolType{
"unknown_type",
"no_raid",
"mirror",
"raidz1",
"raidz2",
}
}
func (enum SchemaPoolType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SchemaPoolType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SchemaPoolType(SchemaPoolType(tmp).String())
return nil
}
type SchemaRAIDLevel string
const (
SchemaRAIDLevelUnknownRaidLevel = SchemaRAIDLevel("unknown_raid_level")
SchemaRAIDLevelRaidLevel0 = SchemaRAIDLevel("raid_level_0")
SchemaRAIDLevelRaidLevel1 = SchemaRAIDLevel("raid_level_1")
SchemaRAIDLevelRaidLevel5 = SchemaRAIDLevel("raid_level_5")
SchemaRAIDLevelRaidLevel6 = SchemaRAIDLevel("raid_level_6")
SchemaRAIDLevelRaidLevel10 = SchemaRAIDLevel("raid_level_10")
)
func (enum SchemaRAIDLevel) String() string {
if enum == "" {
// return default value if empty
return "unknown_raid_level"
}
return string(enum)
}
func (enum SchemaRAIDLevel) Values() []SchemaRAIDLevel {
return []SchemaRAIDLevel{
"unknown_raid_level",
"raid_level_0",
"raid_level_1",
"raid_level_5",
"raid_level_6",
"raid_level_10",
}
}
func (enum SchemaRAIDLevel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SchemaRAIDLevel) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SchemaRAIDLevel(SchemaRAIDLevel(tmp).String())
return nil
}
type ServerBootType string
const (
ServerBootTypeUnknownBootType = ServerBootType("unknown_boot_type")
ServerBootTypeNormal = ServerBootType("normal")
ServerBootTypeRescue = ServerBootType("rescue")
)
func (enum ServerBootType) String() string {
if enum == "" {
// return default value if empty
return "unknown_boot_type"
}
return string(enum)
}
func (enum ServerBootType) Values() []ServerBootType {
return []ServerBootType{
"unknown_boot_type",
"normal",
"rescue",
}
}
func (enum ServerBootType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerBootType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerBootType(ServerBootType(tmp).String())
return nil
}
type ServerInstallStatus string
const (
ServerInstallStatusUnknown = ServerInstallStatus("unknown")
ServerInstallStatusToInstall = ServerInstallStatus("to_install")
ServerInstallStatusInstalling = ServerInstallStatus("installing")
ServerInstallStatusCompleted = ServerInstallStatus("completed")
ServerInstallStatusError = ServerInstallStatus("error")
)
func (enum ServerInstallStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServerInstallStatus) Values() []ServerInstallStatus {
return []ServerInstallStatus{
"unknown",
"to_install",
"installing",
"completed",
"error",
}
}
func (enum ServerInstallStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerInstallStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerInstallStatus(ServerInstallStatus(tmp).String())
return nil
}
type ServerOptionOptionStatus string
const (
ServerOptionOptionStatusOptionStatusUnknown = ServerOptionOptionStatus("option_status_unknown")
ServerOptionOptionStatusOptionStatusEnable = ServerOptionOptionStatus("option_status_enable")
ServerOptionOptionStatusOptionStatusEnabling = ServerOptionOptionStatus("option_status_enabling")
ServerOptionOptionStatusOptionStatusDisabling = ServerOptionOptionStatus("option_status_disabling")
ServerOptionOptionStatusOptionStatusError = ServerOptionOptionStatus("option_status_error")
)
func (enum ServerOptionOptionStatus) String() string {
if enum == "" {
// return default value if empty
return "option_status_unknown"
}
return string(enum)
}
func (enum ServerOptionOptionStatus) Values() []ServerOptionOptionStatus {
return []ServerOptionOptionStatus{
"option_status_unknown",
"option_status_enable",
"option_status_enabling",
"option_status_disabling",
"option_status_error",
}
}
func (enum ServerOptionOptionStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerOptionOptionStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerOptionOptionStatus(ServerOptionOptionStatus(tmp).String())
return nil
}
type ServerPingStatus string
const (
ServerPingStatusPingStatusUnknown = ServerPingStatus("ping_status_unknown")
ServerPingStatusPingStatusUp = ServerPingStatus("ping_status_up")
ServerPingStatusPingStatusDown = ServerPingStatus("ping_status_down")
)
func (enum ServerPingStatus) String() string {
if enum == "" {
// return default value if empty
return "ping_status_unknown"
}
return string(enum)
}
func (enum ServerPingStatus) Values() []ServerPingStatus {
return []ServerPingStatus{
"ping_status_unknown",
"ping_status_up",
"ping_status_down",
}
}
func (enum ServerPingStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerPingStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerPingStatus(ServerPingStatus(tmp).String())
return nil
}
type ServerPrivateNetworkStatus string
const (
ServerPrivateNetworkStatusUnknown = ServerPrivateNetworkStatus("unknown")
ServerPrivateNetworkStatusAttaching = ServerPrivateNetworkStatus("attaching")
ServerPrivateNetworkStatusAttached = ServerPrivateNetworkStatus("attached")
ServerPrivateNetworkStatusError = ServerPrivateNetworkStatus("error")
ServerPrivateNetworkStatusDetaching = ServerPrivateNetworkStatus("detaching")
ServerPrivateNetworkStatusLocked = ServerPrivateNetworkStatus("locked")
)
func (enum ServerPrivateNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServerPrivateNetworkStatus) Values() []ServerPrivateNetworkStatus {
return []ServerPrivateNetworkStatus{
"unknown",
"attaching",
"attached",
"error",
"detaching",
"locked",
}
}
func (enum ServerPrivateNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerPrivateNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerPrivateNetworkStatus(ServerPrivateNetworkStatus(tmp).String())
return nil
}
type ServerStatus string
const (
ServerStatusUnknown = ServerStatus("unknown")
ServerStatusDelivering = ServerStatus("delivering")
ServerStatusReady = ServerStatus("ready")
ServerStatusStopping = ServerStatus("stopping")
ServerStatusStopped = ServerStatus("stopped")
ServerStatusStarting = ServerStatus("starting")
ServerStatusError = ServerStatus("error")
ServerStatusDeleting = ServerStatus("deleting")
ServerStatusLocked = ServerStatus("locked")
ServerStatusOutOfStock = ServerStatus("out_of_stock")
ServerStatusOrdered = ServerStatus("ordered")
ServerStatusResetting = ServerStatus("resetting")
)
func (enum ServerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServerStatus) Values() []ServerStatus {
return []ServerStatus{
"unknown",
"delivering",
"ready",
"stopping",
"stopped",
"starting",
"error",
"deleting",
"locked",
"out_of_stock",
"ordered",
"resetting",
}
}
func (enum ServerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerStatus(ServerStatus(tmp).String())
return nil
}
type SettingType string
const (
SettingTypeUnknown = SettingType("unknown")
SettingTypeSMTP = SettingType("smtp")
)
func (enum SettingType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum SettingType) Values() []SettingType {
return []SettingType{
"unknown",
"smtp",
}
}
func (enum SettingType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SettingType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SettingType(SettingType(tmp).String())
return nil
}
// SchemaPartition: schema partition.
type SchemaPartition struct {
// Label: default value: unknown_partition_label
Label SchemaPartitionLabel `json:"label"`
Number uint32 `json:"number"`
Size scw.Size `json:"size"`
}
// SchemaPool: schema pool.
type SchemaPool struct {
Name string `json:"name"`
// Type: default value: unknown_type
Type SchemaPoolType `json:"type"`
Devices []string `json:"devices"`
Options []string `json:"options"`
FilesystemOptions []string `json:"filesystem_options"`
}
// SchemaDisk: schema disk.
type SchemaDisk struct {
Device string `json:"device"`
Partitions []*SchemaPartition `json:"partitions"`
}
// SchemaFilesystem: schema filesystem.
type SchemaFilesystem struct {
Device string `json:"device"`
// Format: default value: unknown_format
Format SchemaFilesystemFormat `json:"format"`
Mountpoint string `json:"mountpoint"`
}
// SchemaRAID: schema raid.
type SchemaRAID struct {
Name string `json:"name"`
// Level: default value: unknown_raid_level
Level SchemaRAIDLevel `json:"level"`
Devices []string `json:"devices"`
}
// SchemaZFS: schema zfs.
type SchemaZFS struct {
Pools []*SchemaPool `json:"pools"`
}
// CertificationOption: certification option.
type CertificationOption struct {
}
// LicenseOption: license option.
type LicenseOption struct {
OsID string `json:"os_id"`
}
// PrivateNetworkOption: private network option.
type PrivateNetworkOption struct {
BandwidthInBps uint64 `json:"bandwidth_in_bps"`
}
// PublicBandwidthOption: public bandwidth option.
type PublicBandwidthOption struct {
BandwidthInBps uint64 `json:"bandwidth_in_bps"`
}
// RemoteAccessOption: remote access option.
type RemoteAccessOption struct {
}
// Schema: schema.
type Schema struct {
Disks []*SchemaDisk `json:"disks"`
Raids []*SchemaRAID `json:"raids"`
Filesystems []*SchemaFilesystem `json:"filesystems"`
Zfs *SchemaZFS `json:"zfs"`
}
// OSOSField: osos field.
type OSOSField struct {
Editable bool `json:"editable"`
Required bool `json:"required"`
DefaultValue *string `json:"default_value"`
}
// CPU: cpu.
type CPU struct {
// Name: name of the CPU.
Name string `json:"name"`
// CoreCount: number of CPU cores.
CoreCount uint32 `json:"core_count"`
// ThreadCount: number CPU threads.
ThreadCount uint32 `json:"thread_count"`
// Frequency: frequency of the CPU in MHz.
Frequency uint32 `json:"frequency"`
// Benchmark: benchmark of the CPU.
Benchmark string `json:"benchmark"`
}
// Disk: disk.
type Disk struct {
// Capacity: capacity of the disk in bytes.
Capacity scw.Size `json:"capacity"`
// Type: type of the disk.
Type string `json:"type"`
}
// GPU: gpu.
type GPU struct {
// Name: name of the GPU.
Name string `json:"name"`
// Vram: capacity of the vram in bytes.
Vram uint64 `json:"vram"`
}
// Memory: memory.
type Memory struct {
// Capacity: capacity of the memory in bytes.
Capacity scw.Size `json:"capacity"`
// Type: type of the memory.
Type string `json:"type"`
// Frequency: frequency of the memory in MHz.
Frequency uint32 `json:"frequency"`
// IsEcc: true if the memory is an error-correcting code memory.
IsEcc bool `json:"is_ecc"`
}
// OfferOptionOffer: offer option offer.
type OfferOptionOffer struct {
// ID: ID of the option.
ID string `json:"id"`
// Name: name of the option.
Name string `json:"name"`
// Enabled: if true the option is enabled and included by default in the offer
// If false the option is available for the offer but not included by default.
Enabled bool `json:"enabled"`
// SubscriptionPeriod: period of subscription for the offer.
// Default value: unknown_subscription_period
SubscriptionPeriod OfferSubscriptionPeriod `json:"subscription_period"`
// Price: price of the option.
Price *scw.Money `json:"price"`
// Manageable: boolean to know if option could be managed.
Manageable bool `json:"manageable"`
// Deprecated: OsID: deprecated, use LicenseOptionVars.os_id instead.
OsID *string `json:"os_id,omitempty"`
// License: license option, contains the ID of the OS linked to the option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
License *LicenseOption `json:"license,omitempty"`
// PublicBandwidth: public_bandwidth option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PublicBandwidth *PublicBandwidthOption `json:"public_bandwidth,omitempty"`
// PrivateNetwork: private_network option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PrivateNetwork *PrivateNetworkOption `json:"private_network,omitempty"`
// RemoteAccess: remote_access option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
RemoteAccess *RemoteAccessOption `json:"remote_access,omitempty"`
// Certification: certification option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
Certification *CertificationOption `json:"certification,omitempty"`
}
// PersistentMemory: persistent memory.
type PersistentMemory struct {
// Capacity: capacity of the memory in bytes.
Capacity scw.Size `json:"capacity"`
// Type: type of the memory.
Type string `json:"type"`
// Frequency: frequency of the memory in MHz.
Frequency uint32 `json:"frequency"`
}
// RaidController: raid controller.
type RaidController struct {
Model string `json:"model"`
RaidLevel []string `json:"raid_level"`
}
// IP: ip.
type IP struct {
// ID: ID of the IP.
ID string `json:"id"`
// Address: address of the IP.
Address net.IP `json:"address"`
// Reverse: reverse IP value.
Reverse string `json:"reverse"`
// Version: version of IP (v4 or v6).
// Default value: IPv4
Version IPVersion `json:"version"`
// ReverseStatus: status of the reverse.
// Default value: unknown
ReverseStatus IPReverseStatus `json:"reverse_status"`
// ReverseStatusMessage: a message related to the reverse status, e.g. in case of an error.
ReverseStatusMessage string `json:"reverse_status_message"`
}
// ServerInstall: server install.
type ServerInstall struct {
// OsID: ID of the OS.
OsID string `json:"os_id"`
// Hostname: host defined during the server installation.
Hostname string `json:"hostname"`
// SSHKeyIDs: SSH public key IDs defined during server installation.
SSHKeyIDs []string `json:"ssh_key_ids"`
// Status: status of the server installation.
// Default value: unknown
Status ServerInstallStatus `json:"status"`
// User: user defined in the server installation, or the default user if none were specified.
User string `json:"user"`
// ServiceUser: service user defined in the server installation, or the default user if none were specified.
ServiceUser string `json:"service_user"`
// ServiceURL: address of the installed service.
ServiceURL string `json:"service_url"`
// PartitioningSchema: partitioning schema.
PartitioningSchema *Schema `json:"partitioning_schema"`
}
// ServerOption: server option.
type ServerOption struct {
// ID: ID of the option.
ID string `json:"id"`
// Name: name of the option.
Name string `json:"name"`
// Status: status of the option on this server.
// Default value: option_status_unknown
Status ServerOptionOptionStatus `json:"status"`
// Manageable: defines whether the option can be managed (added or removed).
Manageable bool `json:"manageable"`
// ExpiresAt: auto expiration date for compatible options.
ExpiresAt *time.Time `json:"expires_at"`
// License: license option, contains the ID of the OS linked to the option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
License *LicenseOption `json:"license,omitempty"`
// PublicBandwidth: public_bandwidth option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PublicBandwidth *PublicBandwidthOption `json:"public_bandwidth,omitempty"`
// PrivateNetwork: private_network option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PrivateNetwork *PrivateNetworkOption `json:"private_network,omitempty"`
// RemoteAccess: remote_access option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
RemoteAccess *RemoteAccessOption `json:"remote_access,omitempty"`
// Certification: certification option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
Certification *CertificationOption `json:"certification,omitempty"`
}
// ServerRescueServer: server rescue server.
type ServerRescueServer struct {
// User: rescue user name.
User string `json:"user"`
// Password: rescue password.
Password string `json:"password"`
}
// CreateServerRequestInstall: create server request install.
type CreateServerRequestInstall struct {
// OsID: ID of the OS to installation on the server.
OsID string `json:"os_id"`
// Hostname: hostname of the server.
Hostname string `json:"hostname"`
// SSHKeyIDs: SSH key IDs authorized on the server.
SSHKeyIDs []string `json:"ssh_key_ids"`
// User: user for the installation.
User *string `json:"user"`
// Password: password for the installation.
Password *string `json:"password"`
// ServiceUser: regular user that runs the service to be installed on the server.
ServiceUser *string `json:"service_user"`
// ServicePassword: password used for the service to install.
ServicePassword *string `json:"service_password"`
// PartitioningSchema: partitioning schema.
PartitioningSchema *Schema `json:"partitioning_schema"`
}
// OS: os.
type OS struct {
// ID: ID of the OS.
ID string `json:"id"`
// Name: name of the OS.
Name string `json:"name"`
// Version: version of the OS.
Version string `json:"version"`
// LogoURL: URL of this OS's logo.
LogoURL string `json:"logo_url"`
// SSH: object defining the SSH requirements to install the OS.
SSH *OSOSField `json:"ssh"`
// User: object defining the username requirements to install the OS.
User *OSOSField `json:"user"`
// Password: object defining the password requirements to install the OS.
Password *OSOSField `json:"password"`
// ServiceUser: object defining the username requirements to install the service.
ServiceUser *OSOSField `json:"service_user"`
// ServicePassword: object defining the password requirements to install the service.
ServicePassword *OSOSField `json:"service_password"`
// Enabled: defines if the operating system is enabled or not.
Enabled bool `json:"enabled"`
// LicenseRequired: license required (check server options for pricing details).
LicenseRequired bool `json:"license_required"`
// Allowed: defines if a specific Organization is allowed to install this OS type.
Allowed bool `json:"allowed"`
// CustomPartitioningSupported: defines if custom partitioning is supported by this OS.
CustomPartitioningSupported bool `json:"custom_partitioning_supported"`
}
// Offer: offer.
type Offer struct {
// ID: ID of the offer.
ID string `json:"id"`
// Name: name of the offer.
Name string `json:"name"`
// Stock: stock level.
// Default value: empty
Stock OfferStock `json:"stock"`
// Bandwidth: public bandwidth available (in bits/s) with the offer.
Bandwidth uint64 `json:"bandwidth"`
// MaxBandwidth: maximum public bandwidth available (in bits/s) depending on available options.
MaxBandwidth uint64 `json:"max_bandwidth"`
// CommercialRange: commercial range of the offer.
CommercialRange string `json:"commercial_range"`
// PricePerHour: price of the offer for the next 60 minutes (a server order at 11h32 will be payed until 12h32).
PricePerHour *scw.Money `json:"price_per_hour"`
// PricePerMonth: monthly price of the offer, if subscribing on a monthly basis.
PricePerMonth *scw.Money `json:"price_per_month"`
// Disks: disks specifications of the offer.
Disks []*Disk `json:"disks"`
// Enable: defines whether the offer is currently available.
Enable bool `json:"enable"`
// CPUs: CPU specifications of the offer.
CPUs []*CPU `json:"cpus"`
// Memories: memory specifications of the offer.
Memories []*Memory `json:"memories"`
// QuotaName: name of the quota associated to the offer.
QuotaName string `json:"quota_name"`
// PersistentMemories: persistent memory specifications of the offer.
PersistentMemories []*PersistentMemory `json:"persistent_memories"`
// RaidControllers: raid controller specifications of the offer.
RaidControllers []*RaidController `json:"raid_controllers"`
// IncompatibleOsIDs: array of OS images IDs incompatible with the server.
IncompatibleOsIDs []string `json:"incompatible_os_ids"`
// SubscriptionPeriod: period of subscription for the offer.
// Default value: unknown_subscription_period
SubscriptionPeriod OfferSubscriptionPeriod `json:"subscription_period"`
// OperationPath: operation path of the service.
OperationPath string `json:"operation_path"`
// Fee: one time fee invoiced by Scaleway for the setup and activation of the server.
Fee *scw.Money `json:"fee"`
// Options: available options for customization of the server.
Options []*OfferOptionOffer `json:"options"`
// PrivateBandwidth: private bandwidth available in bits/s with the offer.
PrivateBandwidth uint64 `json:"private_bandwidth"`
// SharedBandwidth: defines whether the offer's bandwidth is shared or not.
SharedBandwidth bool `json:"shared_bandwidth"`
// Tags: array of tags attached to the offer.
Tags []string `json:"tags"`
// Gpus: gPU specifications of the offer.
Gpus []*GPU `json:"gpus"`
}
// Option: option.
type Option struct {
// ID: ID of the option.
ID string `json:"id"`
// Name: name of the option.
Name string `json:"name"`
// Manageable: defines whether the option is manageable (could be added or removed).
Manageable bool `json:"manageable"`
// License: license option, contains the ID of the OS linked to the option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
License *LicenseOption `json:"license,omitempty"`
// PublicBandwidth: public_bandwidth option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PublicBandwidth *PublicBandwidthOption `json:"public_bandwidth,omitempty"`
// PrivateNetwork: private_network option, contains the bandwidth_in_bps.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
PrivateNetwork *PrivateNetworkOption `json:"private_network,omitempty"`
// RemoteAccess: remote_access option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
RemoteAccess *RemoteAccessOption `json:"remote_access,omitempty"`
// Certification: certification option.
// Precisely one of License, PublicBandwidth, PrivateNetwork, RemoteAccess, Certification must be set.
Certification *CertificationOption `json:"certification,omitempty"`
}
// ServerEvent: server event.
type ServerEvent struct {
// ID: ID of the server to which the action will be applied.
ID string `json:"id"`
// Action: the action that will be applied to the server.
Action string `json:"action"`
// UpdatedAt: date of last modification of the action.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: date of creation of the action.
CreatedAt *time.Time `json:"created_at"`
}
// ServerPrivateNetwork: server private network.
type ServerPrivateNetwork struct {
// ID: the Private Network ID.
ID string `json:"id"`
// ProjectID: the Private Network Project ID.
ProjectID string `json:"project_id"`
// ServerID: the server ID.
ServerID string `json:"server_id"`
// PrivateNetworkID: the Private Network ID.
PrivateNetworkID string `json:"private_network_id"`
// Vlan: the VLAN ID associated to the Private Network.
Vlan *uint32 `json:"vlan"`
// Status: the configuration status of the Private Network.
// Default value: unknown
Status ServerPrivateNetworkStatus `json:"status"`
// CreatedAt: the Private Network creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: the date the Private Network was last modified.
UpdatedAt *time.Time `json:"updated_at"`
}
// Server: server.
type Server struct {
// ID: ID of the server.
ID string `json:"id"`
// OrganizationID: organization ID the server is attached to.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the server is attached to.
ProjectID string `json:"project_id"`
// Name: name of the server.
Name string `json:"name"`
// Description: description of the server.
Description string `json:"description"`
// UpdatedAt: last modification date of the server.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: creation date of the server.
CreatedAt *time.Time `json:"created_at"`
// Status: status of the server.
// Default value: unknown
Status ServerStatus `json:"status"`
// OfferID: offer ID of the server.
OfferID string `json:"offer_id"`
// OfferName: offer name of the server.
OfferName string `json:"offer_name"`
// Tags: array of custom tags attached to the server.
Tags []string `json:"tags"`
// IPs: array of IPs attached to the server.
IPs []*IP `json:"ips"`
// Domain: domain of the server.
Domain string `json:"domain"`
// BootType: boot type of the server.
// Default value: unknown_boot_type
BootType ServerBootType `json:"boot_type"`
// Zone: zone in which is the server located.
Zone scw.Zone `json:"zone"`
// Install: configuration of the installation.
Install *ServerInstall `json:"install"`
// PingStatus: status of server ping.
// Default value: ping_status_unknown
PingStatus ServerPingStatus `json:"ping_status"`
// Options: options enabled on the server.
Options []*ServerOption `json:"options"`
// RescueServer: configuration of rescue boot.
RescueServer *ServerRescueServer `json:"rescue_server"`
}
// Setting: setting.
type Setting struct {
// ID: ID of the setting.
ID string `json:"id"`
// Type: type of the setting.
// Default value: unknown
Type SettingType `json:"type"`
// ProjectID: ID of the Project ID.
ProjectID string `json:"project_id"`
// Enabled: defines whether the setting is enabled.
Enabled bool `json:"enabled"`
}
// AddOptionServerRequest: add option server request.
type AddOptionServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// OptionID: ID of the option to add.
OptionID string `json:"-"`
// ExpiresAt: auto expire the option after this date.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// BMCAccess: bmc access.
type BMCAccess struct {
// URL: URL to access to the server console.
URL string `json:"url"`
// Login: the login to use for the BMC (Baseboard Management Controller) access authentification.
Login string `json:"login"`
// Password: the password to use for the BMC (Baseboard Management Controller) access authentification.
Password string `json:"password"`
// ExpiresAt: the date after which the BMC (Baseboard Management Controller) access will be closed.
ExpiresAt *time.Time `json:"expires_at"`
}
// CreateServerRequest: create server request.
type CreateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: offer ID of the new server.
OfferID string `json:"offer_id"`
// Deprecated: OrganizationID: organization ID with which the server will be created.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID with which the server will be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Name: name of the server (â hostname).
Name string `json:"name"`
// Description: description associated with the server, max 255 characters.
Description string `json:"description"`
// Tags: tags to associate to the server.
Tags []string `json:"tags"`
// Install: object describing the configuration details of the OS installation on the server.
Install *CreateServerRequestInstall `json:"install,omitempty"`
// OptionIDs: iDs of options to enable on server.
OptionIDs []string `json:"option_ids"`
}
// DeleteOptionServerRequest: delete option server request.
type DeleteOptionServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// OptionID: ID of the option to delete.
OptionID string `json:"-"`
}
// DeleteServerRequest: delete server request.
type DeleteServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to delete.
ServerID string `json:"-"`
}
// GetBMCAccessRequest: get bmc access request.
type GetBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
}
// GetDefaultPartitioningSchemaRequest: get default partitioning schema request.
type GetDefaultPartitioningSchemaRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: ID of the offer.
OfferID string `json:"-"`
// OsID: ID of the OS.
OsID string `json:"-"`
}
// GetOSRequest: get os request.
type GetOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OsID: ID of the OS.
OsID string `json:"-"`
}
// GetOfferRequest: get offer request.
type GetOfferRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: ID of the researched Offer.
OfferID string `json:"-"`
}
// GetOptionRequest: get option request.
type GetOptionRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OptionID: ID of the option.
OptionID string `json:"-"`
}
// GetServerMetricsRequest: get server metrics request.
type GetServerMetricsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to get the metrics.
ServerID string `json:"-"`
}
// GetServerMetricsResponse: get server metrics response.
type GetServerMetricsResponse struct {
// Pings: timeseries object representing pings on the server.
Pings *scw.TimeSeries `json:"pings"`
}
// GetServerRequest: get server request.
type GetServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
}
// InstallServerRequest: install server request.
type InstallServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to install.
ServerID string `json:"-"`
// OsID: ID of the OS to installation on the server.
OsID string `json:"os_id"`
// Hostname: hostname of the server.
Hostname string `json:"hostname"`
// SSHKeyIDs: SSH key IDs authorized on the server.
SSHKeyIDs []string `json:"ssh_key_ids"`
// User: user used for the installation.
User *string `json:"user,omitempty"`
// Password: password used for the installation.
Password *string `json:"password,omitempty"`
// ServiceUser: user used for the service to install.
ServiceUser *string `json:"service_user,omitempty"`
// ServicePassword: password used for the service to install.
ServicePassword *string `json:"service_password,omitempty"`
// PartitioningSchema: partitioning schema.
PartitioningSchema *Schema `json:"partitioning_schema,omitempty"`
}
// ListOSRequest: list os request.
type ListOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of OS per page.
PageSize *uint32 `json:"-"`
// OfferID: offer IDs to filter OSes for.
OfferID *string `json:"-"`
}
// ListOSResponse: list os response.
type ListOSResponse struct {
// TotalCount: total count of matching OS.
TotalCount uint32 `json:"total_count"`
// Os: oS that match filters.
Os []*OS `json:"os"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOSResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Os = append(r.Os, results.Os...)
r.TotalCount += uint32(len(results.Os))
return uint32(len(results.Os)), nil
}
// ListOffersRequest: list offers request.
type ListOffersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of offers per page.
PageSize *uint32 `json:"-"`
// SubscriptionPeriod: subscription period type to filter offers by.
// Default value: unknown_subscription_period
SubscriptionPeriod OfferSubscriptionPeriod `json:"-"`
// Name: offer name to filter offers by.
Name *string `json:"-"`
}
// ListOffersResponse: list offers response.
type ListOffersResponse struct {
// TotalCount: total count of matching offers.
TotalCount uint32 `json:"total_count"`
// Offers: offers that match filters.
Offers []*Offer `json:"offers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOffersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Offers = append(r.Offers, results.Offers...)
r.TotalCount += uint32(len(results.Offers))
return uint32(len(results.Offers)), nil
}
// ListOptionsRequest: list options request.
type ListOptionsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of options per page.
PageSize *uint32 `json:"-"`
// OfferID: offer ID to filter options for.
OfferID *string `json:"-"`
// Name: name to filter options for.
Name *string `json:"-"`
}
// ListOptionsResponse: list options response.
type ListOptionsResponse struct {
// TotalCount: total count of matching options.
TotalCount uint32 `json:"total_count"`
// Options: options that match filters.
Options []*Option `json:"options"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOptionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOptionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOptionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Options = append(r.Options, results.Options...)
r.TotalCount += uint32(len(results.Options))
return uint32(len(results.Options)), nil
}
// ListServerEventsRequest: list server events request.
type ListServerEventsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server events searched.
ServerID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of server events per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the server events.
// Default value: created_at_asc
OrderBy ListServerEventsRequestOrderBy `json:"-"`
}
// ListServerEventsResponse: list server events response.
type ListServerEventsResponse struct {
// TotalCount: total count of matching events.
TotalCount uint32 `json:"total_count"`
// Events: server events that match filters.
Events []*ServerEvent `json:"events"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerEventsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerEventsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServerEventsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Events = append(r.Events, results.Events...)
r.TotalCount += uint32(len(results.Events))
return uint32(len(results.Events)), nil
}
// ListServerPrivateNetworksResponse: list server private networks response.
type ListServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServerPrivateNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ServerPrivateNetworks = append(r.ServerPrivateNetworks, results.ServerPrivateNetworks...)
r.TotalCount += uint32(len(results.ServerPrivateNetworks))
return uint32(len(results.ServerPrivateNetworks)), nil
}
// ListServersRequest: list servers request.
type ListServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of servers per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the servers.
// Default value: created_at_asc
OrderBy ListServersRequestOrderBy `json:"-"`
// Tags: tags to filter for.
Tags []string `json:"-"`
// Status: status to filter for.
Status []string `json:"-"`
// Name: names to filter for.
Name *string `json:"-"`
// OrganizationID: organization ID to filter for.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for.
ProjectID *string `json:"-"`
// OptionID: option ID to filter for.
OptionID *string `json:"-"`
}
// ListServersResponse: list servers response.
type ListServersResponse struct {
// TotalCount: total count of matching servers.
TotalCount uint32 `json:"total_count"`
// Servers: array of Elastic Metal server objects matching the filters in the request.
Servers []*Server `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListSettingsRequest: list settings request.
type ListSettingsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: set the maximum list size.
PageSize *uint32 `json:"-"`
// OrderBy: sort order for items in the response.
// Default value: created_at_asc
OrderBy ListSettingsRequestOrderBy `json:"-"`
// ProjectID: ID of the Project.
ProjectID *string `json:"-"`
}
// ListSettingsResponse: list settings response.
type ListSettingsResponse struct {
// TotalCount: total count of matching settings.
TotalCount uint32 `json:"total_count"`
// Settings: settings that match filters.
Settings []*Setting `json:"settings"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSettingsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSettingsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSettingsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Settings = append(r.Settings, results.Settings...)
r.TotalCount += uint32(len(results.Settings))
return uint32(len(results.Settings)), nil
}
// PrivateNetworkAPIAddServerPrivateNetworkRequest: private network api add server private network request.
type PrivateNetworkAPIAddServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: the ID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: the ID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
}
// PrivateNetworkAPIDeleteServerPrivateNetworkRequest: private network api delete server private network request.
type PrivateNetworkAPIDeleteServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: the ID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: the ID of the Private Network.
PrivateNetworkID string `json:"-"`
}
// PrivateNetworkAPIListServerPrivateNetworksRequest: private network api list server private networks request.
type PrivateNetworkAPIListServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: the sort order for the returned Private Networks.
// Default value: created_at_asc
OrderBy ListServerPrivateNetworksRequestOrderBy `json:"-"`
// Page: the page number for the returned Private Networks.
Page *int32 `json:"-"`
// PageSize: the maximum number of Private Networks per page.
PageSize *uint32 `json:"-"`
// ServerID: filter Private Networks by server ID.
ServerID *string `json:"-"`
// PrivateNetworkID: filter Private Networks by Private Network ID.
PrivateNetworkID *string `json:"-"`
// OrganizationID: filter Private Networks by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter Private Networks by Project ID.
ProjectID *string `json:"-"`
}
// PrivateNetworkAPISetServerPrivateNetworksRequest: private network api set server private networks request.
type PrivateNetworkAPISetServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: the ID of the server.
ServerID string `json:"-"`
// PrivateNetworkIDs: the IDs of the Private Networks.
PrivateNetworkIDs []string `json:"private_network_ids"`
}
// RebootServerRequest: reboot server request.
type RebootServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to reboot.
ServerID string `json:"-"`
// BootType: the type of boot.
// Default value: unknown_boot_type
BootType ServerBootType `json:"boot_type"`
}
// SetServerPrivateNetworksResponse: set server private networks response.
type SetServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
}
// StartBMCAccessRequest: start bmc access request.
type StartBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// IP: the IP authorized to connect to the server.
IP net.IP `json:"ip"`
}
// StartServerRequest: start server request.
type StartServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to start.
ServerID string `json:"-"`
// BootType: the type of boot.
// Default value: unknown_boot_type
BootType ServerBootType `json:"boot_type"`
}
// StopBMCAccessRequest: stop bmc access request.
type StopBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
}
// StopServerRequest: stop server request.
type StopServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to stop.
ServerID string `json:"-"`
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID string `json:"-"`
// IPID: ID of the IP to update.
IPID string `json:"-"`
// Reverse: new reverse IP to update, not updated if null.
Reverse *string `json:"reverse,omitempty"`
}
// UpdateServerRequest: update server request.
type UpdateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to update.
ServerID string `json:"-"`
// Name: name of the server (â hostname), not updated if null.
Name *string `json:"name,omitempty"`
// Description: description associated with the server, max 255 characters, not updated if null.
Description *string `json:"description,omitempty"`
// Tags: tags associated with the server, not updated if null.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateSettingRequest: update setting request.
type UpdateSettingRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SettingID: ID of the setting.
SettingID string `json:"-"`
// Enabled: defines whether the setting is enabled.
Enabled *bool `json:"enabled,omitempty"`
}
// ValidatePartitioningSchemaRequest: validate partitioning schema request.
type ValidatePartitioningSchemaRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PartitioningSchema: partitioning schema.
PartitioningSchema *Schema `json:"partitioning_schema,omitempty"`
// OfferID: offer ID of the server.
OfferID string `json:"offer_id"`
// OsID: oS ID.
OsID string `json:"os_id"`
}
// This API allows you to manage your Elastic Metal servers.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// ListServers: List Elastic Metal servers for a specific Organization.
func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "option_id", req.OptionID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
Query: query,
}
var resp ListServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServer: Get full details of an existing Elastic Metal server associated with the ID.
func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateServer: Create a new Elastic Metal server. Once the server is created, proceed with the [installation of an OS](#post-3e949e).
func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateServer: Update the server associated with the ID. You can update parameters such as the server's name, tags and description. Any parameters left null in the request body are not updated.
func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// InstallServer: Install an Operating System (OS) on the Elastic Metal server with a specific ID.
func (s *API) InstallServer(req *InstallServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/install",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServerMetrics: Get the ping status of the server associated with the ID.
func (s *API) GetServerMetrics(req *GetServerMetricsRequest, opts ...scw.RequestOption) (*GetServerMetricsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/metrics",
}
var resp GetServerMetricsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServer: Delete the server associated with the ID.
func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RebootServer: Reboot the Elastic Metal server associated with the ID, use the `boot_type` `rescue` to reboot the server in rescue mode.
func (s *API) RebootServer(req *RebootServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/reboot",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StartServer: Start the server associated with the ID.
func (s *API) StartServer(req *StartServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/start",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StopServer: Stop the server associated with the ID. The server remains allocated to your account and all data remains on the local storage of the server.
func (s *API) StopServer(req *StopServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/stop",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerEvents: List event (i.e. start/stop/reboot) associated to the server ID.
func (s *API) ListServerEvents(req *ListServerEventsRequest, opts ...scw.RequestOption) (*ListServerEventsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/events",
Query: query,
}
var resp ListServerEventsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDefaultPartitioningSchema: Get the default partitioning schema for the given offer ID and OS ID.
func (s *API) GetDefaultPartitioningSchema(req *GetDefaultPartitioningSchemaRequest, opts ...scw.RequestOption) (*Schema, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "offer_id", req.OfferID)
parameter.AddToQuery(query, "os_id", req.OsID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/partitioning-schemas/default",
Query: query,
}
var resp Schema
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ValidatePartitioningSchema: Validate the incoming partitioning schema from a user before installing the server. Return default ErrorCode if invalid.
func (s *API) ValidatePartitioningSchema(req *ValidatePartitioningSchemaRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/partitioning-schemas/validate",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// StartBMCAccess: Start BMC (Baseboard Management Controller) access associated with the ID.
// The BMC (Baseboard Management Controller) access is available one hour after the installation of the server.
// You need first to create an option Remote Access. You will find the ID and the price with a call to listOffers (https://developers.scaleway.com/en/products/baremetal/api/#get-78db92). Then add the option https://developers.scaleway.com/en/products/baremetal/api/#post-b14abd.
// After adding the BMC option, you need to Get Remote Access to get the login/password https://developers.scaleway.com/en/products/baremetal/api/#get-cefc0f. Do not forget to delete the Option after use.
func (s *API) StartBMCAccess(req *StartBMCAccessRequest, opts ...scw.RequestOption) (*BMCAccess, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp BMCAccess
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetBMCAccess: Get the BMC (Baseboard Management Controller) access associated with the ID, including the URL and login information needed to connect.
func (s *API) GetBMCAccess(req *GetBMCAccessRequest, opts ...scw.RequestOption) (*BMCAccess, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
var resp BMCAccess
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StopBMCAccess: Stop BMC (Baseboard Management Controller) access associated with the ID.
func (s *API) StopBMCAccess(req *StopBMCAccessRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateIP: Configure the IP address associated with the server ID and IP ID. You can use this method to set a reverse DNS for an IP address.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddOptionServer: Add an option, such as Private Networks, to a specific server.
func (s *API) AddOptionServer(req *AddOptionServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.OptionID) == "" {
return nil, errors.New("field OptionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/options/" + fmt.Sprint(req.OptionID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteOptionServer: Delete an option from a specific server.
func (s *API) DeleteOptionServer(req *DeleteOptionServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.OptionID) == "" {
return nil, errors.New("field OptionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/options/" + fmt.Sprint(req.OptionID) + "",
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOffers: List all available Elastic Metal server configurations.
func (s *API) ListOffers(req *ListOffersRequest, opts ...scw.RequestOption) (*ListOffersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "subscription_period", req.SubscriptionPeriod)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/offers",
Query: query,
}
var resp ListOffersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOffer: Get details of an offer identified by its offer ID.
func (s *API) GetOffer(req *GetOfferRequest, opts ...scw.RequestOption) (*Offer, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OfferID) == "" {
return nil, errors.New("field OfferID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/offers/" + fmt.Sprint(req.OfferID) + "",
}
var resp Offer
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOption: Return specific option for the ID.
func (s *API) GetOption(req *GetOptionRequest, opts ...scw.RequestOption) (*Option, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OptionID) == "" {
return nil, errors.New("field OptionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/options/" + fmt.Sprint(req.OptionID) + "",
}
var resp Option
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOptions: List all options matching with filters.
func (s *API) ListOptions(req *ListOptionsRequest, opts ...scw.RequestOption) (*ListOptionsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "offer_id", req.OfferID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/options",
Query: query,
}
var resp ListOptionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSettings: Return all settings for a Project ID.
func (s *API) ListSettings(req *ListSettingsRequest, opts ...scw.RequestOption) (*ListSettingsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/settings",
Query: query,
}
var resp ListSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSetting: Update a setting for a Project ID (enable or disable).
func (s *API) UpdateSetting(req *UpdateSettingRequest, opts ...scw.RequestOption) (*Setting, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SettingID) == "" {
return nil, errors.New("field SettingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/settings/" + fmt.Sprint(req.SettingID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Setting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOS: List all OSes that are available for installation on Elastic Metal servers.
func (s *API) ListOS(req *ListOSRequest, opts ...scw.RequestOption) (*ListOSResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "offer_id", req.OfferID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/os",
Query: query,
}
var resp ListOSResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOS: Return the specific OS for the ID.
func (s *API) GetOS(req *GetOSRequest, opts ...scw.RequestOption) (*OS, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OsID) == "" {
return nil, errors.New("field OsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/os/" + fmt.Sprint(req.OsID) + "",
}
var resp OS
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Elastic Metal - Private Network API.
type PrivateNetworkAPI struct {
client *scw.Client
}
// NewPrivateNetworkAPI returns a PrivateNetworkAPI object from a Scaleway client.
func NewPrivateNetworkAPI(client *scw.Client) *PrivateNetworkAPI {
return &PrivateNetworkAPI{
client: client,
}
}
func (s *PrivateNetworkAPI) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar2}
}
// AddServerPrivateNetwork: Add a server to a Private Network.
func (s *PrivateNetworkAPI) AddServerPrivateNetwork(req *PrivateNetworkAPIAddServerPrivateNetworkRequest, opts ...scw.RequestOption) (*ServerPrivateNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ServerPrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetServerPrivateNetworks: Set multiple Private Networks on a server.
func (s *PrivateNetworkAPI) SetServerPrivateNetworks(req *PrivateNetworkAPISetServerPrivateNetworksRequest, opts ...scw.RequestOption) (*SetServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerPrivateNetworks: List the Private Networks of a server.
func (s *PrivateNetworkAPI) ListServerPrivateNetworks(req *PrivateNetworkAPIListServerPrivateNetworksRequest, opts ...scw.RequestOption) (*ListServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "server_id", req.ServerID)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/server-private-networks",
Query: query,
}
var resp ListServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServerPrivateNetwork: Delete a Private Network.
func (s *PrivateNetworkAPI) DeleteServerPrivateNetwork(req *PrivateNetworkAPIDeleteServerPrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/baremetal/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v1/server_utils.go 0000664 0000000 0000000 00000016502 14747113137 0030360 0 ustar 00root root 0000000 0000000 package baremetal
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 2 * time.Hour
)
// WaitForServerRequest is used by WaitForServer method.
type WaitForServerRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServer wait for the server to be in a "terminal state" before returning.
// This function can be used to wait for a server to be created.
func (s *API) WaitForServer(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerStatus]struct{}{
ServerStatusReady: {},
ServerStatusStopped: {},
ServerStatusError: {},
ServerStatusLocked: {},
ServerStatusUnknown: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
// WaitForServerInstallRequest is used by WaitForServerInstall method.
type WaitForServerInstallRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServerInstall wait for the server install to be in a
// "terminal state" before returning.
// This function can be used to wait for a server to be installed.
func (s *API) WaitForServerInstall(req *WaitForServerInstallRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
installTerminalStatus := map[ServerInstallStatus]struct{}{
ServerInstallStatusCompleted: {},
ServerInstallStatusError: {},
ServerInstallStatusUnknown: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
if res.Install == nil {
return nil, false, errors.New("server creation has not begun for server %s", req.ServerID)
}
_, isTerminal := installTerminalStatus[res.Install.Status]
return res, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server installation failed")
}
return server.(*Server), nil
}
// GetServerOffer returns the offer of a baremetal server
func (s *API) GetServerOffer(server *Server) (*Offer, error) {
offer, err := s.GetOffer(&GetOfferRequest{
OfferID: server.OfferID,
Zone: server.Zone,
})
if err != nil {
return nil, err
}
return offer, nil
}
type GetOfferByNameRequest struct {
OfferName string
Zone scw.Zone
}
// GetOfferByName returns an offer from its commercial name
func (s *API) GetOfferByName(req *GetOfferByNameRequest) (*Offer, error) {
res, err := s.ListOffers(&ListOffersRequest{
Zone: req.Zone,
}, scw.WithAllPages())
if err != nil {
return nil, err
}
for _, offer := range res.Offers {
if req.OfferName == offer.Name {
return offer, nil
}
}
return nil, errors.New("could not find the offer ID from name %s", req.OfferName)
}
// WaitForServerOptionsRequest is used by WaitForServerOptions method.
type WaitForServerOptionsRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServerOptions wait for all server options to be in a "terminal state" before returning.
// This function can be used to wait for all server options to be set.
func (s *API) WaitForServerOptions(req *WaitForServerOptionsRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerOptionOptionStatus]struct{}{
ServerOptionOptionStatusOptionStatusEnable: {},
ServerOptionOptionStatusOptionStatusError: {},
ServerOptionOptionStatusOptionStatusUnknown: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
for i := range res.Options {
_, isTerminal := terminalStatus[res.Options[i].Status]
if !isTerminal {
return res, isTerminal, nil
}
}
return res, true, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server options failed")
}
return server.(*Server), nil
}
// WaitForServerPrivateNetworksRequest is used by WaitForServerPrivateNetworks method.
type WaitForServerPrivateNetworksRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServerPrivateNetworks wait for all server private networks to be in a "terminal state" before returning.
// This function can be used to wait for all server private networks to be set.
func (s *PrivateNetworkAPI) WaitForServerPrivateNetworks(req *WaitForServerPrivateNetworksRequest, opts ...scw.RequestOption) ([]*ServerPrivateNetwork, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerPrivateNetworkStatus]struct{}{
ServerPrivateNetworkStatusAttached: {},
ServerPrivateNetworkStatusError: {},
ServerPrivateNetworkStatusUnknown: {},
ServerPrivateNetworkStatusLocked: {},
}
serverPrivateNetwork, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.ListServerPrivateNetworks(&PrivateNetworkAPIListServerPrivateNetworksRequest{
ServerID: &req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
for i := range res.ServerPrivateNetworks {
_, isTerminal := terminalStatus[res.ServerPrivateNetworks[i].Status]
if !isTerminal {
return res.ServerPrivateNetworks, isTerminal, nil
}
}
return res.ServerPrivateNetworks, true, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server private networks failed")
}
return serverPrivateNetwork.([]*ServerPrivateNetwork), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027134 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000001534 14747113137 0031323 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/baremetal/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepServers(scwClient *scw.Client, zone scw.Zone) error {
baremetalAPI := baremetal.NewAPI(scwClient)
listServers, err := baremetalAPI.ListServers(&baremetal.ListServersRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
return err
}
for _, server := range listServers.Servers {
_, err := baremetalAPI.DeleteServer(&baremetal.DeleteServerRequest{
Zone: zone,
ServerID: server.ID,
})
if err != nil {
return fmt.Errorf("error deleting server in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&baremetal.API{}).Zones() {
err := SweepServers(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v3/ 0000775 0000000 0000000 00000000000 14747113137 0025301 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v3/baremetal_sdk.go 0000664 0000000 0000000 00000031627 14747113137 0030436 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package baremetal provides methods and message types of the baremetal v3 API.
package baremetal
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListServerPrivateNetworksRequestOrderBy string
const (
ListServerPrivateNetworksRequestOrderByCreatedAtAsc = ListServerPrivateNetworksRequestOrderBy("created_at_asc")
ListServerPrivateNetworksRequestOrderByCreatedAtDesc = ListServerPrivateNetworksRequestOrderBy("created_at_desc")
ListServerPrivateNetworksRequestOrderByUpdatedAtAsc = ListServerPrivateNetworksRequestOrderBy("updated_at_asc")
ListServerPrivateNetworksRequestOrderByUpdatedAtDesc = ListServerPrivateNetworksRequestOrderBy("updated_at_desc")
)
func (enum ListServerPrivateNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerPrivateNetworksRequestOrderBy) Values() []ListServerPrivateNetworksRequestOrderBy {
return []ListServerPrivateNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListServerPrivateNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerPrivateNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerPrivateNetworksRequestOrderBy(ListServerPrivateNetworksRequestOrderBy(tmp).String())
return nil
}
type ServerPrivateNetworkStatus string
const (
ServerPrivateNetworkStatusUnknownStatus = ServerPrivateNetworkStatus("unknown_status")
ServerPrivateNetworkStatusAttaching = ServerPrivateNetworkStatus("attaching")
ServerPrivateNetworkStatusAttached = ServerPrivateNetworkStatus("attached")
ServerPrivateNetworkStatusError = ServerPrivateNetworkStatus("error")
ServerPrivateNetworkStatusDetaching = ServerPrivateNetworkStatus("detaching")
ServerPrivateNetworkStatusLocked = ServerPrivateNetworkStatus("locked")
)
func (enum ServerPrivateNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ServerPrivateNetworkStatus) Values() []ServerPrivateNetworkStatus {
return []ServerPrivateNetworkStatus{
"unknown_status",
"attaching",
"attached",
"error",
"detaching",
"locked",
}
}
func (enum ServerPrivateNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerPrivateNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerPrivateNetworkStatus(ServerPrivateNetworkStatus(tmp).String())
return nil
}
// ServerPrivateNetwork: server private network.
type ServerPrivateNetwork struct {
// ID: UUID of the Server-to-Private Network mapping.
ID string `json:"id"`
// ProjectID: private Network Project UUID.
ProjectID string `json:"project_id"`
// ServerID: server UUID.
ServerID string `json:"server_id"`
// PrivateNetworkID: private Network UUID.
PrivateNetworkID string `json:"private_network_id"`
// Vlan: vLAN UUID associated with the Private Network.
Vlan *uint32 `json:"vlan"`
// Status: configuration status of the Private Network.
// Default value: unknown_status
Status ServerPrivateNetworkStatus `json:"status"`
// CreatedAt: private Network creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the Private Network was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// IpamIPIDs: iPAM IP IDs of the server, if it has any.
IpamIPIDs []string `json:"ipam_ip_ids"`
}
// ListServerPrivateNetworksResponse: list server private networks response.
type ListServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerPrivateNetworksResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListServerPrivateNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ServerPrivateNetworks = append(r.ServerPrivateNetworks, results.ServerPrivateNetworks...)
r.TotalCount += uint64(len(results.ServerPrivateNetworks))
return uint64(len(results.ServerPrivateNetworks)), nil
}
// PrivateNetworkAPIAddServerPrivateNetworkRequest: private network api add server private network request.
type PrivateNetworkAPIAddServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: UUID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
// IpamIPIDs: iPAM IDs of an IPs to attach to the server.
IpamIPIDs []string `json:"ipam_ip_ids"`
}
// PrivateNetworkAPIDeleteServerPrivateNetworkRequest: private network api delete server private network request.
type PrivateNetworkAPIDeleteServerPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server.
ServerID string `json:"-"`
// PrivateNetworkID: UUID of the Private Network.
PrivateNetworkID string `json:"-"`
}
// PrivateNetworkAPIListServerPrivateNetworksRequest: private network api list server private networks request.
type PrivateNetworkAPIListServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order for the returned Private Networks.
// Default value: created_at_asc
OrderBy ListServerPrivateNetworksRequestOrderBy `json:"-"`
// Page: page number for the returned Private Networks.
Page *int32 `json:"-"`
// PageSize: maximum number of Private Networks per page.
PageSize *uint32 `json:"-"`
// ServerID: filter Private Networks by server UUID.
ServerID *string `json:"-"`
// PrivateNetworkID: filter Private Networks by Private Network UUID.
PrivateNetworkID *string `json:"-"`
// OrganizationID: filter Private Networks by organization UUID.
OrganizationID *string `json:"-"`
// ProjectID: filter Private Networks by project UUID.
ProjectID *string `json:"-"`
// IpamIPIDs: filter Private Networks by IPAM IP UUIDs.
IpamIPIDs []string `json:"-"`
}
// PrivateNetworkAPISetServerPrivateNetworksRequest: private network api set server private networks request.
type PrivateNetworkAPISetServerPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the server.
ServerID string `json:"-"`
// PerPrivateNetworkIpamIPIDs: object where the keys are the UUIDs of Private Networks and the values are arrays of IPAM IDs representing the IPs to assign to this Elastic Metal server on the Private Network. If the array supplied for a Private Network is empty, the next available IP from the Private Network's CIDR block will automatically be used for attachment.
PerPrivateNetworkIpamIPIDs map[string]*[]string `json:"per_private_network_ipam_ip_ids"`
}
// SetServerPrivateNetworksResponse: set server private networks response.
type SetServerPrivateNetworksResponse struct {
ServerPrivateNetworks []*ServerPrivateNetwork `json:"server_private_networks"`
}
// Elastic Metal - Private Networks API.
type PrivateNetworkAPI struct {
client *scw.Client
}
// NewPrivateNetworkAPI returns a PrivateNetworkAPI object from a Scaleway client.
func NewPrivateNetworkAPI(client *scw.Client) *PrivateNetworkAPI {
return &PrivateNetworkAPI{
client: client,
}
}
func (s *PrivateNetworkAPI) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// AddServerPrivateNetwork: Add an Elastic Metal server to a Private Network.
func (s *PrivateNetworkAPI) AddServerPrivateNetwork(req *PrivateNetworkAPIAddServerPrivateNetworkRequest, opts ...scw.RequestOption) (*ServerPrivateNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/baremetal/v3/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ServerPrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetServerPrivateNetworks: Configure multiple Private Networks on an Elastic Metal server.
func (s *PrivateNetworkAPI) SetServerPrivateNetworks(req *PrivateNetworkAPISetServerPrivateNetworksRequest, opts ...scw.RequestOption) (*SetServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/baremetal/v3/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerPrivateNetworks: List the Private Networks of an Elastic Metal server.
func (s *PrivateNetworkAPI) ListServerPrivateNetworks(req *PrivateNetworkAPIListServerPrivateNetworksRequest, opts ...scw.RequestOption) (*ListServerPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "server_id", req.ServerID)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "ipam_ip_ids", req.IpamIPIDs)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/baremetal/v3/zones/" + fmt.Sprint(req.Zone) + "/server-private-networks",
Query: query,
}
var resp ListServerPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServerPrivateNetwork: Delete a Private Network.
func (s *PrivateNetworkAPI) DeleteServerPrivateNetwork(req *PrivateNetworkAPIDeleteServerPrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/baremetal/v3/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/baremetal/v3/server_utils.go 0000664 0000000 0000000 00000004160 14747113137 0030357 0 ustar 00root root 0000000 0000000 package baremetal
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 2 * time.Hour
)
// WaitForServerPrivateNetworksRequest is used by WaitForServerPrivateNetworks method.
type WaitForServerPrivateNetworksRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServerPrivateNetworks wait for all server private networks to be in a "terminal state" before returning.
// This function can be used to wait for all server private networks to be set.
func (s *PrivateNetworkAPI) WaitForServerPrivateNetworks(req *WaitForServerPrivateNetworksRequest, opts ...scw.RequestOption) ([]*ServerPrivateNetwork, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerPrivateNetworkStatus]struct{}{
ServerPrivateNetworkStatusAttached: {},
ServerPrivateNetworkStatusError: {},
ServerPrivateNetworkStatusUnknownStatus: {},
ServerPrivateNetworkStatusLocked: {},
}
serverPrivateNetwork, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.ListServerPrivateNetworks(&PrivateNetworkAPIListServerPrivateNetworksRequest{
ServerID: &req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
for i := range res.ServerPrivateNetworks {
_, isTerminal := terminalStatus[res.ServerPrivateNetworks[i].Status]
if !isTerminal {
return res.ServerPrivateNetworks, isTerminal, nil
}
}
return res.ServerPrivateNetworks, true, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server private networks failed")
}
return serverPrivateNetwork.([]*ServerPrivateNetwork), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/billing/ 0000775 0000000 0000000 00000000000 14747113137 0024435 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/billing/v2beta1/ 0000775 0000000 0000000 00000000000 14747113137 0025701 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/billing/v2beta1/billing_sdk.go 0000664 0000000 0000000 00000106512 14747113137 0030516 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package billing provides methods and message types of the billing v2beta1 API.
package billing
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DiscountDiscountMode string
const (
// Unknown discount mode.
DiscountDiscountModeUnknownDiscountMode = DiscountDiscountMode("unknown_discount_mode")
// A rate discount that reduces each customer bill by the discount value percentage.
DiscountDiscountModeDiscountModeRate = DiscountDiscountMode("discount_mode_rate")
// A value discount that reduces the amount of the customer bill by the discount value.
DiscountDiscountModeDiscountModeValue = DiscountDiscountMode("discount_mode_value")
// A fixed sum to be deducted from the user's bills.
DiscountDiscountModeDiscountModeSplittable = DiscountDiscountMode("discount_mode_splittable")
)
func (enum DiscountDiscountMode) String() string {
if enum == "" {
// return default value if empty
return "unknown_discount_mode"
}
return string(enum)
}
func (enum DiscountDiscountMode) Values() []DiscountDiscountMode {
return []DiscountDiscountMode{
"unknown_discount_mode",
"discount_mode_rate",
"discount_mode_value",
"discount_mode_splittable",
}
}
func (enum DiscountDiscountMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DiscountDiscountMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DiscountDiscountMode(DiscountDiscountMode(tmp).String())
return nil
}
type DiscountFilterType string
const (
// Unknown filter type.
DiscountFilterTypeUnknownType = DiscountFilterType("unknown_type")
// Product category, such as Compute, Network, Observability.
DiscountFilterTypeCategoryName = DiscountFilterType("category_name")
// Products within the Product category. For example, VPC, Private Networks, and Public Gateways are products in the Network category.
DiscountFilterTypeProductName = DiscountFilterType("product_name")
// The range of a product. For example, `Production Optimized` or `Cost Optimized` for an `instance` product of the `compute` category.
DiscountFilterTypeProductRange = DiscountFilterType("product_range")
// Identifies the reference based on category, product, range, size, region, and zone. It can sometimes include different product options, such as licenses and monthly payments.
DiscountFilterTypeResourceName = DiscountFilterType("resource_name")
// Region name like "FR-PAR", "NL-AMS", "PL-WAW".
DiscountFilterTypeRegion = DiscountFilterType("region")
// Zone name like "FR-PAR-1", "FR-PAR-2", "FR-PAR-3".
DiscountFilterTypeZone = DiscountFilterType("zone")
)
func (enum DiscountFilterType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum DiscountFilterType) Values() []DiscountFilterType {
return []DiscountFilterType{
"unknown_type",
"category_name",
"product_name",
"product_range",
"resource_name",
"region",
"zone",
}
}
func (enum DiscountFilterType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DiscountFilterType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DiscountFilterType(DiscountFilterType(tmp).String())
return nil
}
type DownloadInvoiceRequestFileType string
const (
DownloadInvoiceRequestFileTypePdf = DownloadInvoiceRequestFileType("pdf")
)
func (enum DownloadInvoiceRequestFileType) String() string {
if enum == "" {
// return default value if empty
return "pdf"
}
return string(enum)
}
func (enum DownloadInvoiceRequestFileType) Values() []DownloadInvoiceRequestFileType {
return []DownloadInvoiceRequestFileType{
"pdf",
}
}
func (enum DownloadInvoiceRequestFileType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DownloadInvoiceRequestFileType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DownloadInvoiceRequestFileType(DownloadInvoiceRequestFileType(tmp).String())
return nil
}
type ExportInvoicesRequestFileType string
const (
ExportInvoicesRequestFileTypeCsv = ExportInvoicesRequestFileType("csv")
)
func (enum ExportInvoicesRequestFileType) String() string {
if enum == "" {
// return default value if empty
return "csv"
}
return string(enum)
}
func (enum ExportInvoicesRequestFileType) Values() []ExportInvoicesRequestFileType {
return []ExportInvoicesRequestFileType{
"csv",
}
}
func (enum ExportInvoicesRequestFileType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ExportInvoicesRequestFileType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ExportInvoicesRequestFileType(ExportInvoicesRequestFileType(tmp).String())
return nil
}
type ExportInvoicesRequestOrderBy string
const (
ExportInvoicesRequestOrderByInvoiceNumberDesc = ExportInvoicesRequestOrderBy("invoice_number_desc")
ExportInvoicesRequestOrderByInvoiceNumberAsc = ExportInvoicesRequestOrderBy("invoice_number_asc")
ExportInvoicesRequestOrderByStartDateDesc = ExportInvoicesRequestOrderBy("start_date_desc")
ExportInvoicesRequestOrderByStartDateAsc = ExportInvoicesRequestOrderBy("start_date_asc")
ExportInvoicesRequestOrderByIssuedDateDesc = ExportInvoicesRequestOrderBy("issued_date_desc")
ExportInvoicesRequestOrderByIssuedDateAsc = ExportInvoicesRequestOrderBy("issued_date_asc")
ExportInvoicesRequestOrderByDueDateDesc = ExportInvoicesRequestOrderBy("due_date_desc")
ExportInvoicesRequestOrderByDueDateAsc = ExportInvoicesRequestOrderBy("due_date_asc")
ExportInvoicesRequestOrderByTotalUntaxedDesc = ExportInvoicesRequestOrderBy("total_untaxed_desc")
ExportInvoicesRequestOrderByTotalUntaxedAsc = ExportInvoicesRequestOrderBy("total_untaxed_asc")
ExportInvoicesRequestOrderByTotalTaxedDesc = ExportInvoicesRequestOrderBy("total_taxed_desc")
ExportInvoicesRequestOrderByTotalTaxedAsc = ExportInvoicesRequestOrderBy("total_taxed_asc")
ExportInvoicesRequestOrderByInvoiceTypeDesc = ExportInvoicesRequestOrderBy("invoice_type_desc")
ExportInvoicesRequestOrderByInvoiceTypeAsc = ExportInvoicesRequestOrderBy("invoice_type_asc")
)
func (enum ExportInvoicesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "invoice_number_desc"
}
return string(enum)
}
func (enum ExportInvoicesRequestOrderBy) Values() []ExportInvoicesRequestOrderBy {
return []ExportInvoicesRequestOrderBy{
"invoice_number_desc",
"invoice_number_asc",
"start_date_desc",
"start_date_asc",
"issued_date_desc",
"issued_date_asc",
"due_date_desc",
"due_date_asc",
"total_untaxed_desc",
"total_untaxed_asc",
"total_taxed_desc",
"total_taxed_asc",
"invoice_type_desc",
"invoice_type_asc",
}
}
func (enum ExportInvoicesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ExportInvoicesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ExportInvoicesRequestOrderBy(ExportInvoicesRequestOrderBy(tmp).String())
return nil
}
type InvoiceType string
const (
InvoiceTypeUnknownType = InvoiceType("unknown_type")
InvoiceTypePeriodic = InvoiceType("periodic")
InvoiceTypePurchase = InvoiceType("purchase")
)
func (enum InvoiceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum InvoiceType) Values() []InvoiceType {
return []InvoiceType{
"unknown_type",
"periodic",
"purchase",
}
}
func (enum InvoiceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InvoiceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InvoiceType(InvoiceType(tmp).String())
return nil
}
type ListConsumptionsRequestOrderBy string
const (
// Order consumptions by update date (descending chronological order).
ListConsumptionsRequestOrderByUpdatedAtDesc = ListConsumptionsRequestOrderBy("updated_at_desc")
// Order consumptions by update date (ascending chronological order).
ListConsumptionsRequestOrderByUpdatedAtAsc = ListConsumptionsRequestOrderBy("updated_at_asc")
// Order consumptions by category name (descending alphabetical order).
ListConsumptionsRequestOrderByCategoryNameDesc = ListConsumptionsRequestOrderBy("category_name_desc")
// Order consumptions by category name (ascending alphabetical order).
ListConsumptionsRequestOrderByCategoryNameAsc = ListConsumptionsRequestOrderBy("category_name_asc")
)
func (enum ListConsumptionsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "updated_at_desc"
}
return string(enum)
}
func (enum ListConsumptionsRequestOrderBy) Values() []ListConsumptionsRequestOrderBy {
return []ListConsumptionsRequestOrderBy{
"updated_at_desc",
"updated_at_asc",
"category_name_desc",
"category_name_asc",
}
}
func (enum ListConsumptionsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListConsumptionsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListConsumptionsRequestOrderBy(ListConsumptionsRequestOrderBy(tmp).String())
return nil
}
type ListDiscountsRequestOrderBy string
const (
// Order discounts by creation date (descending chronological order).
ListDiscountsRequestOrderByCreationDateDesc = ListDiscountsRequestOrderBy("creation_date_desc")
// Order discounts by creation date (ascending chronological order).
ListDiscountsRequestOrderByCreationDateAsc = ListDiscountsRequestOrderBy("creation_date_asc")
// Order discounts by start date (descending chronological order).
ListDiscountsRequestOrderByStartDateDesc = ListDiscountsRequestOrderBy("start_date_desc")
// Order discounts by start date (ascending chronological order).
ListDiscountsRequestOrderByStartDateAsc = ListDiscountsRequestOrderBy("start_date_asc")
// Order discounts by stop date (descending chronological order).
ListDiscountsRequestOrderByStopDateDesc = ListDiscountsRequestOrderBy("stop_date_desc")
// Order discounts by stop date (ascending chronological order).
ListDiscountsRequestOrderByStopDateAsc = ListDiscountsRequestOrderBy("stop_date_asc")
)
func (enum ListDiscountsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "creation_date_desc"
}
return string(enum)
}
func (enum ListDiscountsRequestOrderBy) Values() []ListDiscountsRequestOrderBy {
return []ListDiscountsRequestOrderBy{
"creation_date_desc",
"creation_date_asc",
"start_date_desc",
"start_date_asc",
"stop_date_desc",
"stop_date_asc",
}
}
func (enum ListDiscountsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDiscountsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDiscountsRequestOrderBy(ListDiscountsRequestOrderBy(tmp).String())
return nil
}
type ListInvoicesRequestOrderBy string
const (
ListInvoicesRequestOrderByInvoiceNumberDesc = ListInvoicesRequestOrderBy("invoice_number_desc")
ListInvoicesRequestOrderByInvoiceNumberAsc = ListInvoicesRequestOrderBy("invoice_number_asc")
ListInvoicesRequestOrderByStartDateDesc = ListInvoicesRequestOrderBy("start_date_desc")
ListInvoicesRequestOrderByStartDateAsc = ListInvoicesRequestOrderBy("start_date_asc")
ListInvoicesRequestOrderByIssuedDateDesc = ListInvoicesRequestOrderBy("issued_date_desc")
ListInvoicesRequestOrderByIssuedDateAsc = ListInvoicesRequestOrderBy("issued_date_asc")
ListInvoicesRequestOrderByDueDateDesc = ListInvoicesRequestOrderBy("due_date_desc")
ListInvoicesRequestOrderByDueDateAsc = ListInvoicesRequestOrderBy("due_date_asc")
ListInvoicesRequestOrderByTotalUntaxedDesc = ListInvoicesRequestOrderBy("total_untaxed_desc")
ListInvoicesRequestOrderByTotalUntaxedAsc = ListInvoicesRequestOrderBy("total_untaxed_asc")
ListInvoicesRequestOrderByTotalTaxedDesc = ListInvoicesRequestOrderBy("total_taxed_desc")
ListInvoicesRequestOrderByTotalTaxedAsc = ListInvoicesRequestOrderBy("total_taxed_asc")
ListInvoicesRequestOrderByInvoiceTypeDesc = ListInvoicesRequestOrderBy("invoice_type_desc")
ListInvoicesRequestOrderByInvoiceTypeAsc = ListInvoicesRequestOrderBy("invoice_type_asc")
)
func (enum ListInvoicesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "invoice_number_desc"
}
return string(enum)
}
func (enum ListInvoicesRequestOrderBy) Values() []ListInvoicesRequestOrderBy {
return []ListInvoicesRequestOrderBy{
"invoice_number_desc",
"invoice_number_asc",
"start_date_desc",
"start_date_asc",
"issued_date_desc",
"issued_date_asc",
"due_date_desc",
"due_date_asc",
"total_untaxed_desc",
"total_untaxed_asc",
"total_taxed_desc",
"total_taxed_asc",
"invoice_type_desc",
"invoice_type_asc",
}
}
func (enum ListInvoicesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInvoicesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInvoicesRequestOrderBy(ListInvoicesRequestOrderBy(tmp).String())
return nil
}
type ListTaxesRequestOrderBy string
const (
// Order consumptions by update date (descending chronological order).
ListTaxesRequestOrderByUpdatedAtDesc = ListTaxesRequestOrderBy("updated_at_desc")
// Order consumptions by update date (ascending chronological order).
ListTaxesRequestOrderByUpdatedAtAsc = ListTaxesRequestOrderBy("updated_at_asc")
// Order consumptions by category name (descending alphabetical order).
ListTaxesRequestOrderByCategoryNameDesc = ListTaxesRequestOrderBy("category_name_desc")
// Order consumptions by category name (ascending alphabetical order).
ListTaxesRequestOrderByCategoryNameAsc = ListTaxesRequestOrderBy("category_name_asc")
)
func (enum ListTaxesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "updated_at_desc"
}
return string(enum)
}
func (enum ListTaxesRequestOrderBy) Values() []ListTaxesRequestOrderBy {
return []ListTaxesRequestOrderBy{
"updated_at_desc",
"updated_at_asc",
"category_name_desc",
"category_name_asc",
}
}
func (enum ListTaxesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTaxesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTaxesRequestOrderBy(ListTaxesRequestOrderBy(tmp).String())
return nil
}
// DiscountCoupon: discount coupon.
type DiscountCoupon struct {
// Description: the description of the coupon.
Description *string `json:"description"`
}
// DiscountFilter: discount filter.
type DiscountFilter struct {
// Type: type of the filter (category name, product name, product range, resource name, region or zone).
// Default value: unknown_type
Type DiscountFilterType `json:"type"`
// Value: value of filter.
Value string `json:"value"`
// Exclude: boolean to describe if filter is an excluding filter.
Exclude bool `json:"exclude"`
}
// ListConsumptionsResponseConsumption: list consumptions response consumption.
type ListConsumptionsResponseConsumption struct {
// Value: monetary value of the consumption.
Value *scw.Money `json:"value"`
// ProductName: the product name. For example, "VPC Public Gateway S", "VPC Public Gateway M" for the VPC product.
ProductName string `json:"product_name"`
// ResourceName: identifies the reference based on the category.
ResourceName string `json:"resource_name"`
// Sku: unique identifier of the product.
Sku string `json:"sku"`
// ProjectID: project ID of the consumption.
ProjectID string `json:"project_id"`
// CategoryName: name of consumption category.
CategoryName string `json:"category_name"`
// Unit: unit of consumed quantity.
Unit string `json:"unit"`
// BilledQuantity: consumed quantity.
BilledQuantity string `json:"billed_quantity"`
}
// Discount: discount.
type Discount struct {
// ID: the ID of the discount.
ID string `json:"id"`
// CreationDate: the creation date of the discount.
CreationDate *time.Time `json:"creation_date"`
// OrganizationID: the organization ID of the discount.
OrganizationID string `json:"organization_id"`
// Description: the description of the discount.
Description string `json:"description"`
// Value: the initial value of the discount.
Value float64 `json:"value"`
// ValueUsed: the value indicating how much of the discount has been used.
ValueUsed float64 `json:"value_used"`
// ValueRemaining: the remaining value of the discount.
ValueRemaining float64 `json:"value_remaining"`
// Mode: the mode of the discount.
// Default value: unknown_discount_mode
Mode DiscountDiscountMode `json:"mode"`
// StartDate: the start date of the discount.
StartDate *time.Time `json:"start_date"`
// StopDate: the stop date of the discount.
StopDate *time.Time `json:"stop_date"`
// Coupon: the description of the coupon.
Coupon *DiscountCoupon `json:"coupon"`
// Filters: list of the discount scopes.
Filters []*DiscountFilter `json:"filters"`
}
// Invoice: invoice.
type Invoice struct {
// ID: invoice ID.
ID string `json:"id"`
OrganizationID string `json:"organization_id"`
OrganizationName string `json:"organization_name"`
// StartDate: start date of the billing period.
StartDate *time.Time `json:"start_date"`
StopDate *time.Time `json:"stop_date"`
// BillingPeriod: the billing period of the invoice in the YYYY-MM format.
BillingPeriod *time.Time `json:"billing_period"`
// IssuedDate: date when the invoice was sent to the customer.
IssuedDate *time.Time `json:"issued_date"`
// DueDate: payment time limit, set according to the Organization's payment conditions.
DueDate *time.Time `json:"due_date"`
// TotalUntaxed: total amount, untaxed.
TotalUntaxed *scw.Money `json:"total_untaxed"`
// TotalTaxed: total amount, taxed.
TotalTaxed *scw.Money `json:"total_taxed"`
// TotalTax: the total tax amount of the invoice.
TotalTax *scw.Money `json:"total_tax"`
// TotalDiscount: the total discount amount of the invoice.
TotalDiscount *scw.Money `json:"total_discount"`
// TotalUndiscount: the total amount of the invoice before applying the discount.
TotalUndiscount *scw.Money `json:"total_undiscount"`
// Type: type of invoice, either periodic or purchase.
// Default value: unknown_type
Type InvoiceType `json:"type"`
// State: the state of the Invoice.
State string `json:"state"`
// Number: invoice number.
Number int32 `json:"number"`
// SellerName: the name of the seller (Scaleway).
SellerName string `json:"seller_name"`
}
// ListTaxesResponseTax: list taxes response tax.
type ListTaxesResponseTax struct {
// Description: description of the tax applied.
Description string `json:"description"`
// Currency: the three-letter currency code.
Currency string `json:"currency"`
// Rate: applied tax rate (0.2 means a VAT of 20%).
Rate *float64 `json:"rate"`
// TotalTaxValue: the total tax value of the consumption.
TotalTaxValue *float64 `json:"total_tax_value"`
}
// DownloadInvoiceRequest: download invoice request.
type DownloadInvoiceRequest struct {
// InvoiceID: invoice ID.
InvoiceID string `json:"-"`
// FileType: file type. PDF by default.
// Default value: pdf
FileType DownloadInvoiceRequestFileType `json:"-"`
}
// ExportInvoicesRequest: export invoices request.
type ExportInvoicesRequest struct {
// OrganizationID: organization ID. If specified, only invoices from this Organization will be returned.
OrganizationID *string `json:"-"`
// BillingPeriodStartAfter: return only invoice with start date greater than billing_period_start.
BillingPeriodStartAfter *time.Time `json:"-"`
// BillingPeriodStartBefore: return only invoice with start date less than billing_period_start.
BillingPeriodStartBefore *time.Time `json:"-"`
// InvoiceType: invoice type. It can either be `periodic` or `purchase`.
// Default value: unknown_type
InvoiceType InvoiceType `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// OrderBy: how invoices are ordered in the response.
// Default value: invoice_number_desc
OrderBy ExportInvoicesRequestOrderBy `json:"-"`
// FileType: file format for exporting the invoice list.
// Default value: csv
FileType ExportInvoicesRequestFileType `json:"-"`
}
// GetInvoiceRequest: get invoice request.
type GetInvoiceRequest struct {
// InvoiceID: invoice ID.
InvoiceID string `json:"-"`
}
// ListConsumptionsRequest: list consumptions request.
type ListConsumptionsRequest struct {
// OrderBy: order consumptions list in the response by their update date.
// Default value: updated_at_desc
OrderBy ListConsumptionsRequestOrderBy `json:"-"`
// Page: positive integer to choose the page to return.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// OrganizationID: filter by Organization ID.
// Precisely one of OrganizationID, ProjectID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: filter by Project ID.
// Precisely one of OrganizationID, ProjectID must be set.
ProjectID *string `json:"project_id,omitempty"`
// CategoryName: filter by name of a Category as they are shown in the invoice (Compute, Network, Observability).
CategoryName *string `json:"-"`
// BillingPeriod: filter by the billing period in the YYYY-MM format. If it is empty the current billing period will be used as default.
BillingPeriod *string `json:"-"`
}
// ListConsumptionsResponse: list consumptions response.
type ListConsumptionsResponse struct {
// Consumptions: detailed consumption list.
Consumptions []*ListConsumptionsResponseConsumption `json:"consumptions"`
// TotalCount: total number of returned items.
TotalCount uint64 `json:"total_count"`
// TotalDiscountUntaxedValue: sum of all discounts, displayed only when no category or project ID filter is applied.
TotalDiscountUntaxedValue float64 `json:"total_discount_untaxed_value"`
// UpdatedAt: last consumption update date.
UpdatedAt *time.Time `json:"updated_at"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListConsumptionsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListConsumptionsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListConsumptionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Consumptions = append(r.Consumptions, results.Consumptions...)
r.TotalCount += uint64(len(results.Consumptions))
return uint64(len(results.Consumptions)), nil
}
// ListDiscountsRequest: list discounts request.
type ListDiscountsRequest struct {
// OrderBy: order discounts in the response by their description.
// Default value: creation_date_desc
OrderBy ListDiscountsRequestOrderBy `json:"-"`
// Page: positive integer to choose the page to return.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// OrganizationID: ID of the organization.
OrganizationID *string `json:"-"`
}
// ListDiscountsResponse: list discounts response.
type ListDiscountsResponse struct {
// TotalCount: total number of discounts.
TotalCount uint64 `json:"total_count"`
// Discounts: paginated returned discounts.
Discounts []*Discount `json:"discounts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDiscountsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDiscountsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDiscountsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Discounts = append(r.Discounts, results.Discounts...)
r.TotalCount += uint64(len(results.Discounts))
return uint64(len(results.Discounts)), nil
}
// ListInvoicesRequest: list invoices request.
type ListInvoicesRequest struct {
// OrganizationID: organization ID. If specified, only invoices from this Organization will be returned.
OrganizationID *string `json:"-"`
// BillingPeriodStartAfter: return only invoice with start date greater than billing_period_start.
BillingPeriodStartAfter *time.Time `json:"-"`
// BillingPeriodStartBefore: return only invoice with start date less than billing_period_start.
BillingPeriodStartBefore *time.Time `json:"-"`
// InvoiceType: invoice type. It can either be `periodic` or `purchase`.
// Default value: unknown_type
InvoiceType InvoiceType `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// OrderBy: how invoices are ordered in the response.
// Default value: invoice_number_desc
OrderBy ListInvoicesRequestOrderBy `json:"-"`
}
// ListInvoicesResponse: list invoices response.
type ListInvoicesResponse struct {
// TotalCount: total number of invoices.
TotalCount uint64 `json:"total_count"`
// Invoices: paginated returned invoices.
Invoices []*Invoice `json:"invoices"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInvoicesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInvoicesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListInvoicesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Invoices = append(r.Invoices, results.Invoices...)
r.TotalCount += uint64(len(results.Invoices))
return uint64(len(results.Invoices)), nil
}
// ListTaxesRequest: list taxes request.
type ListTaxesRequest struct {
// OrderBy: order consumed taxes list in the response by their update date.
// Default value: updated_at_desc
OrderBy ListTaxesRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: positive integer lower or equal to 100 to select the number of items to return.
PageSize *uint32 `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID string `json:"-"`
// BillingPeriod: filter by the billing period in the YYYY-MM format. If it is empty the current billing period will be used as default.
BillingPeriod *string `json:"-"`
}
// ListTaxesResponse: list taxes response.
type ListTaxesResponse struct {
// Taxes: detailed consumption tax.
Taxes []*ListTaxesResponseTax `json:"taxes"`
// TotalCount: total number of returned items.
TotalCount uint64 `json:"total_count"`
// UpdatedAt: last consumption update date.
UpdatedAt *time.Time `json:"updated_at"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTaxesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTaxesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListTaxesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Taxes = append(r.Taxes, results.Taxes...)
r.TotalCount += uint64(len(results.Taxes))
return uint64(len(results.Taxes)), nil
}
// This API allows you to manage and query your Scaleway billing and consumption.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// ListConsumptions: Consumption allows you to retrieve your past or current consumption cost, by project or category.
func (s *API) ListConsumptions(req *ListConsumptionsRequest, opts ...scw.RequestOption) (*ListConsumptionsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.OrganizationID == nil && req.ProjectID == nil {
req.OrganizationID = &defaultOrganizationID
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.OrganizationID == nil && req.ProjectID == nil {
req.ProjectID = &defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "category_name", req.CategoryName)
parameter.AddToQuery(query, "billing_period", req.BillingPeriod)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/consumptions",
Query: query,
}
var resp ListConsumptionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTaxes: Consumption Tax allows you to retrieve your past or current tax charges, by project or category.
func (s *API) ListTaxes(req *ListTaxesRequest, opts ...scw.RequestOption) (*ListTaxesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "billing_period", req.BillingPeriod)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/taxes",
Query: query,
}
var resp ListTaxesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInvoices: List all your invoices, filtering by `start_date` and `invoice_type`. Each invoice has its own ID.
func (s *API) ListInvoices(req *ListInvoicesRequest, opts ...scw.RequestOption) (*ListInvoicesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "billing_period_start_after", req.BillingPeriodStartAfter)
parameter.AddToQuery(query, "billing_period_start_before", req.BillingPeriodStartBefore)
parameter.AddToQuery(query, "invoice_type", req.InvoiceType)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/invoices",
Query: query,
}
var resp ListInvoicesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ExportInvoices: Export invoices in a CSV file.
func (s *API) ExportInvoices(req *ExportInvoicesRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "billing_period_start_after", req.BillingPeriodStartAfter)
parameter.AddToQuery(query, "billing_period_start_before", req.BillingPeriodStartBefore)
parameter.AddToQuery(query, "invoice_type", req.InvoiceType)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "file_type", req.FileType)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/export-invoices",
Query: query,
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInvoice: Get a specific invoice, specified by its ID.
func (s *API) GetInvoice(req *GetInvoiceRequest, opts ...scw.RequestOption) (*Invoice, error) {
var err error
if fmt.Sprint(req.InvoiceID) == "" {
return nil, errors.New("field InvoiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/invoices/" + fmt.Sprint(req.InvoiceID) + "",
}
var resp Invoice
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DownloadInvoice: Download a specific invoice, specified by its ID.
func (s *API) DownloadInvoice(req *DownloadInvoiceRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "file_type", req.FileType)
if fmt.Sprint(req.InvoiceID) == "" {
return nil, errors.New("field InvoiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/invoices/" + fmt.Sprint(req.InvoiceID) + "/download",
Query: query,
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDiscounts: List all discounts for your organization and usable categories, products, offers, references, regions and zones where the discount can be applied.
func (s *API) ListDiscounts(req *ListDiscountsRequest, opts ...scw.RequestOption) (*ListDiscountsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/billing/v2beta1/discounts",
Query: query,
}
var resp ListDiscountsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/ 0000775 0000000 0000000 00000000000 14747113137 0024107 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025524 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/block_sdk.go 0000664 0000000 0000000 00000117725 14747113137 0030023 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package block provides methods and message types of the block v1alpha1 API.
package block
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListSnapshotsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListSnapshotsRequestOrderByCreatedAtAsc = ListSnapshotsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListSnapshotsRequestOrderByCreatedAtDesc = ListSnapshotsRequestOrderBy("created_at_desc")
// Order by name (ascending order).
ListSnapshotsRequestOrderByNameAsc = ListSnapshotsRequestOrderBy("name_asc")
// Order by name (descending order).
ListSnapshotsRequestOrderByNameDesc = ListSnapshotsRequestOrderBy("name_desc")
)
func (enum ListSnapshotsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSnapshotsRequestOrderBy) Values() []ListSnapshotsRequestOrderBy {
return []ListSnapshotsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListSnapshotsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSnapshotsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSnapshotsRequestOrderBy(ListSnapshotsRequestOrderBy(tmp).String())
return nil
}
type ListVolumesRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListVolumesRequestOrderByCreatedAtAsc = ListVolumesRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListVolumesRequestOrderByCreatedAtDesc = ListVolumesRequestOrderBy("created_at_desc")
// Order by name (ascending order).
ListVolumesRequestOrderByNameAsc = ListVolumesRequestOrderBy("name_asc")
// Order by name (descending order).
ListVolumesRequestOrderByNameDesc = ListVolumesRequestOrderBy("name_desc")
)
func (enum ListVolumesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListVolumesRequestOrderBy) Values() []ListVolumesRequestOrderBy {
return []ListVolumesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListVolumesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListVolumesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListVolumesRequestOrderBy(ListVolumesRequestOrderBy(tmp).String())
return nil
}
type ReferenceStatus string
const (
// If unspecified, the status of the reference is unknown by default.
ReferenceStatusUnknownStatus = ReferenceStatus("unknown_status")
// When the reference is being attached (transient).
ReferenceStatusAttaching = ReferenceStatus("attaching")
// When the reference attached to a volume.
ReferenceStatusAttached = ReferenceStatus("attached")
// When the reference is being detached (transient).
ReferenceStatusDetaching = ReferenceStatus("detaching")
// When the reference is detached from a volume - the reference ceases to exist.
ReferenceStatusDetached = ReferenceStatus("detached")
// Reference under creation which can be rolled back if an error occurs (transient).
ReferenceStatusCreating = ReferenceStatus("creating")
// Error status.
ReferenceStatusError = ReferenceStatus("error")
)
func (enum ReferenceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ReferenceStatus) Values() []ReferenceStatus {
return []ReferenceStatus{
"unknown_status",
"attaching",
"attached",
"detaching",
"detached",
"creating",
"error",
}
}
func (enum ReferenceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ReferenceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ReferenceStatus(ReferenceStatus(tmp).String())
return nil
}
type ReferenceType string
const (
// If unspecified, the reference type is unknown by default.
ReferenceTypeUnknownType = ReferenceType("unknown_type")
// Reference linked to a snapshot (for snapshots only).
ReferenceTypeLink = ReferenceType("link")
// Exclusive reference that can be associated to a volume (for volumes only).
ReferenceTypeExclusive = ReferenceType("exclusive")
// Access to the volume or snapshot in a read-only mode, without storage write access to the resource.
ReferenceTypeReadOnly = ReferenceType("read_only")
)
func (enum ReferenceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ReferenceType) Values() []ReferenceType {
return []ReferenceType{
"unknown_type",
"link",
"exclusive",
"read_only",
}
}
func (enum ReferenceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ReferenceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ReferenceType(ReferenceType(tmp).String())
return nil
}
type SnapshotStatus string
const (
// If unspecified, the snapshot status is unknown by default.
SnapshotStatusUnknownStatus = SnapshotStatus("unknown_status")
// The snapshot is under creation (transient).
SnapshotStatusCreating = SnapshotStatus("creating")
// Snapshot exists and is not attached to any reference.
SnapshotStatusAvailable = SnapshotStatus("available")
// Snapshot in an error status.
SnapshotStatusError = SnapshotStatus("error")
// Snapshot is being deleted (transient).
SnapshotStatusDeleting = SnapshotStatus("deleting")
// Snapshot was deleted.
SnapshotStatusDeleted = SnapshotStatus("deleted")
// Snapshot attached to one or more references.
SnapshotStatusInUse = SnapshotStatus("in_use")
SnapshotStatusLocked = SnapshotStatus("locked")
SnapshotStatusExporting = SnapshotStatus("exporting")
)
func (enum SnapshotStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SnapshotStatus) Values() []SnapshotStatus {
return []SnapshotStatus{
"unknown_status",
"creating",
"available",
"error",
"deleting",
"deleted",
"in_use",
"locked",
"exporting",
}
}
func (enum SnapshotStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotStatus(SnapshotStatus(tmp).String())
return nil
}
type StorageClass string
const (
// If unspecified, the Storage Class is unknown by default.
StorageClassUnknownStorageClass = StorageClass("unknown_storage_class")
// No specific Storage Class selected.
StorageClassUnspecified = StorageClass("unspecified")
// Classic storage.
StorageClassBssd = StorageClass("bssd")
// Performance storage with lower latency.
StorageClassSbs = StorageClass("sbs")
)
func (enum StorageClass) String() string {
if enum == "" {
// return default value if empty
return "unknown_storage_class"
}
return string(enum)
}
func (enum StorageClass) Values() []StorageClass {
return []StorageClass{
"unknown_storage_class",
"unspecified",
"bssd",
"sbs",
}
}
func (enum StorageClass) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *StorageClass) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = StorageClass(StorageClass(tmp).String())
return nil
}
type VolumeStatus string
const (
// If unspecified, the volume status is unknown by default.
VolumeStatusUnknownStatus = VolumeStatus("unknown_status")
// The volume is under creation (transient).
VolumeStatusCreating = VolumeStatus("creating")
// The volume exists and is not attached to any reference.
VolumeStatusAvailable = VolumeStatus("available")
// The volume exists and is already attached to a reference.
VolumeStatusInUse = VolumeStatus("in_use")
// The volume undergoing deletion (transient).
VolumeStatusDeleting = VolumeStatus("deleting")
VolumeStatusDeleted = VolumeStatus("deleted")
// The volume is being increased (transient).
VolumeStatusResizing = VolumeStatus("resizing")
// The volume is an error status.
VolumeStatusError = VolumeStatus("error")
// The volume is undergoing snapshotting operation (transient).
VolumeStatusSnapshotting = VolumeStatus("snapshotting")
VolumeStatusLocked = VolumeStatus("locked")
// The volume is being updated (transient).
VolumeStatusUpdating = VolumeStatus("updating")
)
func (enum VolumeStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum VolumeStatus) Values() []VolumeStatus {
return []VolumeStatus{
"unknown_status",
"creating",
"available",
"in_use",
"deleting",
"deleted",
"resizing",
"error",
"snapshotting",
"locked",
"updating",
}
}
func (enum VolumeStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeStatus(VolumeStatus(tmp).String())
return nil
}
// Reference: reference.
type Reference struct {
// ID: UUID of the reference.
ID string `json:"id"`
// ProductResourceType: type of resource to which the reference is associated.
ProductResourceType string `json:"product_resource_type"`
// ProductResourceID: UUID of the product resource it refers to (according to the product_resource_type).
ProductResourceID string `json:"product_resource_id"`
// CreatedAt: creation date of the reference.
CreatedAt *time.Time `json:"created_at"`
// Type: type of reference (link, exclusive, read_only).
// Default value: unknown_type
Type ReferenceType `json:"type"`
// Status: status of the reference. Statuses include `attaching`, `attached`, and `detaching`.
// Default value: unknown_status
Status ReferenceStatus `json:"status"`
}
// SnapshotParentVolume: snapshot parent volume.
type SnapshotParentVolume struct {
// ID: parent volume UUID (volume from which the snapshot originates).
ID string `json:"id"`
// Name: name of the parent volume.
Name string `json:"name"`
// Type: volume type of the parent volume.
Type string `json:"type"`
// Status: current status the parent volume.
// Default value: unknown_status
Status VolumeStatus `json:"status"`
}
// VolumeSpecifications: volume specifications.
type VolumeSpecifications struct {
// PerfIops: the maximum IO/s expected, according to the different options available in stock (`5000 | 15000`).
PerfIops *uint32 `json:"perf_iops"`
// Class: the storage class of the volume.
// Default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// CreateVolumeRequestFromEmpty: create volume request from empty.
type CreateVolumeRequestFromEmpty struct {
// Size: must be compliant with the minimum (1 GB) and maximum (10 TB) allowed size.
Size scw.Size `json:"size"`
}
// CreateVolumeRequestFromSnapshot: create volume request from snapshot.
type CreateVolumeRequestFromSnapshot struct {
// Size: must be compliant with the minimum (1 GB) and maximum (10 TB) allowed size.
// Size is optional and is used only if a resize of the volume is requested, otherwise original snapshot size will be used.
Size *scw.Size `json:"size"`
// SnapshotID: source snapshot from which volume will be created.
SnapshotID string `json:"snapshot_id"`
}
// Snapshot: snapshot.
type Snapshot struct {
// ID: UUID of the snapshot.
ID string `json:"id"`
// Name: name of the snapshot.
Name string `json:"name"`
// ParentVolume: if the parent volume was deleted, value is null.
ParentVolume *SnapshotParentVolume `json:"parent_volume"`
// Size: size in bytes of the snapshot.
Size scw.Size `json:"size"`
// ProjectID: UUID of the project the snapshot belongs to.
ProjectID string `json:"project_id"`
// CreatedAt: creation date of the snapshot.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the properties of a snapshot.
UpdatedAt *time.Time `json:"updated_at"`
// References: list of the references to the snapshot.
References []*Reference `json:"references"`
// Status: current status of the snapshot (available, in_use, ...).
// Default value: unknown_status
Status SnapshotStatus `json:"status"`
// Tags: list of tags assigned to the volume.
Tags []string `json:"tags"`
// Zone: snapshot zone.
Zone scw.Zone `json:"zone"`
// Class: storage class of the snapshot.
// Default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// VolumeType: volume type.
type VolumeType struct {
// Type: volume type.
Type string `json:"type"`
// Pricing: price of the volume billed in GB/hour.
Pricing *scw.Money `json:"pricing"`
// SnapshotPricing: price of the snapshot billed in GB/hour.
SnapshotPricing *scw.Money `json:"snapshot_pricing"`
// Specs: volume specifications of the volume type.
Specs *VolumeSpecifications `json:"specs"`
}
// Volume: volume.
type Volume struct {
// ID: UUID of the volume.
ID string `json:"id"`
// Name: name of the volume.
Name string `json:"name"`
// Type: volume type.
Type string `json:"type"`
// Size: volume size in bytes.
Size scw.Size `json:"size"`
// ProjectID: UUID of the project to which the volume belongs.
ProjectID string `json:"project_id"`
// CreatedAt: creation date of the volume.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update of the properties of a volume.
UpdatedAt *time.Time `json:"updated_at"`
// References: list of the references to the volume.
References []*Reference `json:"references"`
// ParentSnapshotID: when a volume is created from a snapshot, is the UUID of the snapshot from which the volume has been created.
ParentSnapshotID *string `json:"parent_snapshot_id"`
// Status: current status of the volume (available, in_use, ...).
// Default value: unknown_status
Status VolumeStatus `json:"status"`
// Tags: list of tags assigned to the volume.
Tags []string `json:"tags"`
// Zone: volume zone.
Zone scw.Zone `json:"zone"`
// Specs: specifications of the volume.
Specs *VolumeSpecifications `json:"specs"`
// LastDetachedAt: last time the volume was detached.
LastDetachedAt *time.Time `json:"last_detached_at"`
}
// CreateSnapshotRequest: create snapshot request.
type CreateSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume to snapshot.
VolumeID string `json:"volume_id"`
// Name: name of the snapshot.
Name string `json:"name"`
// ProjectID: UUID of the project to which the volume and the snapshot belong.
ProjectID string `json:"project_id"`
// Tags: list of tags assigned to the snapshot.
Tags []string `json:"tags"`
}
// CreateVolumeRequest: create volume request.
type CreateVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the volume.
Name string `json:"name"`
// PerfIops: the maximum IO/s expected, according to the different options available in stock (`5000 | 15000`).
// Precisely one of PerfIops must be set.
PerfIops *uint32 `json:"perf_iops,omitempty"`
// ProjectID: UUID of the project the volume belongs to.
ProjectID string `json:"project_id"`
// FromEmpty: specify the size of the new volume if creating a new one from scratch.
// Precisely one of FromEmpty, FromSnapshot must be set.
FromEmpty *CreateVolumeRequestFromEmpty `json:"from_empty,omitempty"`
// FromSnapshot: specify the snapshot ID of the original snapshot.
// Precisely one of FromEmpty, FromSnapshot must be set.
FromSnapshot *CreateVolumeRequestFromSnapshot `json:"from_snapshot,omitempty"`
// Tags: list of tags assigned to the volume.
Tags []string `json:"tags"`
}
// DeleteSnapshotRequest: delete snapshot request.
type DeleteSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// DeleteVolumeRequest: delete volume request.
type DeleteVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume.
VolumeID string `json:"-"`
}
// ExportSnapshotToObjectStorageRequest: export snapshot to object storage request.
type ExportSnapshotToObjectStorageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
// Bucket: scaleway Object Storage bucket where the object is stored.
Bucket string `json:"bucket"`
// Key: the object key inside the given bucket.
Key string `json:"key"`
}
// GetSnapshotRequest: get snapshot request.
type GetSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// GetVolumeRequest: get volume request.
type GetVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume.
VolumeID string `json:"-"`
}
// ImportSnapshotFromObjectStorageRequest: import snapshot from object storage request.
type ImportSnapshotFromObjectStorageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Bucket: scaleway Object Storage bucket where the object is stored.
Bucket string `json:"bucket"`
// Key: the object key inside the given bucket.
Key string `json:"key"`
// Name: name of the snapshot.
Name string `json:"name"`
// ProjectID: UUID of the Project to which the volume and the snapshot belong.
ProjectID string `json:"project_id"`
// Tags: list of tags assigned to the snapshot.
Tags []string `json:"tags"`
// Size: size of the snapshot.
Size *scw.Size `json:"size,omitempty"`
}
// ImportSnapshotFromS3Request: import snapshot from s3 request.
type ImportSnapshotFromS3Request struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Bucket: scaleway Object Storage bucket where the object is stored.
Bucket string `json:"bucket"`
// Key: the object key inside the given bucket.
Key string `json:"key"`
// Name: name of the snapshot.
Name string `json:"name"`
// ProjectID: UUID of the Project to which the volume and the snapshot belong.
ProjectID string `json:"project_id"`
// Tags: list of tags assigned to the snapshot.
Tags []string `json:"tags"`
// Size: size of the snapshot.
Size *scw.Size `json:"size,omitempty"`
}
// ListSnapshotsRequest: list snapshots request.
type ListSnapshotsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: criteria to use when ordering the list.
// Default value: created_at_asc
OrderBy ListSnapshotsRequestOrderBy `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size, defines how many entries are returned in one page, must be lower or equal to 100.
PageSize *uint32 `json:"-"`
// VolumeID: filter snapshots by the ID of the original volume.
VolumeID *string `json:"-"`
// Name: filter snapshots by their names.
Name *string `json:"-"`
}
// ListSnapshotsResponse: list snapshots response.
type ListSnapshotsResponse struct {
// Snapshots: paginated returned list of snapshots.
Snapshots []*Snapshot `json:"snapshots"`
// TotalCount: total number of snpashots in the project.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSnapshotsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Snapshots = append(r.Snapshots, results.Snapshots...)
r.TotalCount += uint64(len(results.Snapshots))
return uint64(len(results.Snapshots)), nil
}
// ListVolumeTypesRequest: list volume types request.
type ListVolumeTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size, defines how many entries are returned in one page, must be lower or equal to 100.
PageSize *uint32 `json:"-"`
}
// ListVolumeTypesResponse: list volume types response.
type ListVolumeTypesResponse struct {
// VolumeTypes: returns paginated list of volume-types.
VolumeTypes []*VolumeType `json:"volume_types"`
// TotalCount: total number of volume-types currently available in stock.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVolumeTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVolumeTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListVolumeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.VolumeTypes = append(r.VolumeTypes, results.VolumeTypes...)
r.TotalCount += uint64(len(results.VolumeTypes))
return uint64(len(results.VolumeTypes)), nil
}
// ListVolumesRequest: list volumes request.
type ListVolumesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: criteria to use when ordering the list.
// Default value: created_at_asc
OrderBy ListVolumesRequestOrderBy `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size, defines how many entries are returned in one page, must be lower or equal to 100.
PageSize *uint32 `json:"-"`
// Name: filter the return volumes by their names.
Name *string `json:"-"`
// ProductResourceID: filter by a product resource ID linked to this volume (such as an Instance ID).
ProductResourceID *string `json:"-"`
// Tags: filter by tags. Only volumes with one or more matching tags will be returned.
Tags []string `json:"-"`
}
// ListVolumesResponse: list volumes response.
type ListVolumesResponse struct {
// Volumes: paginated returned list of volumes.
Volumes []*Volume `json:"volumes"`
// TotalCount: total number of volumes in the project.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVolumesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVolumesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListVolumesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Volumes = append(r.Volumes, results.Volumes...)
r.TotalCount += uint64(len(results.Volumes))
return uint64(len(results.Volumes)), nil
}
// UpdateSnapshotRequest: update snapshot request.
type UpdateSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
// Name: when defined, is the name of the snapshot.
Name *string `json:"name,omitempty"`
// Tags: list of tags assigned to the snapshot.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateVolumeRequest: update volume request.
type UpdateVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume.
VolumeID string `json:"-"`
// Name: when defined, is the new name of the volume.
Name *string `json:"name,omitempty"`
// Size: size in bytes of the volume, with a granularity of 1 GB (10^9 bytes).
// Must be compliant with the minimum (1GB) and maximum (10TB) allowed size.
Size *scw.Size `json:"size,omitempty"`
// Tags: list of tags assigned to the volume.
Tags *[]string `json:"tags,omitempty"`
// PerfIops: the selected value must be available for the volume's current storage class.
PerfIops *uint32 `json:"perf_iops,omitempty"`
}
// This API allows you to manage your Block Storage volumes.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// ListVolumeTypes: List all available volume types in a specified zone. The volume types listed are ordered by name in ascending order.
func (s *API) ListVolumeTypes(req *ListVolumeTypesRequest, opts ...scw.RequestOption) (*ListVolumeTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volume-types",
Query: query,
}
var resp ListVolumeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVolumes: List all existing volumes in a specified zone. By default, the volumes listed are ordered by creation date in ascending order. This can be modified via the `order_by` field.
func (s *API) ListVolumes(req *ListVolumesRequest, opts ...scw.RequestOption) (*ListVolumesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "product_resource_id", req.ProductResourceID)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volumes",
Query: query,
}
var resp ListVolumesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateVolume: To create a new volume from scratch, you must specify `from_empty` and the `size`.
// To create a volume from an existing snapshot, specify `from_snapshot` and the `snapshot_id` in the request payload instead, size is optional and can be specified if you need to extend the original size. The volume will take on the same volume class and underlying IOPS limitations as the original snapshot.
func (s *API) CreateVolume(req *CreateVolumeRequest, opts ...scw.RequestOption) (*Volume, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("vol")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volumes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Volume
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetVolume: Retrieve technical information about a specific volume. Details such as size, type, and status are returned in the response.
func (s *API) GetVolume(req *GetVolumeRequest, opts ...scw.RequestOption) (*Volume, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return nil, errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
var resp Volume
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteVolume: You must specify the `volume_id` of the volume you want to delete. The volume must not be in the `in_use` status.
func (s *API) DeleteVolume(req *DeleteVolumeRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateVolume: Update the technical details of a volume, such as its name, tags, or its new size and `volume_type` (within the same Block Storage class).
// You can only resize a volume to a larger size. It is currently not possible to change your Block Storage Class.
func (s *API) UpdateVolume(req *UpdateVolumeRequest, opts ...scw.RequestOption) (*Volume, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return nil, errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Volume
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSnapshots: List all available snapshots in a specified zone. By default, the snapshots listed are ordered by creation date in ascending order. This can be modified via the `order_by` field.
func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "volume_id", req.VolumeID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots",
Query: query,
}
var resp ListSnapshotsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnapshot: Retrieve technical information about a specific snapshot. Details such as size, volume type, and status are returned in the response.
func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnapshot: To create a snapshot, the volume must be in the `in_use` or the `available` status.
// If your volume is in a transient state, you need to wait until the end of the current operation.
func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("snp")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: ImportSnapshotFromS3: Import a snapshot from a Scaleway Object Storage bucket
// The bucket must contain a QCOW2 image.
// The bucket can be imported into any Availability Zone as long as it is in the same region as the bucket.
func (s *API) ImportSnapshotFromS3(req *ImportSnapshotFromS3Request, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/import-from-s3",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ImportSnapshotFromObjectStorage: The bucket must contain a QCOW2 image.
// The bucket can be imported into any Availability Zone as long as it is in the same region as the bucket.
func (s *API) ImportSnapshotFromObjectStorage(req *ImportSnapshotFromObjectStorageRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/import-from-object-storage",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ExportSnapshotToObjectStorage: The snapshot is exported in QCOW2 format.
// The snapshot must not be in transient state.
func (s *API) ExportSnapshotToObjectStorage(req *ExportSnapshotToObjectStorageRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "/export-to-object-storage",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnapshot: You must specify the `snapshot_id` of the snapshot you want to delete. The snapshot must not be in use.
func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateSnapshot: Update the name or tags of the snapshot.
func (s *API) UpdateSnapshot(req *UpdateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/block/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/snapshot_utils.go 0000664 0000000 0000000 00000003607 14747113137 0031140 0 ustar 00root root 0000000 0000000 package block
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForSnapshotRequest is used by WaitForSnapshot method.
type WaitForSnapshotRequest struct {
SnapshotID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
// If set, will wait until this specific status has been reached or the
// snapshot has an error status. This is useful when we need to wait for
// the snapshot to transition from "in_use" to "available".
TerminalStatus *SnapshotStatus
}
// WaitForSnapshot wait for the snapshot to be in a "terminal state" before returning.
func (s *API) WaitForSnapshot(req *WaitForSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[SnapshotStatus]struct{}{
SnapshotStatusError: {},
SnapshotStatusLocked: {},
SnapshotStatusDeleted: {},
}
if req.TerminalStatus != nil {
terminalStatus[*req.TerminalStatus] = struct{}{}
} else {
terminalStatus[SnapshotStatusAvailable] = struct{}{}
terminalStatus[SnapshotStatusInUse] = struct{}{}
}
snapshot, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetSnapshot(&GetSnapshotRequest{
SnapshotID: req.SnapshotID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for snapshot failed")
}
return snapshot.(*Snapshot), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027361 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000003066 14747113137 0031552 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
block "github.com/scaleway/scaleway-sdk-go/api/block/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepVolumes(scwClient *scw.Client, zone scw.Zone) error {
blockAPI := block.NewAPI(scwClient)
listVolumes, err := blockAPI.ListVolumes(
&block.ListVolumesRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing volume in (%s) in sweeper: %s", zone, err)
}
for _, volume := range listVolumes.Volumes {
err := blockAPI.DeleteVolume(&block.DeleteVolumeRequest{
VolumeID: volume.ID,
Zone: zone,
})
if err != nil {
return fmt.Errorf("error deleting volume in sweeper: %s", err)
}
}
return nil
}
func SweepSnapshots(scwClient *scw.Client, zone scw.Zone) error {
blockAPI := block.NewAPI(scwClient)
listSnapshots, err := blockAPI.ListSnapshots(
&block.ListSnapshotsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing snapshot in (%s) in sweeper: %s", zone, err)
}
for _, snapshot := range listSnapshots.Snapshots {
err := blockAPI.DeleteSnapshot(&block.DeleteSnapshotRequest{
SnapshotID: snapshot.ID,
Zone: zone,
})
if err != nil {
return fmt.Errorf("error deleting snapshot in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&block.API{}).Zones() {
err := SweepVolumes(scwClient, zone)
if err != nil {
return err
}
err = SweepSnapshots(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/block/v1alpha1/volume_utils.go 0000664 0000000 0000000 00000010207 14747113137 0030602 0 ustar 00root root 0000000 0000000 package block
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForVolumeRequest is used by WaitForVolume method.
type WaitForVolumeRequest struct {
VolumeID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
// If set, will wait until this specific status has been reached or the
// volume has an error status. This is useful when we need to wait for
// the volume to transition from "in_use" to "available".
TerminalStatus *VolumeStatus
}
// WaitForVolume waits for the volume to be in a "terminal state" before returning.
func (s *API) WaitForVolume(req *WaitForVolumeRequest, opts ...scw.RequestOption) (*Volume, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[VolumeStatus]struct{}{
VolumeStatusError: {},
VolumeStatusLocked: {},
VolumeStatusDeleted: {},
}
if req.TerminalStatus != nil {
terminalStatus[*req.TerminalStatus] = struct{}{}
} else {
terminalStatus[VolumeStatusAvailable] = struct{}{}
terminalStatus[VolumeStatusInUse] = struct{}{}
}
volume, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetVolume(&GetVolumeRequest{
VolumeID: req.VolumeID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for volume failed")
}
return volume.(*Volume), nil
}
// WaitForVolumeAndReferencesRequest is used by WaitForVolumeAndReferences method.
type WaitForVolumeAndReferencesRequest struct {
VolumeID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
VolumeTerminalStatus *VolumeStatus
ReferenceTerminalStatus *ReferenceStatus
}
// WaitForVolumeAndReferences waits for the volume and its references to be in a "terminal state" before returning.
func (s *API) WaitForVolumeAndReferences(req *WaitForVolumeAndReferencesRequest, opts ...scw.RequestOption) (*Volume, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[VolumeStatus]struct{}{
VolumeStatusError: {},
VolumeStatusLocked: {},
VolumeStatusDeleted: {},
}
if req.VolumeTerminalStatus != nil {
terminalStatus[*req.VolumeTerminalStatus] = struct{}{}
} else {
terminalStatus[VolumeStatusAvailable] = struct{}{}
terminalStatus[VolumeStatusInUse] = struct{}{}
}
referenceTerminalStatus := map[ReferenceStatus]struct{}{
ReferenceStatusError: {},
}
if req.ReferenceTerminalStatus != nil {
referenceTerminalStatus[*req.ReferenceTerminalStatus] = struct{}{}
} else {
referenceTerminalStatus[ReferenceStatusAttached] = struct{}{}
referenceTerminalStatus[ReferenceStatusDetached] = struct{}{}
}
volume, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
volume, err := s.GetVolume(&GetVolumeRequest{
VolumeID: req.VolumeID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
referencesAreTerminal := true
for _, reference := range volume.References {
_, referenceIsTerminal := referenceTerminalStatus[reference.Status]
referencesAreTerminal = referencesAreTerminal && referenceIsTerminal
}
_, isTerminal := terminalStatus[volume.Status]
return volume, isTerminal && referencesAreTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Volume failed")
}
return volume.(*Volume), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/cockpit/ 0000775 0000000 0000000 00000000000 14747113137 0024451 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/cockpit/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024777 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/cockpit/v1/cockpit_sdk.go 0000664 0000000 0000000 00000215124 14747113137 0027630 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package cockpit provides methods and message types of the cockpit v1 API.
package cockpit
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DataSourceOrigin string
const (
// Unknown data source origin.
DataSourceOriginUnknownOrigin = DataSourceOrigin("unknown_origin")
// Data source managed by Scaleway, used to store and query metrics and logs from Scaleway resources.
DataSourceOriginScaleway = DataSourceOrigin("scaleway")
// Data source created by the user, used to store and query metrics, logs and traces from user's custom resources.
DataSourceOriginExternal = DataSourceOrigin("external")
// Data source created by the user, used to store and query metrics, logs and traces from user's custom resources.
DataSourceOriginCustom = DataSourceOrigin("custom")
)
func (enum DataSourceOrigin) String() string {
if enum == "" {
// return default value if empty
return "unknown_origin"
}
return string(enum)
}
func (enum DataSourceOrigin) Values() []DataSourceOrigin {
return []DataSourceOrigin{
"unknown_origin",
"scaleway",
"external",
"custom",
}
}
func (enum DataSourceOrigin) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DataSourceOrigin) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DataSourceOrigin(DataSourceOrigin(tmp).String())
return nil
}
type DataSourceType string
const (
// Unknown data source type.
DataSourceTypeUnknownType = DataSourceType("unknown_type")
// Metrics data source type, used to store and query metrics using Grafana Mimir.
DataSourceTypeMetrics = DataSourceType("metrics")
// Logs data source type, used to store and query logs using Grafana Loki.
DataSourceTypeLogs = DataSourceType("logs")
// Traces data source type, used to store and query traces using Grafana Tempo.
DataSourceTypeTraces = DataSourceType("traces")
)
func (enum DataSourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum DataSourceType) Values() []DataSourceType {
return []DataSourceType{
"unknown_type",
"metrics",
"logs",
"traces",
}
}
func (enum DataSourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DataSourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DataSourceType(DataSourceType(tmp).String())
return nil
}
type GrafanaUserRole string
const (
// Unknown role.
GrafanaUserRoleUnknownRole = GrafanaUserRole("unknown_role")
// Editor role.
GrafanaUserRoleEditor = GrafanaUserRole("editor")
// Viewer role.
GrafanaUserRoleViewer = GrafanaUserRole("viewer")
)
func (enum GrafanaUserRole) String() string {
if enum == "" {
// return default value if empty
return "unknown_role"
}
return string(enum)
}
func (enum GrafanaUserRole) Values() []GrafanaUserRole {
return []GrafanaUserRole{
"unknown_role",
"editor",
"viewer",
}
}
func (enum GrafanaUserRole) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GrafanaUserRole) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GrafanaUserRole(GrafanaUserRole(tmp).String())
return nil
}
type ListDataSourcesRequestOrderBy string
const (
ListDataSourcesRequestOrderByCreatedAtAsc = ListDataSourcesRequestOrderBy("created_at_asc")
ListDataSourcesRequestOrderByCreatedAtDesc = ListDataSourcesRequestOrderBy("created_at_desc")
ListDataSourcesRequestOrderByNameAsc = ListDataSourcesRequestOrderBy("name_asc")
ListDataSourcesRequestOrderByNameDesc = ListDataSourcesRequestOrderBy("name_desc")
ListDataSourcesRequestOrderByTypeAsc = ListDataSourcesRequestOrderBy("type_asc")
ListDataSourcesRequestOrderByTypeDesc = ListDataSourcesRequestOrderBy("type_desc")
)
func (enum ListDataSourcesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDataSourcesRequestOrderBy) Values() []ListDataSourcesRequestOrderBy {
return []ListDataSourcesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"type_asc",
"type_desc",
}
}
func (enum ListDataSourcesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDataSourcesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDataSourcesRequestOrderBy(ListDataSourcesRequestOrderBy(tmp).String())
return nil
}
type ListGrafanaUsersRequestOrderBy string
const (
ListGrafanaUsersRequestOrderByLoginAsc = ListGrafanaUsersRequestOrderBy("login_asc")
ListGrafanaUsersRequestOrderByLoginDesc = ListGrafanaUsersRequestOrderBy("login_desc")
)
func (enum ListGrafanaUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "login_asc"
}
return string(enum)
}
func (enum ListGrafanaUsersRequestOrderBy) Values() []ListGrafanaUsersRequestOrderBy {
return []ListGrafanaUsersRequestOrderBy{
"login_asc",
"login_desc",
}
}
func (enum ListGrafanaUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGrafanaUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGrafanaUsersRequestOrderBy(ListGrafanaUsersRequestOrderBy(tmp).String())
return nil
}
type ListManagedAlertsRequestOrderBy string
const (
ListManagedAlertsRequestOrderByCreatedAtAsc = ListManagedAlertsRequestOrderBy("created_at_asc")
ListManagedAlertsRequestOrderByCreatedAtDesc = ListManagedAlertsRequestOrderBy("created_at_desc")
ListManagedAlertsRequestOrderByNameAsc = ListManagedAlertsRequestOrderBy("name_asc")
ListManagedAlertsRequestOrderByNameDesc = ListManagedAlertsRequestOrderBy("name_desc")
ListManagedAlertsRequestOrderByTypeAsc = ListManagedAlertsRequestOrderBy("type_asc")
ListManagedAlertsRequestOrderByTypeDesc = ListManagedAlertsRequestOrderBy("type_desc")
)
func (enum ListManagedAlertsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListManagedAlertsRequestOrderBy) Values() []ListManagedAlertsRequestOrderBy {
return []ListManagedAlertsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"type_asc",
"type_desc",
}
}
func (enum ListManagedAlertsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListManagedAlertsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListManagedAlertsRequestOrderBy(ListManagedAlertsRequestOrderBy(tmp).String())
return nil
}
type ListPlansRequestOrderBy string
const (
ListPlansRequestOrderByNameAsc = ListPlansRequestOrderBy("name_asc")
ListPlansRequestOrderByNameDesc = ListPlansRequestOrderBy("name_desc")
)
func (enum ListPlansRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListPlansRequestOrderBy) Values() []ListPlansRequestOrderBy {
return []ListPlansRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListPlansRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPlansRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPlansRequestOrderBy(ListPlansRequestOrderBy(tmp).String())
return nil
}
type ListTokensRequestOrderBy string
const (
ListTokensRequestOrderByCreatedAtAsc = ListTokensRequestOrderBy("created_at_asc")
ListTokensRequestOrderByCreatedAtDesc = ListTokensRequestOrderBy("created_at_desc")
ListTokensRequestOrderByNameAsc = ListTokensRequestOrderBy("name_asc")
ListTokensRequestOrderByNameDesc = ListTokensRequestOrderBy("name_desc")
)
func (enum ListTokensRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTokensRequestOrderBy) Values() []ListTokensRequestOrderBy {
return []ListTokensRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListTokensRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTokensRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTokensRequestOrderBy(ListTokensRequestOrderBy(tmp).String())
return nil
}
type PlanName string
const (
PlanNameUnknownName = PlanName("unknown_name")
PlanNameFree = PlanName("free")
PlanNamePremium = PlanName("premium")
PlanNameCustom = PlanName("custom")
)
func (enum PlanName) String() string {
if enum == "" {
// return default value if empty
return "unknown_name"
}
return string(enum)
}
func (enum PlanName) Values() []PlanName {
return []PlanName{
"unknown_name",
"free",
"premium",
"custom",
}
}
func (enum PlanName) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlanName) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlanName(PlanName(tmp).String())
return nil
}
type TokenScope string
const (
// The token's permission scope is unknown.
TokenScopeUnknownScope = TokenScope("unknown_scope")
// Token has permission to read data from metrics data sources.
TokenScopeReadOnlyMetrics = TokenScope("read_only_metrics")
// Token has permission to write data in metrics data sources.
TokenScopeWriteOnlyMetrics = TokenScope("write_only_metrics")
// Token has permission to read and write prometheus rules in metrics data sources.
TokenScopeFullAccessMetricsRules = TokenScope("full_access_metrics_rules")
// Token has permission to read data from logs data sources.
TokenScopeReadOnlyLogs = TokenScope("read_only_logs")
// Token has permission to write data in logs data sources.
TokenScopeWriteOnlyLogs = TokenScope("write_only_logs")
// Token has permission to read and write prometheus rules in logs data sources.
TokenScopeFullAccessLogsRules = TokenScope("full_access_logs_rules")
// Token has permission to read and write the Alert manager API.
TokenScopeFullAccessAlertManager = TokenScope("full_access_alert_manager")
// Token has permission to read data from traces data sources.
TokenScopeReadOnlyTraces = TokenScope("read_only_traces")
// Token has permission to write data in traces data sources.
TokenScopeWriteOnlyTraces = TokenScope("write_only_traces")
)
func (enum TokenScope) String() string {
if enum == "" {
// return default value if empty
return "unknown_scope"
}
return string(enum)
}
func (enum TokenScope) Values() []TokenScope {
return []TokenScope{
"unknown_scope",
"read_only_metrics",
"write_only_metrics",
"full_access_metrics_rules",
"read_only_logs",
"write_only_logs",
"full_access_logs_rules",
"full_access_alert_manager",
"read_only_traces",
"write_only_traces",
}
}
func (enum TokenScope) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TokenScope) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TokenScope(TokenScope(tmp).String())
return nil
}
type UsageUnit string
const (
UsageUnitUnknownUnit = UsageUnit("unknown_unit")
UsageUnitBytes = UsageUnit("bytes")
UsageUnitSamples = UsageUnit("samples")
)
func (enum UsageUnit) String() string {
if enum == "" {
// return default value if empty
return "unknown_unit"
}
return string(enum)
}
func (enum UsageUnit) Values() []UsageUnit {
return []UsageUnit{
"unknown_unit",
"bytes",
"samples",
}
}
func (enum UsageUnit) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *UsageUnit) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = UsageUnit(UsageUnit(tmp).String())
return nil
}
// ContactPointEmail: contact point email.
type ContactPointEmail struct {
To string `json:"to"`
}
// GetConfigResponseRetention: get config response retention.
type GetConfigResponseRetention struct {
MinDays uint32 `json:"min_days"`
MaxDays uint32 `json:"max_days"`
DefaultDays uint32 `json:"default_days"`
}
// ContactPoint: Contact point.
type ContactPoint struct {
// Email: email address to send alerts to.
// Precisely one of Email must be set.
Email *ContactPointEmail `json:"email,omitempty"`
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"region"`
}
// DataSource: Data source.
type DataSource struct {
// ID: ID of the data source.
ID string `json:"id"`
// ProjectID: ID of the Project the data source belongs to.
ProjectID string `json:"project_id"`
// Name: data source name.
Name string `json:"name"`
// URL: data source URL.
URL string `json:"url"`
// Type: data source type.
// Default value: unknown_type
Type DataSourceType `json:"type"`
// Origin: data source origin.
// Default value: unknown_origin
Origin DataSourceOrigin `json:"origin"`
// CreatedAt: date the data source was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the data source was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// SynchronizedWithGrafana: indicates whether the data source is synchronized with Grafana.
SynchronizedWithGrafana bool `json:"synchronized_with_grafana"`
// RetentionDays: bETA - Duration for which the data will be retained in the data source.
RetentionDays uint32 `json:"retention_days"`
// Region: region of the data source.
Region scw.Region `json:"region"`
}
// GrafanaProductDashboard: Grafana dashboard.
type GrafanaProductDashboard struct {
// Name: dashboard name.
Name string `json:"name"`
// Title: dashboard title.
Title string `json:"title"`
// URL: dashboard URL.
URL string `json:"url"`
// Tags: dashboard tags.
Tags []string `json:"tags"`
// Variables: dashboard variables.
Variables []string `json:"variables"`
}
// GrafanaUser: Grafana user.
type GrafanaUser struct {
// ID: ID of the Grafana user.
ID uint32 `json:"id"`
// Login: username of the Grafana user.
Login string `json:"login"`
// Role: role assigned to the Grafana user.
// Default value: unknown_role
Role GrafanaUserRole `json:"role"`
// Password: grafana user's password.
Password *string `json:"password"`
}
// Alert: alert.
type Alert struct {
ProductFamily string `json:"product_family"`
Product string `json:"product"`
Name string `json:"name"`
Rule string `json:"rule"`
Description string `json:"description"`
}
// Plan: Type of pricing plan.
type Plan struct {
// Name: name of a given pricing plan.
// Default value: unknown_name
Name PlanName `json:"name"`
// RetentionMetricsInterval: interval of time during which Scaleway's Cockpit keeps your metrics.
RetentionMetricsInterval *scw.Duration `json:"retention_metrics_interval"`
// RetentionLogsInterval: interval of time during which Scaleway's Cockpit keeps your logs.
RetentionLogsInterval *scw.Duration `json:"retention_logs_interval"`
// RetentionTracesInterval: interval of time during which Scaleway's Cockpit keeps your traces.
RetentionTracesInterval *scw.Duration `json:"retention_traces_interval"`
// SampleIngestionPrice: ingestion price in cents for 1 million samples.
SampleIngestionPrice uint32 `json:"sample_ingestion_price"`
// LogsIngestionPrice: ingestion price in cents for 1 GB of logs.
LogsIngestionPrice uint32 `json:"logs_ingestion_price"`
// TracesIngestionPrice: ingestion price in cents for 1 GB of traces.
TracesIngestionPrice uint32 `json:"traces_ingestion_price"`
// MonthlyPrice: retention price in euros per month.
MonthlyPrice uint32 `json:"monthly_price"`
}
// Token: Token.
type Token struct {
// ID: ID of the token.
ID string `json:"id"`
// ProjectID: ID of the Project the token belongs to.
ProjectID string `json:"project_id"`
// Name: name of the token.
Name string `json:"name"`
// CreatedAt: token creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: token last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Scopes: token permission scopes.
Scopes []TokenScope `json:"scopes"`
// SecretKey: token secret key.
SecretKey *string `json:"secret_key"`
// Region: regions where the token is located.
Region scw.Region `json:"region"`
}
// Usage: Data source usage.
type Usage struct {
// DataSourceID: ID of the data source.
DataSourceID *string `json:"data_source_id"`
// ProjectID: ID of the Project the data source belongs to.
ProjectID string `json:"project_id"`
// DataSourceOrigin: origin of the data source.
// Default value: unknown_origin
DataSourceOrigin DataSourceOrigin `json:"data_source_origin"`
// DataSourceType: type of the data source.
// Default value: unknown_type
DataSourceType DataSourceType `json:"data_source_type"`
// Unit: unit of the data source usage.
// Default value: unknown_unit
Unit UsageUnit `json:"unit"`
// Interval: interval for the data source usage.
Interval *scw.Duration `json:"interval"`
// QuantityOverInterval: data source usage for the given interval.
QuantityOverInterval uint64 `json:"quantity_over_interval"`
// Region: region of the data source usage.
Region scw.Region `json:"region"`
}
// AlertManager: Alert manager information.
type AlertManager struct {
// AlertManagerURL: alert manager URL.
AlertManagerURL *string `json:"alert_manager_url"`
// AlertManagerEnabled: the Alert manager is enabled.
AlertManagerEnabled bool `json:"alert_manager_enabled"`
// ManagedAlertsEnabled: managed alerts are enabled.
ManagedAlertsEnabled bool `json:"managed_alerts_enabled"`
// Region: regions where the Alert manager is enabled.
Region scw.Region `json:"region"`
}
// GetConfigResponse: Cockpit configuration.
type GetConfigResponse struct {
// CustomMetricsRetention: custom metrics retention configuration.
CustomMetricsRetention *GetConfigResponseRetention `json:"custom_metrics_retention"`
// CustomLogsRetention: custom logs retention configuration.
CustomLogsRetention *GetConfigResponseRetention `json:"custom_logs_retention"`
// CustomTracesRetention: custom traces retention configuration.
CustomTracesRetention *GetConfigResponseRetention `json:"custom_traces_retention"`
// ProductMetricsRetention: scaleway metrics retention configuration.
ProductMetricsRetention *GetConfigResponseRetention `json:"product_metrics_retention"`
// ProductLogsRetention: scaleway logs retention configuration.
ProductLogsRetention *GetConfigResponseRetention `json:"product_logs_retention"`
}
// GlobalAPICreateGrafanaUserRequest: Create a Grafana user.
type GlobalAPICreateGrafanaUserRequest struct {
// ProjectID: ID of the Project in which to create the Grafana user.
ProjectID string `json:"project_id"`
// Login: username of the Grafana user. Note that the `admin` username is not available for creation.
Login string `json:"login"`
// Role: role assigned to the Grafana user.
// Default value: unknown_role
Role GrafanaUserRole `json:"role"`
}
// GlobalAPIDeleteGrafanaUserRequest: Delete a Grafana user.
type GlobalAPIDeleteGrafanaUserRequest struct {
// GrafanaUserID: ID of the Grafana user.
GrafanaUserID uint32 `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
}
// GlobalAPIGetCurrentPlanRequest: Retrieve a pricing plan for the given Project.
type GlobalAPIGetCurrentPlanRequest struct {
// ProjectID: ID of the Project.
ProjectID string `json:"-"`
}
// GlobalAPIGetGrafanaProductDashboardRequest: Retrieve a specific dashboard.
type GlobalAPIGetGrafanaProductDashboardRequest struct {
// DashboardName: name of the dashboard.
DashboardName string `json:"-"`
// ProjectID: ID of the Project the dashboard belongs to.
ProjectID string `json:"-"`
}
// GlobalAPIGetGrafanaRequest: Request a Grafana.
type GlobalAPIGetGrafanaRequest struct {
// ProjectID: ID of the Project.
ProjectID string `json:"-"`
}
// GlobalAPIListGrafanaProductDashboardsRequest: Retrieve a list of available product dashboards.
type GlobalAPIListGrafanaProductDashboardsRequest struct {
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size.
PageSize *uint32 `json:"-"`
// Tags: tags to filter for.
Tags []string `json:"-"`
}
// GlobalAPIListGrafanaUsersRequest: List all Grafana users.
type GlobalAPIListGrafanaUsersRequest struct {
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size.
PageSize *uint32 `json:"-"`
// OrderBy: order of the Grafana users.
// Default value: login_asc
OrderBy ListGrafanaUsersRequestOrderBy `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
}
// GlobalAPIListPlansRequest: Retrieve a list of available pricing plans.
type GlobalAPIListPlansRequest struct {
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size.
PageSize *uint32 `json:"-"`
// OrderBy: default value: name_asc
OrderBy ListPlansRequestOrderBy `json:"-"`
}
// GlobalAPIResetGrafanaUserPasswordRequest: Reset a Grafana user's password.
type GlobalAPIResetGrafanaUserPasswordRequest struct {
// GrafanaUserID: ID of the Grafana user.
GrafanaUserID uint32 `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"project_id"`
}
// GlobalAPISelectPlanRequest: Select a specific pricing plan.
type GlobalAPISelectPlanRequest struct {
// ProjectID: ID of the Project.
ProjectID string `json:"project_id"`
// PlanName: name of the pricing plan.
// Default value: unknown_name
PlanName PlanName `json:"plan_name"`
}
// GlobalAPISyncGrafanaDataSourcesRequest: Trigger the synchronization of all data sources created in the relevant regions.
type GlobalAPISyncGrafanaDataSourcesRequest struct {
// ProjectID: ID of the Project to target.
ProjectID string `json:"project_id"`
}
// Grafana: Grafana user.
type Grafana struct {
// GrafanaURL: URL to access your Cockpit's Grafana.
GrafanaURL string `json:"grafana_url"`
}
// ListContactPointsResponse: Response returned when listing contact points.
type ListContactPointsResponse struct {
// TotalCount: total count of contact points associated with the default receiver.
TotalCount uint64 `json:"total_count"`
// ContactPoints: list of contact points associated with the default receiver.
ContactPoints []*ContactPoint `json:"contact_points"`
// HasAdditionalReceivers: indicates whether the Alert manager has other receivers than the default one.
HasAdditionalReceivers bool `json:"has_additional_receivers"`
// HasAdditionalContactPoints: indicates whether there are unmanaged contact points on the default receiver.
HasAdditionalContactPoints bool `json:"has_additional_contact_points"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListContactPointsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListContactPointsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListContactPointsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ContactPoints = append(r.ContactPoints, results.ContactPoints...)
r.TotalCount += uint64(len(results.ContactPoints))
return uint64(len(results.ContactPoints)), nil
}
// ListDataSourcesResponse: Response returned when listing data sources.
type ListDataSourcesResponse struct {
// TotalCount: total count of data sources matching the request.
TotalCount uint64 `json:"total_count"`
// DataSources: data sources matching the request within the pagination.
DataSources []*DataSource `json:"data_sources"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDataSourcesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDataSourcesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDataSourcesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.DataSources = append(r.DataSources, results.DataSources...)
r.TotalCount += uint64(len(results.DataSources))
return uint64(len(results.DataSources)), nil
}
// ListGrafanaProductDashboardsResponse: Output returned when listing dashboards.
type ListGrafanaProductDashboardsResponse struct {
// TotalCount: total count of Grafana dashboards.
TotalCount uint64 `json:"total_count"`
// Dashboards: grafana dashboards information.
Dashboards []*GrafanaProductDashboard `json:"dashboards"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGrafanaProductDashboardsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGrafanaProductDashboardsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListGrafanaProductDashboardsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Dashboards = append(r.Dashboards, results.Dashboards...)
r.TotalCount += uint64(len(results.Dashboards))
return uint64(len(results.Dashboards)), nil
}
// ListGrafanaUsersResponse: Ouptut returned when listing Grafana users.
type ListGrafanaUsersResponse struct {
// TotalCount: total count of Grafana users.
TotalCount uint64 `json:"total_count"`
// GrafanaUsers: grafana users information.
GrafanaUsers []*GrafanaUser `json:"grafana_users"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGrafanaUsersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGrafanaUsersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListGrafanaUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.GrafanaUsers = append(r.GrafanaUsers, results.GrafanaUsers...)
r.TotalCount += uint64(len(results.GrafanaUsers))
return uint64(len(results.GrafanaUsers)), nil
}
// ListManagedAlertsResponse: Response returned when listing data sources.
type ListManagedAlertsResponse struct {
// TotalCount: total count of data sources matching the request.
TotalCount uint64 `json:"total_count"`
// Alerts: alerts matching the request within the pagination.
Alerts []*Alert `json:"alerts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListManagedAlertsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListManagedAlertsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListManagedAlertsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Alerts = append(r.Alerts, results.Alerts...)
r.TotalCount += uint64(len(results.Alerts))
return uint64(len(results.Alerts)), nil
}
// ListPlansResponse: Output returned when listing pricing plans.
type ListPlansResponse struct {
// TotalCount: total count of available pricing plans.
TotalCount uint64 `json:"total_count"`
// Plans: plan types information.
Plans []*Plan `json:"plans"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPlansResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPlansResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPlansResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Plans = append(r.Plans, results.Plans...)
r.TotalCount += uint64(len(results.Plans))
return uint64(len(results.Plans)), nil
}
// ListTokensResponse: Response returned when listing tokens.
type ListTokensResponse struct {
// TotalCount: total count of tokens matching the request.
TotalCount uint64 `json:"total_count"`
// Tokens: tokens matching the request within the pagination.
Tokens []*Token `json:"tokens"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListTokensResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tokens = append(r.Tokens, results.Tokens...)
r.TotalCount += uint64(len(results.Tokens))
return uint64(len(results.Tokens)), nil
}
// RegionalAPICreateContactPointRequest: Create a contact point.
type RegionalAPICreateContactPointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to create the contact point in.
ProjectID string `json:"project_id"`
// Email: email address of the contact point to create.
// Precisely one of Email must be set.
Email *ContactPointEmail `json:"email,omitempty"`
}
// RegionalAPICreateDataSourceRequest: Create a data source.
type RegionalAPICreateDataSourceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project the data source belongs to.
ProjectID string `json:"project_id"`
// Name: data source name.
Name string `json:"name"`
// Type: data source type.
// Default value: unknown_type
Type DataSourceType `json:"type"`
// RetentionDays: default values are 30 days for metrics, 7 days for logs and traces.
RetentionDays *uint32 `json:"retention_days,omitempty"`
}
// RegionalAPICreateTokenRequest: Create a token.
type RegionalAPICreateTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project the token belongs to.
ProjectID string `json:"project_id"`
// Name: name of the token.
Name string `json:"name"`
// TokenScopes: token permission scopes.
TokenScopes []TokenScope `json:"token_scopes"`
}
// RegionalAPIDeleteContactPointRequest: Delete a contact point.
type RegionalAPIDeleteContactPointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project containing the contact point to delete.
ProjectID string `json:"project_id"`
// Email: email address of the contact point to delete.
// Precisely one of Email must be set.
Email *ContactPointEmail `json:"email,omitempty"`
}
// RegionalAPIDeleteDataSourceRequest: Delete a data source.
type RegionalAPIDeleteDataSourceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DataSourceID: ID of the data source to delete.
DataSourceID string `json:"-"`
}
// RegionalAPIDeleteTokenRequest: Delete a token.
type RegionalAPIDeleteTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: ID of the token to delete.
TokenID string `json:"-"`
}
// RegionalAPIDisableAlertManagerRequest: Disable the Alert manager.
type RegionalAPIDisableAlertManagerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to disable the Alert manager in.
ProjectID string `json:"project_id"`
}
// RegionalAPIDisableManagedAlertsRequest: Disable the sending of managed alerts.
type RegionalAPIDisableManagedAlertsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project.
ProjectID string `json:"project_id"`
}
// RegionalAPIEnableAlertManagerRequest: Enable the Alert manager.
type RegionalAPIEnableAlertManagerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to enable the Alert manager in.
ProjectID string `json:"project_id"`
}
// RegionalAPIEnableManagedAlertsRequest: Enable the sending of managed alerts.
type RegionalAPIEnableManagedAlertsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project.
ProjectID string `json:"project_id"`
}
// RegionalAPIGetAlertManagerRequest: Get the Alert manager.
type RegionalAPIGetAlertManagerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project ID of the requested Alert manager.
ProjectID string `json:"project_id"`
}
// RegionalAPIGetConfigRequest: Get Cockpit configuration.
type RegionalAPIGetConfigRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// RegionalAPIGetDataSourceRequest: Retrieve a data source.
type RegionalAPIGetDataSourceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DataSourceID: ID of the relevant data source.
DataSourceID string `json:"-"`
}
// RegionalAPIGetTokenRequest: Get a token.
type RegionalAPIGetTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: token ID.
TokenID string `json:"-"`
}
// RegionalAPIGetUsageOverviewRequest: regional api get usage overview request.
type RegionalAPIGetUsageOverviewRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
ProjectID string `json:"-"`
Interval *scw.Duration `json:"-"`
}
// RegionalAPIListContactPointsRequest: List contact points.
type RegionalAPIListContactPointsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: total count of contact points to return per page.
PageSize *uint32 `json:"-"`
// ProjectID: ID of the Project containing the contact points to list.
ProjectID string `json:"-"`
}
// RegionalAPIListDataSourcesRequest: List data sources.
type RegionalAPIListDataSourcesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of data sources to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order for data sources in the response.
// Default value: created_at_asc
OrderBy ListDataSourcesRequestOrderBy `json:"-"`
// ProjectID: project ID to filter for, only data sources from this Project will be returned.
ProjectID string `json:"-"`
// Origin: origin to filter for, only data sources with matching origin will be returned.
// Default value: unknown_origin
Origin DataSourceOrigin `json:"-"`
// Types: types to filter for, only data sources with matching types will be returned.
Types []DataSourceType `json:"-"`
}
// RegionalAPIListManagedAlertsRequest: Enable the sending of managed alerts.
type RegionalAPIListManagedAlertsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of data sources to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order for data sources in the response.
// Default value: created_at_asc
OrderBy ListManagedAlertsRequestOrderBy `json:"-"`
// ProjectID: project ID to filter for, only data sources from this Project will be returned.
ProjectID string `json:"-"`
}
// RegionalAPIListTokensRequest: List tokens.
type RegionalAPIListTokensRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of tokens to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListTokensRequestOrderBy `json:"-"`
// ProjectID: ID of the Project the tokens belong to.
ProjectID string `json:"-"`
// TokenScopes: token scopes to filter for.
TokenScopes []TokenScope `json:"-"`
}
// RegionalAPITriggerTestAlertRequest: Request to trigger a test alert.
type RegionalAPITriggerTestAlertRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project.
ProjectID string `json:"project_id"`
}
// RegionalAPIUpdateDataSourceRequest: Update a data source name.
type RegionalAPIUpdateDataSourceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DataSourceID: ID of the data source to update.
DataSourceID string `json:"-"`
// Name: updated name of the data source.
Name *string `json:"name,omitempty"`
// RetentionDays: bETA - Duration for which the data will be retained in the data source.
RetentionDays *uint32 `json:"retention_days,omitempty"`
}
// UsageOverview: usage overview.
type UsageOverview struct {
ScalewayMetricsUsage *Usage `json:"scaleway_metrics_usage"`
ScalewayLogsUsage *Usage `json:"scaleway_logs_usage"`
ExternalMetricsUsage *Usage `json:"external_metrics_usage"`
ExternalLogsUsage *Usage `json:"external_logs_usage"`
ExternalTracesUsage *Usage `json:"external_traces_usage"`
}
// The Cockpit Global API allows you to manage your Cockpit's Grafana and plans.
type GlobalAPI struct {
client *scw.Client
}
// NewGlobalAPI returns a GlobalAPI object from a Scaleway client.
func NewGlobalAPI(client *scw.Client) *GlobalAPI {
return &GlobalAPI{
client: client,
}
}
// GetGrafana: Retrieve information on your Cockpit's Grafana, specified by the ID of the Project the Cockpit belongs to.
// The output returned displays the URL to access your Cockpit's Grafana.
func (s *GlobalAPI) GetGrafana(req *GlobalAPIGetGrafanaRequest, opts ...scw.RequestOption) (*Grafana, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/grafana",
Query: query,
}
var resp Grafana
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SyncGrafanaDataSources: Trigger the synchronization of all your data sources and the alert manager in the relevant regions. The alert manager will only be synchronized if you have enabled it.
func (s *GlobalAPI) SyncGrafanaDataSources(req *GlobalAPISyncGrafanaDataSourcesRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/grafana/sync-data-sources",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateGrafanaUser: Create a Grafana user to connect to your Cockpit's Grafana. Upon creation, your user password displays only once, so make sure that you save it.
// Each Grafana user is associated with a role: viewer or editor. A viewer can only view dashboards, whereas an editor can create and edit dashboards. Note that the `admin` username is not available for creation.
func (s *GlobalAPI) CreateGrafanaUser(req *GlobalAPICreateGrafanaUserRequest, opts ...scw.RequestOption) (*GrafanaUser, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/grafana/users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GrafanaUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListGrafanaUsers: List all Grafana users created in your Cockpit's Grafana. By default, the Grafana users returned in the list are ordered in ascending order.
func (s *GlobalAPI) ListGrafanaUsers(req *GlobalAPIListGrafanaUsersRequest, opts ...scw.RequestOption) (*ListGrafanaUsersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/grafana/users",
Query: query,
}
var resp ListGrafanaUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGrafanaUser: Delete a Grafana user from your Cockpit's Grafana, specified by the ID of the Project the Cockpit belongs to, and the ID of the Grafana user.
func (s *GlobalAPI) DeleteGrafanaUser(req *GlobalAPIDeleteGrafanaUserRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.GrafanaUserID) == "" {
return errors.New("field GrafanaUserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/cockpit/v1/grafana/users/" + fmt.Sprint(req.GrafanaUserID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ResetGrafanaUserPassword: Reset the password of a Grafana user, specified by the ID of the Project the Cockpit belongs to, and the ID of the Grafana user.
// A new password regenerates and only displays once. Make sure that you save it.
func (s *GlobalAPI) ResetGrafanaUserPassword(req *GlobalAPIResetGrafanaUserPasswordRequest, opts ...scw.RequestOption) (*GrafanaUser, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.GrafanaUserID) == "" {
return nil, errors.New("field GrafanaUserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/grafana/users/" + fmt.Sprint(req.GrafanaUserID) + "/reset-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GrafanaUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListGrafanaProductDashboards: Retrieve a list of available dashboards in Grafana, for all Scaleway resources which are integrated with Cockpit.
func (s *GlobalAPI) ListGrafanaProductDashboards(req *GlobalAPIListGrafanaProductDashboardsRequest, opts ...scw.RequestOption) (*ListGrafanaProductDashboardsResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "tags", req.Tags)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/grafana/product-dashboards",
Query: query,
}
var resp ListGrafanaProductDashboardsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGrafanaProductDashboard: Retrieve information about the dashboard of a Scaleway resource in Grafana, specified by the ID of the Project the Cockpit belongs to, and the name of the dashboard.
func (s *GlobalAPI) GetGrafanaProductDashboard(req *GlobalAPIGetGrafanaProductDashboardRequest, opts ...scw.RequestOption) (*GrafanaProductDashboard, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.DashboardName) == "" {
return nil, errors.New("field DashboardName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/grafana/product-dashboards/" + fmt.Sprint(req.DashboardName) + "",
Query: query,
}
var resp GrafanaProductDashboard
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: ListPlans: Retrieve a list of available pricing plan types.
// Deprecated, retention is now managed at the data source level.
func (s *GlobalAPI) ListPlans(req *GlobalAPIListPlansRequest, opts ...scw.RequestOption) (*ListPlansResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/plans",
Query: query,
}
var resp ListPlansResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: SelectPlan: Apply a pricing plan on a given Project. You must specify the ID of the pricing plan type. Note that you will be billed for the plan you apply.
// Deprecated, retention is now managed at the data source level.
func (s *GlobalAPI) SelectPlan(req *GlobalAPISelectPlanRequest, opts ...scw.RequestOption) (*Plan, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/cockpit/v1/plans",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Plan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: GetCurrentPlan: Retrieve a pricing plan for the given Project, specified by the ID of the Project.
// Deprecated, retention is now managed at the data source level.
func (s *GlobalAPI) GetCurrentPlan(req *GlobalAPIGetCurrentPlanRequest, opts ...scw.RequestOption) (*Plan, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/current-plan",
Query: query,
}
var resp Plan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// The Cockpit Regional API allows you to create data sources and tokens to store and query data types such as metrics, logs, and traces. You can also push your data into Cockpit, and send alerts to your contact points when your resources may require your attention, using the regional Alert manager.
type RegionalAPI struct {
client *scw.Client
}
// NewRegionalAPI returns a RegionalAPI object from a Scaleway client.
func NewRegionalAPI(client *scw.Client) *RegionalAPI {
return &RegionalAPI{
client: client,
}
}
func (s *RegionalAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// GetConfig: Get the Cockpit configuration.
func (s *RegionalAPI) GetConfig(req *RegionalAPIGetConfigRequest, opts ...scw.RequestOption) (*GetConfigResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/config",
}
var resp GetConfigResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDataSource: You must specify the data source type upon creation. Available data source types include:
// - metrics
// - logs
// - traces
//
// The name of the data source will then be used as reference to name the associated Grafana data source.
func (s *RegionalAPI) CreateDataSource(req *RegionalAPICreateDataSourceRequest, opts ...scw.RequestOption) (*DataSource, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/data-sources",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DataSource
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDataSource: Retrieve information about a given data source, specified by the data source ID. The data source's information such as its name, type, URL, origin, and retention period, is returned.
func (s *RegionalAPI) GetDataSource(req *RegionalAPIGetDataSourceRequest, opts ...scw.RequestOption) (*DataSource, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DataSourceID) == "" {
return nil, errors.New("field DataSourceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/data-sources/" + fmt.Sprint(req.DataSourceID) + "",
}
var resp DataSource
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDataSource: Delete a given data source, specified by the data source ID. Note that deleting a data source is irreversible, and cannot be undone.
func (s *RegionalAPI) DeleteDataSource(req *RegionalAPIDeleteDataSourceRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DataSourceID) == "" {
return errors.New("field DataSourceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/data-sources/" + fmt.Sprint(req.DataSourceID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDataSources: Retrieve the list of data sources available in the specified region. By default, the data sources returned in the list are ordered by creation date, in ascending order.
// You can list data sources by Project, type and origin.
func (s *RegionalAPI) ListDataSources(req *RegionalAPIListDataSourcesRequest, opts ...scw.RequestOption) (*ListDataSourcesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "origin", req.Origin)
parameter.AddToQuery(query, "types", req.Types)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/data-sources",
Query: query,
}
var resp ListDataSourcesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDataSource: Update a given data source name, specified by the data source ID.
func (s *RegionalAPI) UpdateDataSource(req *RegionalAPIUpdateDataSourceRequest, opts ...scw.RequestOption) (*DataSource, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DataSourceID) == "" {
return nil, errors.New("field DataSourceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/data-sources/" + fmt.Sprint(req.DataSourceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DataSource
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetUsageOverview: Retrieve the data source usage overview per type for the specified Project.
func (s *RegionalAPI) GetUsageOverview(req *RegionalAPIGetUsageOverviewRequest, opts ...scw.RequestOption) (*UsageOverview, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "interval", req.Interval)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/usage-overview",
Query: query,
}
var resp UsageOverview
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateToken: Give your token the relevant scopes to ensure it has the right permissions to interact with your data sources and the Alert manager. Make sure that you create your token in the same regions as the data sources you want to use it for.
// Upon creation, your token's secret key display only once. Make sure that you save it.
func (s *RegionalAPI) CreateToken(req *RegionalAPICreateTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/tokens",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTokens: Retrieve a list of all tokens in the specified region. By default, tokens returned in the list are ordered by creation date, in ascending order.
// You can filter tokens by Project ID and token scopes.
func (s *RegionalAPI) ListTokens(req *RegionalAPIListTokensRequest, opts ...scw.RequestOption) (*ListTokensResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "token_scopes", req.TokenScopes)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/tokens",
Query: query,
}
var resp ListTokensResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetToken: Retrieve information about a given token, specified by the token ID. The token's information such as its scopes, is returned.
func (s *RegionalAPI) GetToken(req *RegionalAPIGetTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return nil, errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteToken: Delete a given token, specified by the token ID. Deleting a token is irreversible and cannot be undone.
func (s *RegionalAPI) DeleteToken(req *RegionalAPIDeleteTokenRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetAlertManager: Retrieve information about the Alert manager which is unique per Project and region. By default the Alert manager is disabled.
// The output returned displays a URL to access the Alert manager, and whether the Alert manager and managed alerts are enabled.
func (s *RegionalAPI) GetAlertManager(req *RegionalAPIGetAlertManagerRequest, opts ...scw.RequestOption) (*AlertManager, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager",
Query: query,
}
var resp AlertManager
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableAlertManager: Enabling the Alert manager allows you to enable managed alerts and create contact points in the specified Project and region, to be notified when your Scaleway resources may require your attention.
func (s *RegionalAPI) EnableAlertManager(req *RegionalAPIEnableAlertManagerRequest, opts ...scw.RequestOption) (*AlertManager, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AlertManager
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableAlertManager: Disabling the Alert manager deletes the contact points you have created and disables managed alerts in the specified Project and region.
func (s *RegionalAPI) DisableAlertManager(req *RegionalAPIDisableAlertManagerRequest, opts ...scw.RequestOption) (*AlertManager, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AlertManager
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateContactPoint: Contact points are email addresses associated with the default receiver, that the Alert manager sends alerts to.
// The source of the alerts are data sources within the same Project and region as the Alert manager.
// If you need to receive alerts for other receivers, you can create additional contact points and receivers in Grafana. Make sure that you select the Scaleway Alert manager.
func (s *RegionalAPI) CreateContactPoint(req *RegionalAPICreateContactPointRequest, opts ...scw.RequestOption) (*ContactPoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/contact-points",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ContactPoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListContactPoints: Retrieve a list of contact points for the specified Project. The response lists all contact points and receivers created in Grafana or via the API.
func (s *RegionalAPI) ListContactPoints(req *RegionalAPIListContactPointsRequest, opts ...scw.RequestOption) (*ListContactPointsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/contact-points",
Query: query,
}
var resp ListContactPointsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteContactPoint: Delete a contact point associated with the default receiver.
func (s *RegionalAPI) DeleteContactPoint(req *RegionalAPIDeleteContactPointRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/contact-points/delete",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListManagedAlerts: List all managed alerts for the specified Project.
func (s *RegionalAPI) ListManagedAlerts(req *RegionalAPIListManagedAlertsRequest, opts ...scw.RequestOption) (*ListManagedAlertsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/managed-alerts",
Query: query,
}
var resp ListManagedAlertsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableManagedAlerts: Enable the sending of managed alerts for the specified Project. Managed alerts are predefined alerts that apply to Scaleway recources integrated with Cockpit by default.
func (s *RegionalAPI) EnableManagedAlerts(req *RegionalAPIEnableManagedAlertsRequest, opts ...scw.RequestOption) (*AlertManager, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/managed-alerts/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AlertManager
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableManagedAlerts: Disable the sending of managed alerts for the specified Project.
func (s *RegionalAPI) DisableManagedAlerts(req *RegionalAPIDisableManagedAlertsRequest, opts ...scw.RequestOption) (*AlertManager, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/managed-alerts/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AlertManager
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// TriggerTestAlert: Send a test alert to the Alert manager to make sure your contact points get notified.
func (s *RegionalAPI) TriggerTestAlert(req *RegionalAPITriggerTestAlertRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/cockpit/v1/regions/" + fmt.Sprint(req.Region) + "/alert-manager/trigger-test-alert",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/cockpit/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026634 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/cockpit/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000006705 14747113137 0031030 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"strings"
accountSDK "github.com/scaleway/scaleway-sdk-go/api/account/v3"
"github.com/scaleway/scaleway-sdk-go/api/cockpit/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepToken(scwClient *scw.Client) error {
accountAPI := accountSDK.NewProjectAPI(scwClient)
cockpitAPI := cockpit.NewRegionalAPI(scwClient)
listProjects, err := accountAPI.ListProjects(&accountSDK.ProjectAPIListProjectsRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
if !strings.HasPrefix(project.Name, "tf_tests") {
continue
}
listTokens, err := cockpitAPI.ListTokens(&cockpit.RegionalAPIListTokensRequest{
ProjectID: project.ID,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list tokens: %w", err)
}
for _, token := range listTokens.Tokens {
err = cockpitAPI.DeleteToken(&cockpit.RegionalAPIDeleteTokenRequest{
TokenID: token.ID,
})
if err != nil {
return fmt.Errorf("failed to delete token: %w", err)
}
}
}
return nil
}
func SweepGrafanaUser(scwClient *scw.Client) error {
accountAPI := accountSDK.NewProjectAPI(scwClient)
cockpitAPI := cockpit.NewGlobalAPI(scwClient)
listProjects, err := accountAPI.ListProjects(&accountSDK.ProjectAPIListProjectsRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
if !strings.HasPrefix(project.Name, "tf_tests") {
continue
}
listGrafanaUsers, err := cockpitAPI.ListGrafanaUsers(&cockpit.GlobalAPIListGrafanaUsersRequest{
ProjectID: project.ID,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list grafana users: %w", err)
}
for _, grafanaUser := range listGrafanaUsers.GrafanaUsers {
err = cockpitAPI.DeleteGrafanaUser(&cockpit.GlobalAPIDeleteGrafanaUserRequest{
ProjectID: project.ID,
GrafanaUserID: grafanaUser.ID,
})
if err != nil {
return fmt.Errorf("failed to delete grafana user: %w", err)
}
}
}
return nil
}
func SweepSource(scwClient *scw.Client, region scw.Region) error {
accountAPI := accountSDK.NewProjectAPI(scwClient)
cockpitAPI := cockpit.NewRegionalAPI(scwClient)
listProjects, err := accountAPI.ListProjects(&accountSDK.ProjectAPIListProjectsRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
if !strings.HasPrefix(project.Name, "tf_tests") {
continue
}
listDatasources, err := cockpitAPI.ListDataSources(&cockpit.RegionalAPIListDataSourcesRequest{
ProjectID: project.ID,
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list sources: %w", err)
}
for _, datsource := range listDatasources.DataSources {
err = cockpitAPI.DeleteDataSource(&cockpit.RegionalAPIDeleteDataSourceRequest{
DataSourceID: datsource.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("failed to delete cockpit source: %w", err)
}
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
if err := SweepToken(scwClient); err != nil {
return err
}
if err := SweepGrafanaUser(scwClient); err != nil {
return err
}
for _, region := range (&cockpit.RegionalAPI{}).Regions() {
if err := SweepSource(scwClient, region); err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/ 0000775 0000000 0000000 00000000000 14747113137 0024777 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0026242 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/container_helpers.go 0000664 0000000 0000000 00000015645 14747113137 0032310 0 ustar 00root root 0000000 0000000 package container
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
waitForNamespaceDefaultTimeout = 15 * time.Minute
waitForCronDefaultTimeout = 15 * time.Minute
waitForContainerDefaultTimeout = 15 * time.Minute
waitForDomainDefaultTimeout = 15 * time.Minute
waitForTriggerDefaultTimeout = 15 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForNamespaceRequest is used by WaitForNamespace method.
type WaitForNamespaceRequest struct {
NamespaceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForNamespace waits for the Namespace to be in a ready state before returning.
func (s *API) WaitForNamespace(req *WaitForNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
timeout := waitForNamespaceDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[NamespaceStatus]struct{}{
NamespaceStatusError: {},
NamespaceStatusReady: {},
NamespaceStatusLocked: {},
}
namespace, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
namespace, err := s.GetNamespace(&GetNamespaceRequest{
NamespaceID: req.NamespaceID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[namespace.Status]
return namespace, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Namespace failed")
}
return namespace.(*Namespace), nil
}
// WaitForContainerRequest is used by WaitForNamespace method.
type WaitForContainerRequest struct {
ContainerID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForContainer waits for the Container to be in a ready state before returning.
func (s *API) WaitForContainer(req *WaitForContainerRequest, opts ...scw.RequestOption) (*Container, error) {
timeout := waitForContainerDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ContainerStatus]struct{}{
ContainerStatusError: {},
ContainerStatusCreated: {},
ContainerStatusReady: {},
ContainerStatusLocked: {},
}
container, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
container, err := s.GetContainer(&GetContainerRequest{
ContainerID: req.ContainerID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[container.Status]
return container, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for container failed")
}
return container.(*Container), nil
}
// WaitForCronRequest is used by WaitForNamespace method.
type WaitForCronRequest struct {
CronID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForCron waits for the Cron to be in a ready state before returning.
func (s *API) WaitForCron(req *WaitForCronRequest, opts ...scw.RequestOption) (*Cron, error) {
timeout := waitForCronDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[CronStatus]struct{}{
CronStatusError: {},
CronStatusReady: {},
CronStatusLocked: {},
}
cron, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
cron, err := s.GetCron(&GetCronRequest{
CronID: req.CronID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[cron.Status]
return cron, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Cron failed")
}
return cron.(*Cron), nil
}
// WaitForDomainRequest waits for the Domain to be in a ready state before returning.
type WaitForDomainRequest struct {
DomainID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDomain waits for the Domain to be in a ready state before returning.
func (s *API) WaitForDomain(req *WaitForDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
timeout := waitForDomainDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DomainStatus]struct{}{
DomainStatusError: {},
DomainStatusReady: {},
}
domain, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
domain, err := s.GetDomain(&GetDomainRequest{
DomainID: req.DomainID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[domain.Status]
return domain, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Domain failed")
}
return domain.(*Domain), nil
}
// WaitForTriggerRequest waits for the Trigger to be in a ready state before returning.
type WaitForTriggerRequest struct {
TriggerID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForTrigger waits for the Trigger to be in a ready state before returning.
func (s *API) WaitForTrigger(req *WaitForTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
timeout := waitForTriggerDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[TriggerStatus]struct{}{
TriggerStatusError: {},
TriggerStatusReady: {},
}
trigger, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
trigger, err := s.GetTrigger(&GetTriggerRequest{
TriggerID: req.TriggerID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[trigger.Status]
return trigger, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Trigger failed")
}
return trigger.(*Trigger), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/container_sdk.go 0000664 0000000 0000000 00000237066 14747113137 0031432 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package container provides methods and message types of the container v1beta1 API.
package container
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ContainerHTTPOption string
const (
ContainerHTTPOptionUnknownHTTPOption = ContainerHTTPOption("unknown_http_option")
ContainerHTTPOptionEnabled = ContainerHTTPOption("enabled")
ContainerHTTPOptionRedirected = ContainerHTTPOption("redirected")
)
func (enum ContainerHTTPOption) String() string {
if enum == "" {
// return default value if empty
return "unknown_http_option"
}
return string(enum)
}
func (enum ContainerHTTPOption) Values() []ContainerHTTPOption {
return []ContainerHTTPOption{
"unknown_http_option",
"enabled",
"redirected",
}
}
func (enum ContainerHTTPOption) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContainerHTTPOption) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContainerHTTPOption(ContainerHTTPOption(tmp).String())
return nil
}
type ContainerPrivacy string
const (
ContainerPrivacyUnknownPrivacy = ContainerPrivacy("unknown_privacy")
ContainerPrivacyPublic = ContainerPrivacy("public")
ContainerPrivacyPrivate = ContainerPrivacy("private")
)
func (enum ContainerPrivacy) String() string {
if enum == "" {
// return default value if empty
return "unknown_privacy"
}
return string(enum)
}
func (enum ContainerPrivacy) Values() []ContainerPrivacy {
return []ContainerPrivacy{
"unknown_privacy",
"public",
"private",
}
}
func (enum ContainerPrivacy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContainerPrivacy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContainerPrivacy(ContainerPrivacy(tmp).String())
return nil
}
type ContainerProtocol string
const (
ContainerProtocolUnknownProtocol = ContainerProtocol("unknown_protocol")
ContainerProtocolHTTP1 = ContainerProtocol("http1")
ContainerProtocolH2c = ContainerProtocol("h2c")
)
func (enum ContainerProtocol) String() string {
if enum == "" {
// return default value if empty
return "unknown_protocol"
}
return string(enum)
}
func (enum ContainerProtocol) Values() []ContainerProtocol {
return []ContainerProtocol{
"unknown_protocol",
"http1",
"h2c",
}
}
func (enum ContainerProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContainerProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContainerProtocol(ContainerProtocol(tmp).String())
return nil
}
type ContainerSandbox string
const (
// Unknown sandbox.
ContainerSandboxUnknownSandbox = ContainerSandbox("unknown_sandbox")
// Legacy sandboxing with slower cold starts. Fully supports the Linux system call interface.
ContainerSandboxV1 = ContainerSandbox("v1")
// Recommended sandboxing with faster cold starts.
ContainerSandboxV2 = ContainerSandbox("v2")
)
func (enum ContainerSandbox) String() string {
if enum == "" {
// return default value if empty
return "unknown_sandbox"
}
return string(enum)
}
func (enum ContainerSandbox) Values() []ContainerSandbox {
return []ContainerSandbox{
"unknown_sandbox",
"v1",
"v2",
}
}
func (enum ContainerSandbox) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContainerSandbox) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContainerSandbox(ContainerSandbox(tmp).String())
return nil
}
type ContainerStatus string
const (
ContainerStatusUnknown = ContainerStatus("unknown")
ContainerStatusReady = ContainerStatus("ready")
ContainerStatusDeleting = ContainerStatus("deleting")
ContainerStatusError = ContainerStatus("error")
ContainerStatusLocked = ContainerStatus("locked")
ContainerStatusCreating = ContainerStatus("creating")
ContainerStatusPending = ContainerStatus("pending")
ContainerStatusCreated = ContainerStatus("created")
)
func (enum ContainerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ContainerStatus) Values() []ContainerStatus {
return []ContainerStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
"created",
}
}
func (enum ContainerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContainerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContainerStatus(ContainerStatus(tmp).String())
return nil
}
type CronStatus string
const (
CronStatusUnknown = CronStatus("unknown")
CronStatusReady = CronStatus("ready")
CronStatusDeleting = CronStatus("deleting")
CronStatusError = CronStatus("error")
CronStatusLocked = CronStatus("locked")
CronStatusCreating = CronStatus("creating")
CronStatusPending = CronStatus("pending")
)
func (enum CronStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum CronStatus) Values() []CronStatus {
return []CronStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
}
}
func (enum CronStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *CronStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = CronStatus(CronStatus(tmp).String())
return nil
}
type DomainStatus string
const (
DomainStatusUnknown = DomainStatus("unknown")
DomainStatusReady = DomainStatus("ready")
DomainStatusDeleting = DomainStatus("deleting")
DomainStatusError = DomainStatus("error")
DomainStatusCreating = DomainStatus("creating")
DomainStatusPending = DomainStatus("pending")
)
func (enum DomainStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DomainStatus) Values() []DomainStatus {
return []DomainStatus{
"unknown",
"ready",
"deleting",
"error",
"creating",
"pending",
}
}
func (enum DomainStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainStatus(DomainStatus(tmp).String())
return nil
}
type ListContainersRequestOrderBy string
const (
ListContainersRequestOrderByCreatedAtAsc = ListContainersRequestOrderBy("created_at_asc")
ListContainersRequestOrderByCreatedAtDesc = ListContainersRequestOrderBy("created_at_desc")
ListContainersRequestOrderByNameAsc = ListContainersRequestOrderBy("name_asc")
ListContainersRequestOrderByNameDesc = ListContainersRequestOrderBy("name_desc")
)
func (enum ListContainersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListContainersRequestOrderBy) Values() []ListContainersRequestOrderBy {
return []ListContainersRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListContainersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListContainersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListContainersRequestOrderBy(ListContainersRequestOrderBy(tmp).String())
return nil
}
type ListCronsRequestOrderBy string
const (
ListCronsRequestOrderByCreatedAtAsc = ListCronsRequestOrderBy("created_at_asc")
ListCronsRequestOrderByCreatedAtDesc = ListCronsRequestOrderBy("created_at_desc")
)
func (enum ListCronsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListCronsRequestOrderBy) Values() []ListCronsRequestOrderBy {
return []ListCronsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListCronsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListCronsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListCronsRequestOrderBy(ListCronsRequestOrderBy(tmp).String())
return nil
}
type ListDomainsRequestOrderBy string
const (
ListDomainsRequestOrderByCreatedAtAsc = ListDomainsRequestOrderBy("created_at_asc")
ListDomainsRequestOrderByCreatedAtDesc = ListDomainsRequestOrderBy("created_at_desc")
ListDomainsRequestOrderByHostnameAsc = ListDomainsRequestOrderBy("hostname_asc")
ListDomainsRequestOrderByHostnameDesc = ListDomainsRequestOrderBy("hostname_desc")
)
func (enum ListDomainsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDomainsRequestOrderBy) Values() []ListDomainsRequestOrderBy {
return []ListDomainsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"hostname_asc",
"hostname_desc",
}
}
func (enum ListDomainsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDomainsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDomainsRequestOrderBy(ListDomainsRequestOrderBy(tmp).String())
return nil
}
type ListNamespacesRequestOrderBy string
const (
ListNamespacesRequestOrderByCreatedAtAsc = ListNamespacesRequestOrderBy("created_at_asc")
ListNamespacesRequestOrderByCreatedAtDesc = ListNamespacesRequestOrderBy("created_at_desc")
ListNamespacesRequestOrderByNameAsc = ListNamespacesRequestOrderBy("name_asc")
ListNamespacesRequestOrderByNameDesc = ListNamespacesRequestOrderBy("name_desc")
)
func (enum ListNamespacesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNamespacesRequestOrderBy) Values() []ListNamespacesRequestOrderBy {
return []ListNamespacesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListNamespacesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNamespacesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNamespacesRequestOrderBy(ListNamespacesRequestOrderBy(tmp).String())
return nil
}
type ListTokensRequestOrderBy string
const (
ListTokensRequestOrderByCreatedAtAsc = ListTokensRequestOrderBy("created_at_asc")
ListTokensRequestOrderByCreatedAtDesc = ListTokensRequestOrderBy("created_at_desc")
)
func (enum ListTokensRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTokensRequestOrderBy) Values() []ListTokensRequestOrderBy {
return []ListTokensRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListTokensRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTokensRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTokensRequestOrderBy(ListTokensRequestOrderBy(tmp).String())
return nil
}
type ListTriggersRequestOrderBy string
const (
// Order by creation date ascending.
ListTriggersRequestOrderByCreatedAtAsc = ListTriggersRequestOrderBy("created_at_asc")
// Order by creation date descending.
ListTriggersRequestOrderByCreatedAtDesc = ListTriggersRequestOrderBy("created_at_desc")
)
func (enum ListTriggersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTriggersRequestOrderBy) Values() []ListTriggersRequestOrderBy {
return []ListTriggersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListTriggersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTriggersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTriggersRequestOrderBy(ListTriggersRequestOrderBy(tmp).String())
return nil
}
type NamespaceStatus string
const (
NamespaceStatusUnknown = NamespaceStatus("unknown")
NamespaceStatusReady = NamespaceStatus("ready")
NamespaceStatusDeleting = NamespaceStatus("deleting")
NamespaceStatusError = NamespaceStatus("error")
NamespaceStatusLocked = NamespaceStatus("locked")
NamespaceStatusCreating = NamespaceStatus("creating")
NamespaceStatusPending = NamespaceStatus("pending")
)
func (enum NamespaceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NamespaceStatus) Values() []NamespaceStatus {
return []NamespaceStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
}
}
func (enum NamespaceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NamespaceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NamespaceStatus(NamespaceStatus(tmp).String())
return nil
}
type TokenStatus string
const (
TokenStatusUnknown = TokenStatus("unknown")
TokenStatusReady = TokenStatus("ready")
TokenStatusDeleting = TokenStatus("deleting")
TokenStatusError = TokenStatus("error")
TokenStatusCreating = TokenStatus("creating")
)
func (enum TokenStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum TokenStatus) Values() []TokenStatus {
return []TokenStatus{
"unknown",
"ready",
"deleting",
"error",
"creating",
}
}
func (enum TokenStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TokenStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TokenStatus(TokenStatus(tmp).String())
return nil
}
type TriggerInputType string
const (
// Unknown input type.
TriggerInputTypeUnknownInputType = TriggerInputType("unknown_input_type")
TriggerInputTypeSqs = TriggerInputType("sqs")
// Scaleway Messaging and Queuing SQS queue.
TriggerInputTypeScwSqs = TriggerInputType("scw_sqs")
TriggerInputTypeNats = TriggerInputType("nats")
// Scaleway Messaging and Queuing NATS subject.
TriggerInputTypeScwNats = TriggerInputType("scw_nats")
)
func (enum TriggerInputType) String() string {
if enum == "" {
// return default value if empty
return "unknown_input_type"
}
return string(enum)
}
func (enum TriggerInputType) Values() []TriggerInputType {
return []TriggerInputType{
"unknown_input_type",
"sqs",
"scw_sqs",
"nats",
"scw_nats",
}
}
func (enum TriggerInputType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TriggerInputType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TriggerInputType(TriggerInputType(tmp).String())
return nil
}
type TriggerStatus string
const (
// Unknown status.
TriggerStatusUnknownStatus = TriggerStatus("unknown_status")
// Ready status.
TriggerStatusReady = TriggerStatus("ready")
// Deleting status.
TriggerStatusDeleting = TriggerStatus("deleting")
// Error status.
TriggerStatusError = TriggerStatus("error")
// Creating status.
TriggerStatusCreating = TriggerStatus("creating")
// Pending status.
TriggerStatusPending = TriggerStatus("pending")
)
func (enum TriggerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum TriggerStatus) Values() []TriggerStatus {
return []TriggerStatus{
"unknown_status",
"ready",
"deleting",
"error",
"creating",
"pending",
}
}
func (enum TriggerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TriggerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TriggerStatus(TriggerStatus(tmp).String())
return nil
}
// ContainerHealthCheckSpecHTTPProbe: container health check spec http probe.
type ContainerHealthCheckSpecHTTPProbe struct {
// Path: path to use for the HTTP health check.
Path string `json:"path"`
}
// ContainerHealthCheckSpecTCPProbe: container health check spec tcp probe.
type ContainerHealthCheckSpecTCPProbe struct {
}
// ContainerHealthCheckSpec: container health check spec.
type ContainerHealthCheckSpec struct {
// HTTP: HTTP health check configuration.
// Precisely one of HTTP, TCP must be set.
HTTP *ContainerHealthCheckSpecHTTPProbe `json:"http,omitempty"`
// TCP: TCP health check configuration.
// Precisely one of HTTP, TCP must be set.
TCP *ContainerHealthCheckSpecTCPProbe `json:"tcp,omitempty"`
// FailureThreshold: during a deployment, if a newly created container fails to pass the health check, the deployment is aborted.
// As a result, lowering this value can help to reduce the time it takes to detect a failed deployment.
FailureThreshold uint32 `json:"failure_threshold"`
// Interval: period between health checks.
Interval *scw.Duration `json:"interval"`
}
// ContainerScalingOption: container scaling option.
type ContainerScalingOption struct {
// Precisely one of ConcurrentRequestsThreshold, CPUUsageThreshold, MemoryUsageThreshold must be set.
ConcurrentRequestsThreshold *uint32 `json:"concurrent_requests_threshold,omitempty"`
// Precisely one of ConcurrentRequestsThreshold, CPUUsageThreshold, MemoryUsageThreshold must be set.
CPUUsageThreshold *uint32 `json:"cpu_usage_threshold,omitempty"`
// Precisely one of ConcurrentRequestsThreshold, CPUUsageThreshold, MemoryUsageThreshold must be set.
MemoryUsageThreshold *uint32 `json:"memory_usage_threshold,omitempty"`
}
// SecretHashedValue: secret hashed value.
type SecretHashedValue struct {
Key string `json:"key"`
HashedValue string `json:"hashed_value"`
}
// TriggerMnqNatsClientConfig: trigger mnq nats client config.
type TriggerMnqNatsClientConfig struct {
// Subject: name of the NATS subject the trigger listens to.
Subject string `json:"subject"`
// MnqNatsAccountID: ID of the Messaging and Queuing NATS account.
MnqNatsAccountID string `json:"mnq_nats_account_id"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
// MnqCredentialID: ID of the Messaging and Queuing credentials used to subscribe to the NATS subject.
MnqCredentialID *string `json:"mnq_credential_id"`
}
// TriggerMnqSqsClientConfig: trigger mnq sqs client config.
type TriggerMnqSqsClientConfig struct {
// Queue: name of the SQS queue the trigger listens to.
Queue string `json:"queue"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
// MnqCredentialID: ID of the Messaging and Queuing credentials used to read from the SQS queue.
MnqCredentialID *string `json:"mnq_credential_id"`
}
// TriggerSqsClientConfig: trigger sqs client config.
type TriggerSqsClientConfig struct {
Endpoint string `json:"endpoint"`
QueueURL string `json:"queue_url"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
}
// Secret: secret.
type Secret struct {
Key string `json:"key"`
Value *string `json:"value"`
}
// CreateTriggerRequestMnqNatsClientConfig: create trigger request mnq nats client config.
type CreateTriggerRequestMnqNatsClientConfig struct {
// Subject: name of the NATS subject the trigger should listen to.
Subject string `json:"subject"`
// MnqNatsAccountID: ID of the Messaging and Queuing NATS account.
MnqNatsAccountID string `json:"mnq_nats_account_id"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
}
// CreateTriggerRequestMnqSqsClientConfig: create trigger request mnq sqs client config.
type CreateTriggerRequestMnqSqsClientConfig struct {
// Queue: name of the SQS queue the trigger should listen to.
Queue string `json:"queue"`
// MnqProjectID: you must have activated SQS on this project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
}
// CreateTriggerRequestSqsClientConfig: create trigger request sqs client config.
type CreateTriggerRequestSqsClientConfig struct {
Endpoint string `json:"endpoint"`
QueueURL string `json:"queue_url"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
}
// Container: container.
type Container struct {
// ID: UUID of the container.
ID string `json:"id"`
// Name: name of the container.
Name string `json:"name"`
// NamespaceID: UUID of the namespace the container belongs to.
NamespaceID string `json:"namespace_id"`
// Status: status of the container.
// Default value: unknown
Status ContainerStatus `json:"status"`
// EnvironmentVariables: environment variables of the container.
EnvironmentVariables map[string]string `json:"environment_variables"`
// MinScale: minimum number of instances to scale the container to.
MinScale uint32 `json:"min_scale"`
// MaxScale: maximum number of instances to scale the container to.
MaxScale uint32 `json:"max_scale"`
// MemoryLimit: memory limit of the container in MB.
MemoryLimit uint32 `json:"memory_limit"`
// CPULimit: CPU limit of the container in mvCPU.
CPULimit uint32 `json:"cpu_limit"`
// Timeout: processing time limit for the container.
Timeout *scw.Duration `json:"timeout"`
// ErrorMessage: last error message of the container.
ErrorMessage *string `json:"error_message"`
// Privacy: privacy setting of the container.
// Default value: unknown_privacy
Privacy ContainerPrivacy `json:"privacy"`
// Description: description of the container.
Description *string `json:"description"`
// RegistryImage: name of the registry image (e.g. "rg.fr-par.scw.cloud/something/image:tag").
RegistryImage string `json:"registry_image"`
// MaxConcurrency: number of maximum concurrent executions of the container.
MaxConcurrency uint32 `json:"max_concurrency"`
// DomainName: domain name attributed to the contaioner.
DomainName string `json:"domain_name"`
// Protocol: protocol the container uses.
// Default value: unknown_protocol
Protocol ContainerProtocol `json:"protocol"`
// Port: port the container listens on.
Port uint32 `json:"port"`
// SecretEnvironmentVariables: secret environment variables of the container.
SecretEnvironmentVariables []*SecretHashedValue `json:"secret_environment_variables"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption ContainerHTTPOption `json:"http_option"`
// Sandbox: execution environment of the container.
// Default value: unknown_sandbox
Sandbox ContainerSandbox `json:"sandbox"`
// LocalStorageLimit: local storage limit of the container (in MB).
LocalStorageLimit uint32 `json:"local_storage_limit"`
// ScalingOption: possible values:
// - concurrent_requests_threshold: Scale depending on the number of concurrent requests being processed per container instance.
// - cpu_usage_threshold: Scale depending on the CPU usage of a container instance.
// - memory_usage_threshold: Scale depending on the memory usage of a container instance.
ScalingOption *ContainerScalingOption `json:"scaling_option"`
// HealthCheck: health check configuration of the container.
HealthCheck *ContainerHealthCheckSpec `json:"health_check"`
// CreatedAt: creation date of the container.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of the container.
UpdatedAt *time.Time `json:"updated_at"`
// ReadyAt: last date when the container was successfully deployed and set to ready.
ReadyAt *time.Time `json:"ready_at"`
// Region: region in which the container will be deployed.
Region scw.Region `json:"region"`
}
// Cron: cron.
type Cron struct {
// ID: UUID of the cron.
ID string `json:"id"`
// ContainerID: UUID of the container invoked by this cron.
ContainerID string `json:"container_id"`
// Schedule: uNIX cron shedule.
Schedule string `json:"schedule"`
// Args: arguments to pass with the cron.
Args *scw.JSONObject `json:"args"`
// Status: status of the cron.
// Default value: unknown
Status CronStatus `json:"status"`
// Name: name of the cron.
Name string `json:"name"`
}
// Domain: domain.
type Domain struct {
// ID: UUID of the domain.
ID string `json:"id"`
// Hostname: domain assigned to the container.
Hostname string `json:"hostname"`
// ContainerID: UUID of the container.
ContainerID string `json:"container_id"`
// URL: URL (TBD).
URL string `json:"url"`
// Status: status of the domain.
// Default value: unknown
Status DomainStatus `json:"status"`
// ErrorMessage: last error message of the domain.
ErrorMessage *string `json:"error_message"`
}
// Namespace: namespace.
type Namespace struct {
// ID: UUID of the namespace.
ID string `json:"id"`
// Name: name of the namespace.
Name string `json:"name"`
// EnvironmentVariables: environment variables of the namespace.
EnvironmentVariables map[string]string `json:"environment_variables"`
// OrganizationID: UUID of the Organization the namespace belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: UUID of the Project the namespace belongs to.
ProjectID string `json:"project_id"`
// Status: status of the namespace.
// Default value: unknown
Status NamespaceStatus `json:"status"`
// RegistryNamespaceID: UUID of the registry namespace.
RegistryNamespaceID string `json:"registry_namespace_id"`
// ErrorMessage: last error message of the namesace.
ErrorMessage *string `json:"error_message"`
// RegistryEndpoint: registry endpoint of the namespace.
RegistryEndpoint string `json:"registry_endpoint"`
// Description: description of the endpoint.
Description *string `json:"description"`
// SecretEnvironmentVariables: secret environment variables of the namespace.
SecretEnvironmentVariables []*SecretHashedValue `json:"secret_environment_variables"`
// Region: region in which the namespace will be created.
Region scw.Region `json:"region"`
// Tags: [ALPHA] List of tags applied to the Serverless Container Namespace.
Tags []string `json:"tags"`
// CreatedAt: creation date of the namespace.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of the namespace.
UpdatedAt *time.Time `json:"updated_at"`
}
// Token: token.
type Token struct {
// ID: UUID of the token.
ID string `json:"id"`
// Token: identifier of the token.
Token string `json:"token"`
// ContainerID: UUID of the container the token belongs to.
// Precisely one of ContainerID, NamespaceID must be set.
ContainerID *string `json:"container_id,omitempty"`
// NamespaceID: UUID of the namespace the token belongs to.
// Precisely one of ContainerID, NamespaceID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// Deprecated: PublicKey: public key of the token.
PublicKey *string `json:"public_key,omitempty"`
// Status: status of the token.
// Default value: unknown
Status TokenStatus `json:"status"`
// Description: description of the token.
Description *string `json:"description"`
// ExpiresAt: expiry date of the token.
ExpiresAt *time.Time `json:"expires_at"`
}
// Trigger: trigger.
type Trigger struct {
// ID: ID of the trigger.
ID string `json:"id"`
// Name: name of the trigger.
Name string `json:"name"`
// Description: description of the trigger.
Description string `json:"description"`
// ContainerID: ID of the container to trigger.
ContainerID string `json:"container_id"`
// InputType: type of the input.
// Default value: unknown_input_type
InputType TriggerInputType `json:"input_type"`
// Status: status of the trigger.
// Default value: unknown_status
Status TriggerStatus `json:"status"`
// ErrorMessage: error message of the trigger.
ErrorMessage *string `json:"error_message"`
// ScwSqsConfig: configuration for a Scaleway Messaging and Queuing SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwSqsConfig *TriggerMnqSqsClientConfig `json:"scw_sqs_config,omitempty"`
// ScwNatsConfig: configuration for a Scaleway Messaging and Queuing NATS subject.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwNatsConfig *TriggerMnqNatsClientConfig `json:"scw_nats_config,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
SqsConfig *TriggerSqsClientConfig `json:"sqs_config,omitempty"`
}
// UpdateTriggerRequestSqsClientConfig: update trigger request sqs client config.
type UpdateTriggerRequestSqsClientConfig struct {
AccessKey *string `json:"access_key"`
SecretKey *string `json:"secret_key"`
}
// CreateContainerRequest: create container request.
type CreateContainerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace the container belongs to.
NamespaceID string `json:"namespace_id"`
// Name: name of the container.
Name string `json:"name"`
// EnvironmentVariables: environment variables of the container.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// MinScale: minimum number of instances to scale the container to.
MinScale *uint32 `json:"min_scale,omitempty"`
// MaxScale: maximum number of instances to scale the container to.
MaxScale *uint32 `json:"max_scale,omitempty"`
// MemoryLimit: memory limit of the container in MB.
MemoryLimit *uint32 `json:"memory_limit,omitempty"`
// CPULimit: CPU limit of the container in mvCPU.
CPULimit *uint32 `json:"cpu_limit,omitempty"`
// Timeout: processing time limit for the container.
Timeout *scw.Duration `json:"timeout,omitempty"`
// Privacy: privacy setting of the container.
// Default value: unknown_privacy
Privacy ContainerPrivacy `json:"privacy"`
// Description: description of the container.
Description *string `json:"description,omitempty"`
// RegistryImage: name of the registry image (e.g. "rg.fr-par.scw.cloud/something/image:tag").
RegistryImage *string `json:"registry_image,omitempty"`
// Deprecated: MaxConcurrency: number of maximum concurrent executions of the container.
MaxConcurrency *uint32 `json:"max_concurrency,omitempty"`
// Protocol: protocol the container uses.
// Default value: unknown_protocol
Protocol ContainerProtocol `json:"protocol"`
// Port: port the container listens on.
Port *uint32 `json:"port,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the container.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption ContainerHTTPOption `json:"http_option"`
// Sandbox: execution environment of the container.
// Default value: unknown_sandbox
Sandbox ContainerSandbox `json:"sandbox"`
// LocalStorageLimit: local storage limit of the container (in MB).
LocalStorageLimit *uint32 `json:"local_storage_limit,omitempty"`
// ScalingOption: possible values:
// - concurrent_requests_threshold: Scale depending on the number of concurrent requests being processed per container instance.
// - cpu_usage_threshold: Scale depending on the CPU usage of a container instance.
// - memory_usage_threshold: Scale depending on the memory usage of a container instance.
ScalingOption *ContainerScalingOption `json:"scaling_option,omitempty"`
// HealthCheck: health check configuration of the container.
HealthCheck *ContainerHealthCheckSpec `json:"health_check,omitempty"`
}
// CreateCronRequest: create cron request.
type CreateCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to invoke by the cron.
ContainerID string `json:"container_id"`
// Schedule: uNIX cron shedule.
Schedule string `json:"schedule"`
// Args: arguments to pass with the cron.
Args *scw.JSONObject `json:"args,omitempty"`
// Name: name of the cron to create.
Name *string `json:"name,omitempty"`
}
// CreateDomainRequest: create domain request.
type CreateDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Hostname: domain to assign.
Hostname string `json:"hostname"`
// ContainerID: UUID of the container to assign the domain to.
ContainerID string `json:"container_id"`
}
// CreateNamespaceRequest: create namespace request.
type CreateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the namespace to create.
Name string `json:"name"`
// EnvironmentVariables: environment variables of the namespace to create.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// ProjectID: UUID of the Project in which the namespace will be created.
ProjectID string `json:"project_id"`
// Description: description of the namespace to create.
Description *string `json:"description,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the namespace to create.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// Tags: [ALPHA] Tags of the Serverless Container Namespace.
Tags []string `json:"tags"`
}
// CreateTokenRequest: create token request.
type CreateTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to create the token for.
// Precisely one of ContainerID, NamespaceID must be set.
ContainerID *string `json:"container_id,omitempty"`
// NamespaceID: UUID of the namespace to create the token for.
// Precisely one of ContainerID, NamespaceID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// Description: description of the token.
Description *string `json:"description,omitempty"`
// ExpiresAt: expiry date of the token.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateTriggerRequest: create trigger request.
type CreateTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the trigger.
Name string `json:"name"`
// ContainerID: ID of the container to trigger.
ContainerID string `json:"container_id"`
// Description: description of the trigger.
Description *string `json:"description,omitempty"`
// ScwSqsConfig: configuration for a Scaleway Messaging and Queuing SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwSqsConfig *CreateTriggerRequestMnqSqsClientConfig `json:"scw_sqs_config,omitempty"`
// ScwNatsConfig: configuration for a Scaleway Messaging and Queuing NATS subject.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwNatsConfig *CreateTriggerRequestMnqNatsClientConfig `json:"scw_nats_config,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
SqsConfig *CreateTriggerRequestSqsClientConfig `json:"sqs_config,omitempty"`
}
// DeleteContainerRequest: delete container request.
type DeleteContainerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to delete.
ContainerID string `json:"-"`
}
// DeleteCronRequest: delete cron request.
type DeleteCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to delete.
CronID string `json:"-"`
}
// DeleteDomainRequest: delete domain request.
type DeleteDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: UUID of the domain to delete.
DomainID string `json:"-"`
}
// DeleteNamespaceRequest: delete namespace request.
type DeleteNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace to delete.
NamespaceID string `json:"-"`
}
// DeleteTokenRequest: delete token request.
type DeleteTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: UUID of the token to delete.
TokenID string `json:"-"`
}
// DeleteTriggerRequest: delete trigger request.
type DeleteTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to delete.
TriggerID string `json:"-"`
}
// DeployContainerRequest: deploy container request.
type DeployContainerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to deploy.
ContainerID string `json:"-"`
}
// GetContainerRequest: get container request.
type GetContainerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to get.
ContainerID string `json:"-"`
}
// GetCronRequest: get cron request.
type GetCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to get.
CronID string `json:"-"`
}
// GetDomainRequest: get domain request.
type GetDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: UUID of the domain to get.
DomainID string `json:"-"`
}
// GetNamespaceRequest: get namespace request.
type GetNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace to get.
NamespaceID string `json:"-"`
}
// GetTokenRequest: get token request.
type GetTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: UUID of the token to get.
TokenID string `json:"-"`
}
// GetTriggerRequest: get trigger request.
type GetTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to get.
TriggerID string `json:"-"`
}
// ListContainersRequest: list containers request.
type ListContainersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of containers per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the containers.
// Default value: created_at_asc
OrderBy ListContainersRequestOrderBy `json:"-"`
// NamespaceID: UUID of the namespace the container belongs to.
NamespaceID string `json:"-"`
// Name: name of the container.
Name *string `json:"-"`
// OrganizationID: UUID of the Organization the container belongs to.
OrganizationID *string `json:"-"`
// ProjectID: UUID of the Project the container belongs to.
ProjectID *string `json:"-"`
}
// ListContainersResponse: list containers response.
type ListContainersResponse struct {
// Containers: array of containers.
Containers []*Container `json:"containers"`
// TotalCount: total number of containers.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListContainersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListContainersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListContainersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Containers = append(r.Containers, results.Containers...)
r.TotalCount += uint32(len(results.Containers))
return uint32(len(results.Containers)), nil
}
// ListCronsRequest: list crons request.
type ListCronsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of crons per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the crons.
// Default value: created_at_asc
OrderBy ListCronsRequestOrderBy `json:"-"`
// ContainerID: UUID of the container invoked by the cron.
ContainerID string `json:"-"`
}
// ListCronsResponse: list crons response.
type ListCronsResponse struct {
// Crons: array of crons.
Crons []*Cron `json:"crons"`
// TotalCount: total number of crons.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListCronsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListCronsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListCronsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Crons = append(r.Crons, results.Crons...)
r.TotalCount += uint32(len(results.Crons))
return uint32(len(results.Crons)), nil
}
// ListDomainsRequest: list domains request.
type ListDomainsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of domains per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the domains.
// Default value: created_at_asc
OrderBy ListDomainsRequestOrderBy `json:"-"`
// ContainerID: UUID of the container the domain belongs to.
ContainerID string `json:"-"`
}
// ListDomainsResponse: list domains response.
type ListDomainsResponse struct {
// Domains: array of domains.
Domains []*Domain `json:"domains"`
// TotalCount: total number of domains.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDomainsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Domains = append(r.Domains, results.Domains...)
r.TotalCount += uint32(len(results.Domains))
return uint32(len(results.Domains)), nil
}
// ListNamespacesRequest: list namespaces request.
type ListNamespacesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of namespaces per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the namespaces.
// Default value: created_at_asc
OrderBy ListNamespacesRequestOrderBy `json:"-"`
// Name: name of the namespaces.
Name *string `json:"-"`
// OrganizationID: UUID of the Organization the namespace belongs to.
OrganizationID *string `json:"-"`
// ProjectID: UUID of the Project the namespace belongs to.
ProjectID *string `json:"-"`
}
// ListNamespacesResponse: list namespaces response.
type ListNamespacesResponse struct {
// Namespaces: array of the namespaces.
Namespaces []*Namespace `json:"namespaces"`
// TotalCount: total number of namespaces.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNamespacesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Namespaces = append(r.Namespaces, results.Namespaces...)
r.TotalCount += uint32(len(results.Namespaces))
return uint32(len(results.Namespaces)), nil
}
// ListTokensRequest: list tokens request.
type ListTokensRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of tokens per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the tokens.
// Default value: created_at_asc
OrderBy ListTokensRequestOrderBy `json:"-"`
// ContainerID: UUID of the container the token belongs to.
ContainerID *string `json:"-"`
// NamespaceID: UUID of the namespace the token belongs to.
NamespaceID *string `json:"-"`
}
// ListTokensResponse: list tokens response.
type ListTokensResponse struct {
Tokens []*Token `json:"tokens"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTokensResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tokens = append(r.Tokens, results.Tokens...)
r.TotalCount += uint32(len(results.Tokens))
return uint32(len(results.Tokens)), nil
}
// ListTriggersRequest: list triggers request.
type ListTriggersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of triggers to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListTriggersRequestOrderBy `json:"-"`
// ContainerID: ID of the container the triggers belongs to.
// Precisely one of ContainerID, NamespaceID, ProjectID must be set.
ContainerID *string `json:"container_id,omitempty"`
// NamespaceID: ID of the namespace the triggers belongs to.
// Precisely one of ContainerID, NamespaceID, ProjectID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// ProjectID: ID of the project the triggers belongs to.
// Precisely one of ContainerID, NamespaceID, ProjectID must be set.
ProjectID *string `json:"project_id,omitempty"`
}
// ListTriggersResponse: list triggers response.
type ListTriggersResponse struct {
// TotalCount: total count of existing triggers (matching any filters specified).
TotalCount uint32 `json:"total_count"`
// Triggers: triggers on this page.
Triggers []*Trigger `json:"triggers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTriggersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTriggersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTriggersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Triggers = append(r.Triggers, results.Triggers...)
r.TotalCount += uint32(len(results.Triggers))
return uint32(len(results.Triggers)), nil
}
// UpdateContainerRequest: update container request.
type UpdateContainerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ContainerID: UUID of the container to update.
ContainerID string `json:"-"`
// EnvironmentVariables: environment variables of the container.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// MinScale: minimum number of instances to scale the container to.
MinScale *uint32 `json:"min_scale,omitempty"`
// MaxScale: maximum number of instances to scale the container to.
MaxScale *uint32 `json:"max_scale,omitempty"`
// MemoryLimit: memory limit of the container in MB.
MemoryLimit *uint32 `json:"memory_limit,omitempty"`
// CPULimit: CPU limit of the container in mvCPU.
CPULimit *uint32 `json:"cpu_limit,omitempty"`
// Timeout: processing time limit for the container.
Timeout *scw.Duration `json:"timeout,omitempty"`
// Redeploy: defines whether to redeploy failed containers.
Redeploy *bool `json:"redeploy,omitempty"`
// Privacy: privacy settings of the container.
// Default value: unknown_privacy
Privacy ContainerPrivacy `json:"privacy"`
// Description: description of the container.
Description *string `json:"description,omitempty"`
// RegistryImage: name of the registry image (e.g. "rg.fr-par.scw.cloud/something/image:tag").
RegistryImage *string `json:"registry_image,omitempty"`
// Deprecated: MaxConcurrency: number of maximum concurrent executions of the container.
MaxConcurrency *uint32 `json:"max_concurrency,omitempty"`
// Protocol: default value: unknown_protocol
Protocol ContainerProtocol `json:"protocol"`
Port *uint32 `json:"port,omitempty"`
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption ContainerHTTPOption `json:"http_option"`
// Sandbox: execution environment of the container.
// Default value: unknown_sandbox
Sandbox ContainerSandbox `json:"sandbox"`
// LocalStorageLimit: local storage limit of the container (in MB).
LocalStorageLimit *uint32 `json:"local_storage_limit,omitempty"`
// ScalingOption: possible values:
// - concurrent_requests_threshold: Scale depending on the number of concurrent requests being processed per container instance.
// - cpu_usage_threshold: Scale depending on the CPU usage of a container instance.
// - memory_usage_threshold: Scale depending on the memory usage of a container instance.
ScalingOption *ContainerScalingOption `json:"scaling_option,omitempty"`
// HealthCheck: health check configuration of the container.
HealthCheck *ContainerHealthCheckSpec `json:"health_check,omitempty"`
}
// UpdateCronRequest: update cron request.
type UpdateCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to update.
CronID string `json:"-"`
// ContainerID: UUID of the container invoked by the cron.
ContainerID *string `json:"container_id,omitempty"`
// Schedule: uNIX cron schedule.
Schedule *string `json:"schedule,omitempty"`
// Args: arguments to pass with the cron.
Args *scw.JSONObject `json:"args,omitempty"`
// Name: name of the cron.
Name *string `json:"name,omitempty"`
}
// UpdateNamespaceRequest: update namespace request.
type UpdateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace to update.
NamespaceID string `json:"-"`
// EnvironmentVariables: environment variables of the namespace to update.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// Description: description of the namespace to update.
Description *string `json:"description,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the namespace to update.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// Tags: [ALPHA] Tags of the Serverless Container Namespace.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateTriggerRequest: update trigger request.
type UpdateTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to update.
TriggerID string `json:"-"`
// Name: name of the trigger.
Name *string `json:"name,omitempty"`
// Description: description of the trigger.
Description *string `json:"description,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of SqsConfig must be set.
SqsConfig *UpdateTriggerRequestSqsClientConfig `json:"sqs_config,omitempty"`
}
// This API allows you to manage your Serverless Containers.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListNamespaces: List all namespaces in a specified region.
func (s *API) ListNamespaces(req *ListNamespacesRequest, opts ...scw.RequestOption) (*ListNamespacesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
Query: query,
}
var resp ListNamespacesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNamespace: Get the namespace associated with the specified ID.
func (s *API) GetNamespace(req *GetNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateNamespace: Create a new namespace in a specified region.
func (s *API) CreateNamespace(req *CreateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("cns")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateNamespace: Update the space associated with the specified ID.
func (s *API) UpdateNamespace(req *UpdateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNamespace: Delete the namespace associated with the specified ID.
func (s *API) DeleteNamespace(req *DeleteNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListContainers: List all containers for a specified region.
func (s *API) ListContainers(req *ListContainersRequest, opts ...scw.RequestOption) (*ListContainersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers",
Query: query,
}
var resp ListContainersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetContainer: Get the container associated with the specified ID.
func (s *API) GetContainer(req *GetContainerRequest, opts ...scw.RequestOption) (*Container, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ContainerID) == "" {
return nil, errors.New("field ContainerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers/" + fmt.Sprint(req.ContainerID) + "",
}
var resp Container
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateContainer: Create a new container in the specified region.
func (s *API) CreateContainer(req *CreateContainerRequest, opts ...scw.RequestOption) (*Container, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Container
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateContainer: Update the container associated with the specified ID.
func (s *API) UpdateContainer(req *UpdateContainerRequest, opts ...scw.RequestOption) (*Container, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ContainerID) == "" {
return nil, errors.New("field ContainerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers/" + fmt.Sprint(req.ContainerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Container
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteContainer: Delete the container associated with the specified ID.
func (s *API) DeleteContainer(req *DeleteContainerRequest, opts ...scw.RequestOption) (*Container, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ContainerID) == "" {
return nil, errors.New("field ContainerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers/" + fmt.Sprint(req.ContainerID) + "",
}
var resp Container
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeployContainer: Deploy a container associated with the specified ID.
func (s *API) DeployContainer(req *DeployContainerRequest, opts ...scw.RequestOption) (*Container, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ContainerID) == "" {
return nil, errors.New("field ContainerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/containers/" + fmt.Sprint(req.ContainerID) + "/deploy",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Container
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListCrons: List all your crons.
func (s *API) ListCrons(req *ListCronsRequest, opts ...scw.RequestOption) (*ListCronsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "container_id", req.ContainerID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons",
Query: query,
}
var resp ListCronsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCron: Get the cron associated with the specified ID.
func (s *API) GetCron(req *GetCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateCron: Create a new cron.
func (s *API) CreateCron(req *CreateCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCron: Update the cron associated with the specified ID.
func (s *API) UpdateCron(req *UpdateCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCron: Delete the cron associated with the specified ID.
func (s *API) DeleteCron(req *DeleteCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDomains: List all custom domains in a specified region.
func (s *API) ListDomains(req *ListDomainsRequest, opts ...scw.RequestOption) (*ListDomainsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "container_id", req.ContainerID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains",
Query: query,
}
var resp ListDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomain: Get a custom domain for the container with the specified ID.
func (s *API) GetDomain(req *GetDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDomain: Create a custom domain for the container with the specified ID.
func (s *API) CreateDomain(req *CreateDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDomain: Delete the custom domain with the specific ID.
func (s *API) DeleteDomain(req *DeleteDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateToken: Create a new revocable token.
func (s *API) CreateToken(req *CreateTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetToken: Get a token with a specified ID.
func (s *API) GetToken(req *GetTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return nil, errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTokens: List all tokens belonging to a specified Organization or Project.
func (s *API) ListTokens(req *ListTokensRequest, opts ...scw.RequestOption) (*ListTokensResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "container_id", req.ContainerID)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens",
Query: query,
}
var resp ListTokensResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteToken: Delete a token with a specified ID.
func (s *API) DeleteToken(req *DeleteTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return nil, errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateTrigger: Create a new trigger for a specified container.
func (s *API) CreateTrigger(req *CreateTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetTrigger: Get a trigger with a specified ID.
func (s *API) GetTrigger(req *GetTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTriggers: List all triggers belonging to a specified Organization or Project.
func (s *API) ListTriggers(req *ListTriggersRequest, opts ...scw.RequestOption) (*ListTriggersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ContainerID == nil && req.NamespaceID == nil && req.ProjectID == nil {
req.ProjectID = &defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "container_id", req.ContainerID)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers",
Query: query,
}
var resp ListTriggersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateTrigger: Update a trigger with a specified ID.
func (s *API) UpdateTrigger(req *UpdateTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTrigger: Delete a trigger with a specified ID.
func (s *API) DeleteTrigger(req *DeleteTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/containers/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/container_sdk_test.go 0000664 0000000 0000000 00000001357 14747113137 0032461 0 ustar 00root root 0000000 0000000 package container
import (
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestListContainerNamespaceMultipleRegions(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("container-list-regions")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
containerAPI := NewAPI(client)
// Create server
_, err = containerAPI.ListNamespaces(&ListNamespacesRequest{}, scw.WithRegions(containerAPI.Regions()...))
testhelpers.Assert(t, err == nil, "This request should not error: %s", err)
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0030077 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/sweepers/sweepers.go 0000664 0000000 0000000 00000005207 14747113137 0032267 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
container "github.com/scaleway/scaleway-sdk-go/api/container/v1beta1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepTrigger(scwClient *scw.Client, region scw.Region) error {
containerAPI := container.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the container triggers in (%s)", region)
listTriggers, err := containerAPI.ListTriggers(
&container.ListTriggersRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing trigger in (%s) in sweeper: %s", region, err)
}
for _, trigger := range listTriggers.Triggers {
_, err := containerAPI.DeleteTrigger(&container.DeleteTriggerRequest{
TriggerID: trigger.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting trigger in sweeper: %s", err)
}
}
return nil
}
func SweepContainer(scwClient *scw.Client, region scw.Region) error {
containerAPI := container.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the container in (%s)", region)
listNamespaces, err := containerAPI.ListContainers(
&container.ListContainersRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing containers in (%s) in sweeper: %s", region, err)
}
for _, cont := range listNamespaces.Containers {
_, err := containerAPI.DeleteContainer(&container.DeleteContainerRequest{
ContainerID: cont.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting container in sweeper: %s", err)
}
}
return nil
}
func SweepNamespace(scwClient *scw.Client, region scw.Region) error {
containerAPI := container.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the container namespaces in (%s)", region)
listNamespaces, err := containerAPI.ListNamespaces(
&container.ListNamespacesRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing namespaces in (%s) in sweeper: %s", region, err)
}
for _, ns := range listNamespaces.Namespaces {
_, err := containerAPI.DeleteNamespace(&container.DeleteNamespaceRequest{
NamespaceID: ns.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting namespace in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&container.API{}).Regions() {
err := SweepTrigger(scwClient, region)
if err != nil {
return err
}
err = SweepContainer(scwClient, region)
if err != nil {
return err
}
err = SweepNamespace(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/testdata/ 0000775 0000000 0000000 00000000000 14747113137 0030053 5 ustar 00root root 0000000 0000000 container-list-regions.yaml 0000664 0000000 0000000 00000005706 14747113137 0035267 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/container/v1beta1/testdata ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/containers/v1beta1/regions/fr-par/namespaces?order_by=created_at_asc
method: GET
response:
body: '{"namespaces":[], "total_count":0}'
headers:
Content-Length:
- "34"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 03 Mar 2023 11:09:20 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 64534ead-60ca-4176-a37c-89f2781ec10e
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/containers/v1beta1/regions/nl-ams/namespaces?order_by=created_at_asc
method: GET
response:
body: '{"namespaces":[{"id":"5113d87a-3a49-4e8d-be27-e1a20b9a59c1", "name":"dfdsffsfsqf",
"environment_variables":{}, "organization_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "status":"ready", "registry_namespace_id":"d0afb8a1-6417-4e7e-8a1c-29e348f96f05",
"error_message":null, "registry_endpoint":"rg.nl-ams.scw.cloud/funcscwdfdsffsfsqfkvsfbdbr",
"description":"", "secret_environment_variables":[], "region":"nl-ams"}], "total_count":1}'
headers:
Content-Length:
- "486"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 03 Mar 2023 11:09:20 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- ef764335-0239-4aa5-92ca-a91a9a22db3a
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/containers/v1beta1/regions/pl-waw/namespaces?order_by=created_at_asc
method: GET
response:
body: '{"namespaces":[], "total_count":0}'
headers:
Content-Length:
- "34"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 03 Mar 2023 11:09:20 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 33115f4e-1a87-41cb-8ba4-0ec491271287
status: 200 OK
code: 200
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/dedibox/ 0000775 0000000 0000000 00000000000 14747113137 0024433 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/dedibox/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024761 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/dedibox/v1/dedibox_sdk.go 0000664 0000000 0000000 00000705371 14747113137 0027604 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package dedibox provides methods and message types of the dedibox v1 API.
package dedibox
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type AttachFailoverIPToMacAddressRequestMacType string
const (
AttachFailoverIPToMacAddressRequestMacTypeMacTypeUnknown = AttachFailoverIPToMacAddressRequestMacType("mac_type_unknown")
AttachFailoverIPToMacAddressRequestMacTypeVmware = AttachFailoverIPToMacAddressRequestMacType("vmware")
AttachFailoverIPToMacAddressRequestMacTypeKvm = AttachFailoverIPToMacAddressRequestMacType("kvm")
AttachFailoverIPToMacAddressRequestMacTypeXen = AttachFailoverIPToMacAddressRequestMacType("xen")
)
func (enum AttachFailoverIPToMacAddressRequestMacType) String() string {
if enum == "" {
// return default value if empty
return "mac_type_unknown"
}
return string(enum)
}
func (enum AttachFailoverIPToMacAddressRequestMacType) Values() []AttachFailoverIPToMacAddressRequestMacType {
return []AttachFailoverIPToMacAddressRequestMacType{
"mac_type_unknown",
"vmware",
"kvm",
"xen",
}
}
func (enum AttachFailoverIPToMacAddressRequestMacType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *AttachFailoverIPToMacAddressRequestMacType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = AttachFailoverIPToMacAddressRequestMacType(AttachFailoverIPToMacAddressRequestMacType(tmp).String())
return nil
}
type BMCAccessStatus string
const (
BMCAccessStatusUnknown = BMCAccessStatus("unknown")
BMCAccessStatusCreating = BMCAccessStatus("creating")
BMCAccessStatusCreated = BMCAccessStatus("created")
BMCAccessStatusDeleting = BMCAccessStatus("deleting")
)
func (enum BMCAccessStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum BMCAccessStatus) Values() []BMCAccessStatus {
return []BMCAccessStatus{
"unknown",
"creating",
"created",
"deleting",
}
}
func (enum BMCAccessStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BMCAccessStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BMCAccessStatus(BMCAccessStatus(tmp).String())
return nil
}
type BackupStatus string
const (
BackupStatusUnknownBackupStatus = BackupStatus("unknown_backup_status")
BackupStatusUninitialized = BackupStatus("uninitialized")
BackupStatusInactive = BackupStatus("inactive")
BackupStatusReady = BackupStatus("ready")
)
func (enum BackupStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_backup_status"
}
return string(enum)
}
func (enum BackupStatus) Values() []BackupStatus {
return []BackupStatus{
"unknown_backup_status",
"uninitialized",
"inactive",
"ready",
}
}
func (enum BackupStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BackupStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BackupStatus(BackupStatus(tmp).String())
return nil
}
type FailoverBlockVersion string
const (
FailoverBlockVersionUnknownVersion = FailoverBlockVersion("unknown_version")
FailoverBlockVersionIPv4 = FailoverBlockVersion("ipv4")
FailoverBlockVersionIPv6 = FailoverBlockVersion("ipv6")
)
func (enum FailoverBlockVersion) String() string {
if enum == "" {
// return default value if empty
return "unknown_version"
}
return string(enum)
}
func (enum FailoverBlockVersion) Values() []FailoverBlockVersion {
return []FailoverBlockVersion{
"unknown_version",
"ipv4",
"ipv6",
}
}
func (enum FailoverBlockVersion) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FailoverBlockVersion) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FailoverBlockVersion(FailoverBlockVersion(tmp).String())
return nil
}
type FailoverIPInterfaceType string
const (
FailoverIPInterfaceTypeUnknown = FailoverIPInterfaceType("unknown")
FailoverIPInterfaceTypeNormal = FailoverIPInterfaceType("normal")
FailoverIPInterfaceTypeIpmi = FailoverIPInterfaceType("ipmi")
FailoverIPInterfaceTypeVirtual = FailoverIPInterfaceType("virtual")
)
func (enum FailoverIPInterfaceType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum FailoverIPInterfaceType) Values() []FailoverIPInterfaceType {
return []FailoverIPInterfaceType{
"unknown",
"normal",
"ipmi",
"virtual",
}
}
func (enum FailoverIPInterfaceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FailoverIPInterfaceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FailoverIPInterfaceType(FailoverIPInterfaceType(tmp).String())
return nil
}
type FailoverIPStatus string
const (
FailoverIPStatusUnknownStatus = FailoverIPStatus("unknown_status")
FailoverIPStatusReady = FailoverIPStatus("ready")
FailoverIPStatusBusy = FailoverIPStatus("busy")
FailoverIPStatusLocked = FailoverIPStatus("locked")
)
func (enum FailoverIPStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum FailoverIPStatus) Values() []FailoverIPStatus {
return []FailoverIPStatus{
"unknown_status",
"ready",
"busy",
"locked",
}
}
func (enum FailoverIPStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FailoverIPStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FailoverIPStatus(FailoverIPStatus(tmp).String())
return nil
}
type FailoverIPVersion string
const (
FailoverIPVersionUnknownVersion = FailoverIPVersion("unknown_version")
FailoverIPVersionIPv4 = FailoverIPVersion("ipv4")
FailoverIPVersionIPv6 = FailoverIPVersion("ipv6")
)
func (enum FailoverIPVersion) String() string {
if enum == "" {
// return default value if empty
return "unknown_version"
}
return string(enum)
}
func (enum FailoverIPVersion) Values() []FailoverIPVersion {
return []FailoverIPVersion{
"unknown_version",
"ipv4",
"ipv6",
}
}
func (enum FailoverIPVersion) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FailoverIPVersion) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FailoverIPVersion(FailoverIPVersion(tmp).String())
return nil
}
type GetRpnStatusResponseStatus string
const (
GetRpnStatusResponseStatusUnknownStatus = GetRpnStatusResponseStatus("unknown_status")
GetRpnStatusResponseStatusBusy = GetRpnStatusResponseStatus("busy")
GetRpnStatusResponseStatusOperational = GetRpnStatusResponseStatus("operational")
)
func (enum GetRpnStatusResponseStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum GetRpnStatusResponseStatus) Values() []GetRpnStatusResponseStatus {
return []GetRpnStatusResponseStatus{
"unknown_status",
"busy",
"operational",
}
}
func (enum GetRpnStatusResponseStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GetRpnStatusResponseStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GetRpnStatusResponseStatus(GetRpnStatusResponseStatus(tmp).String())
return nil
}
type IPSemantic string
const (
IPSemanticUnknown = IPSemantic("unknown")
IPSemanticProxad = IPSemantic("proxad")
IPSemanticExt = IPSemantic("ext")
IPSemanticPublic = IPSemantic("public")
IPSemanticPrivate = IPSemantic("private")
IPSemanticIpmi = IPSemantic("ipmi")
IPSemanticAdm = IPSemantic("adm")
IPSemanticRedirect = IPSemantic("redirect")
IPSemanticMigration = IPSemantic("migration")
)
func (enum IPSemantic) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum IPSemantic) Values() []IPSemantic {
return []IPSemantic{
"unknown",
"proxad",
"ext",
"public",
"private",
"ipmi",
"adm",
"redirect",
"migration",
}
}
func (enum IPSemantic) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPSemantic) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPSemantic(IPSemantic(tmp).String())
return nil
}
type IPStatus string
const (
IPStatusUnknownStatus = IPStatus("unknown_status")
IPStatusReady = IPStatus("ready")
IPStatusBusy = IPStatus("busy")
IPStatusLocked = IPStatus("locked")
)
func (enum IPStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum IPStatus) Values() []IPStatus {
return []IPStatus{
"unknown_status",
"ready",
"busy",
"locked",
}
}
func (enum IPStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPStatus(IPStatus(tmp).String())
return nil
}
type IPVersion string
const (
IPVersionIPv4 = IPVersion("ipv4")
IPVersionIPv6 = IPVersion("ipv6")
)
func (enum IPVersion) String() string {
if enum == "" {
// return default value if empty
return "ipv4"
}
return string(enum)
}
func (enum IPVersion) Values() []IPVersion {
return []IPVersion{
"ipv4",
"ipv6",
}
}
func (enum IPVersion) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPVersion) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPVersion(IPVersion(tmp).String())
return nil
}
type IPv6BlockDelegationStatus string
const (
IPv6BlockDelegationStatusUnknownStatus = IPv6BlockDelegationStatus("unknown_status")
IPv6BlockDelegationStatusUpdating = IPv6BlockDelegationStatus("updating")
IPv6BlockDelegationStatusDone = IPv6BlockDelegationStatus("done")
)
func (enum IPv6BlockDelegationStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum IPv6BlockDelegationStatus) Values() []IPv6BlockDelegationStatus {
return []IPv6BlockDelegationStatus{
"unknown_status",
"updating",
"done",
}
}
func (enum IPv6BlockDelegationStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPv6BlockDelegationStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPv6BlockDelegationStatus(IPv6BlockDelegationStatus(tmp).String())
return nil
}
type InvoicePaymentMethod string
const (
InvoicePaymentMethodUnknownPaymentMethod = InvoicePaymentMethod("unknown_payment_method")
InvoicePaymentMethodCreditCard = InvoicePaymentMethod("credit_card")
InvoicePaymentMethodAmex = InvoicePaymentMethod("amex")
InvoicePaymentMethodPaypal = InvoicePaymentMethod("paypal")
InvoicePaymentMethodTransfer = InvoicePaymentMethod("transfer")
InvoicePaymentMethodDirectDebit = InvoicePaymentMethod("direct_debit")
)
func (enum InvoicePaymentMethod) String() string {
if enum == "" {
// return default value if empty
return "unknown_payment_method"
}
return string(enum)
}
func (enum InvoicePaymentMethod) Values() []InvoicePaymentMethod {
return []InvoicePaymentMethod{
"unknown_payment_method",
"credit_card",
"amex",
"paypal",
"transfer",
"direct_debit",
}
}
func (enum InvoicePaymentMethod) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InvoicePaymentMethod) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InvoicePaymentMethod(InvoicePaymentMethod(tmp).String())
return nil
}
type InvoiceStatus string
const (
InvoiceStatusUnknownInvoiceStatus = InvoiceStatus("unknown_invoice_status")
InvoiceStatusUnpaid = InvoiceStatus("unpaid")
InvoiceStatusPaid = InvoiceStatus("paid")
InvoiceStatusErrored = InvoiceStatus("errored")
)
func (enum InvoiceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_invoice_status"
}
return string(enum)
}
func (enum InvoiceStatus) Values() []InvoiceStatus {
return []InvoiceStatus{
"unknown_invoice_status",
"unpaid",
"paid",
"errored",
}
}
func (enum InvoiceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InvoiceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InvoiceStatus(InvoiceStatus(tmp).String())
return nil
}
type ListFailoverIPsRequestOrderBy string
const (
ListFailoverIPsRequestOrderByIPAsc = ListFailoverIPsRequestOrderBy("ip_asc")
ListFailoverIPsRequestOrderByIPDesc = ListFailoverIPsRequestOrderBy("ip_desc")
)
func (enum ListFailoverIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "ip_asc"
}
return string(enum)
}
func (enum ListFailoverIPsRequestOrderBy) Values() []ListFailoverIPsRequestOrderBy {
return []ListFailoverIPsRequestOrderBy{
"ip_asc",
"ip_desc",
}
}
func (enum ListFailoverIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListFailoverIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListFailoverIPsRequestOrderBy(ListFailoverIPsRequestOrderBy(tmp).String())
return nil
}
type ListInvoicesRequestOrderBy string
const (
ListInvoicesRequestOrderByCreatedAtAsc = ListInvoicesRequestOrderBy("created_at_asc")
ListInvoicesRequestOrderByCreatedAtDesc = ListInvoicesRequestOrderBy("created_at_desc")
)
func (enum ListInvoicesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInvoicesRequestOrderBy) Values() []ListInvoicesRequestOrderBy {
return []ListInvoicesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListInvoicesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInvoicesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInvoicesRequestOrderBy(ListInvoicesRequestOrderBy(tmp).String())
return nil
}
type ListOSRequestOrderBy string
const (
ListOSRequestOrderByCreatedAtAsc = ListOSRequestOrderBy("created_at_asc")
ListOSRequestOrderByCreatedAtDesc = ListOSRequestOrderBy("created_at_desc")
ListOSRequestOrderByReleasedAtAsc = ListOSRequestOrderBy("released_at_asc")
ListOSRequestOrderByReleasedAtDesc = ListOSRequestOrderBy("released_at_desc")
)
func (enum ListOSRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListOSRequestOrderBy) Values() []ListOSRequestOrderBy {
return []ListOSRequestOrderBy{
"created_at_asc",
"created_at_desc",
"released_at_asc",
"released_at_desc",
}
}
func (enum ListOSRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListOSRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListOSRequestOrderBy(ListOSRequestOrderBy(tmp).String())
return nil
}
type ListOffersRequestOrderBy string
const (
ListOffersRequestOrderByCreatedAtAsc = ListOffersRequestOrderBy("created_at_asc")
ListOffersRequestOrderByCreatedAtDesc = ListOffersRequestOrderBy("created_at_desc")
ListOffersRequestOrderByNameAsc = ListOffersRequestOrderBy("name_asc")
ListOffersRequestOrderByNameDesc = ListOffersRequestOrderBy("name_desc")
ListOffersRequestOrderByPriceAsc = ListOffersRequestOrderBy("price_asc")
ListOffersRequestOrderByPriceDesc = ListOffersRequestOrderBy("price_desc")
)
func (enum ListOffersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListOffersRequestOrderBy) Values() []ListOffersRequestOrderBy {
return []ListOffersRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"price_asc",
"price_desc",
}
}
func (enum ListOffersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListOffersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListOffersRequestOrderBy(ListOffersRequestOrderBy(tmp).String())
return nil
}
type ListRefundsRequestOrderBy string
const (
ListRefundsRequestOrderByCreatedAtAsc = ListRefundsRequestOrderBy("created_at_asc")
ListRefundsRequestOrderByCreatedAtDesc = ListRefundsRequestOrderBy("created_at_desc")
)
func (enum ListRefundsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRefundsRequestOrderBy) Values() []ListRefundsRequestOrderBy {
return []ListRefundsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRefundsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRefundsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRefundsRequestOrderBy(ListRefundsRequestOrderBy(tmp).String())
return nil
}
type ListRpnCapableSanServersRequestOrderBy string
const (
ListRpnCapableSanServersRequestOrderByCreatedAtAsc = ListRpnCapableSanServersRequestOrderBy("created_at_asc")
ListRpnCapableSanServersRequestOrderByCreatedAtDesc = ListRpnCapableSanServersRequestOrderBy("created_at_desc")
)
func (enum ListRpnCapableSanServersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnCapableSanServersRequestOrderBy) Values() []ListRpnCapableSanServersRequestOrderBy {
return []ListRpnCapableSanServersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnCapableSanServersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnCapableSanServersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnCapableSanServersRequestOrderBy(ListRpnCapableSanServersRequestOrderBy(tmp).String())
return nil
}
type ListRpnCapableServersRequestOrderBy string
const (
ListRpnCapableServersRequestOrderByCreatedAtAsc = ListRpnCapableServersRequestOrderBy("created_at_asc")
ListRpnCapableServersRequestOrderByCreatedAtDesc = ListRpnCapableServersRequestOrderBy("created_at_desc")
)
func (enum ListRpnCapableServersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnCapableServersRequestOrderBy) Values() []ListRpnCapableServersRequestOrderBy {
return []ListRpnCapableServersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnCapableServersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnCapableServersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnCapableServersRequestOrderBy(ListRpnCapableServersRequestOrderBy(tmp).String())
return nil
}
type ListRpnGroupMembersRequestOrderBy string
const (
ListRpnGroupMembersRequestOrderByCreatedAtAsc = ListRpnGroupMembersRequestOrderBy("created_at_asc")
ListRpnGroupMembersRequestOrderByCreatedAtDesc = ListRpnGroupMembersRequestOrderBy("created_at_desc")
)
func (enum ListRpnGroupMembersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnGroupMembersRequestOrderBy) Values() []ListRpnGroupMembersRequestOrderBy {
return []ListRpnGroupMembersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnGroupMembersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnGroupMembersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnGroupMembersRequestOrderBy(ListRpnGroupMembersRequestOrderBy(tmp).String())
return nil
}
type ListRpnGroupsRequestOrderBy string
const (
ListRpnGroupsRequestOrderByCreatedAtAsc = ListRpnGroupsRequestOrderBy("created_at_asc")
ListRpnGroupsRequestOrderByCreatedAtDesc = ListRpnGroupsRequestOrderBy("created_at_desc")
)
func (enum ListRpnGroupsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnGroupsRequestOrderBy) Values() []ListRpnGroupsRequestOrderBy {
return []ListRpnGroupsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnGroupsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnGroupsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnGroupsRequestOrderBy(ListRpnGroupsRequestOrderBy(tmp).String())
return nil
}
type ListRpnInvitesRequestOrderBy string
const (
ListRpnInvitesRequestOrderByCreatedAtAsc = ListRpnInvitesRequestOrderBy("created_at_asc")
ListRpnInvitesRequestOrderByCreatedAtDesc = ListRpnInvitesRequestOrderBy("created_at_desc")
)
func (enum ListRpnInvitesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnInvitesRequestOrderBy) Values() []ListRpnInvitesRequestOrderBy {
return []ListRpnInvitesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnInvitesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnInvitesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnInvitesRequestOrderBy(ListRpnInvitesRequestOrderBy(tmp).String())
return nil
}
type ListRpnSansRequestOrderBy string
const (
ListRpnSansRequestOrderByCreatedAtAsc = ListRpnSansRequestOrderBy("created_at_asc")
ListRpnSansRequestOrderByCreatedAtDesc = ListRpnSansRequestOrderBy("created_at_desc")
)
func (enum ListRpnSansRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnSansRequestOrderBy) Values() []ListRpnSansRequestOrderBy {
return []ListRpnSansRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnSansRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnSansRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnSansRequestOrderBy(ListRpnSansRequestOrderBy(tmp).String())
return nil
}
type ListRpnServerCapabilitiesRequestOrderBy string
const (
ListRpnServerCapabilitiesRequestOrderByCreatedAtAsc = ListRpnServerCapabilitiesRequestOrderBy("created_at_asc")
ListRpnServerCapabilitiesRequestOrderByCreatedAtDesc = ListRpnServerCapabilitiesRequestOrderBy("created_at_desc")
)
func (enum ListRpnServerCapabilitiesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnServerCapabilitiesRequestOrderBy) Values() []ListRpnServerCapabilitiesRequestOrderBy {
return []ListRpnServerCapabilitiesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnServerCapabilitiesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnServerCapabilitiesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnServerCapabilitiesRequestOrderBy(ListRpnServerCapabilitiesRequestOrderBy(tmp).String())
return nil
}
type ListRpnV2CapableResourcesRequestOrderBy string
const (
ListRpnV2CapableResourcesRequestOrderByCreatedAtAsc = ListRpnV2CapableResourcesRequestOrderBy("created_at_asc")
ListRpnV2CapableResourcesRequestOrderByCreatedAtDesc = ListRpnV2CapableResourcesRequestOrderBy("created_at_desc")
)
func (enum ListRpnV2CapableResourcesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnV2CapableResourcesRequestOrderBy) Values() []ListRpnV2CapableResourcesRequestOrderBy {
return []ListRpnV2CapableResourcesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnV2CapableResourcesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnV2CapableResourcesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnV2CapableResourcesRequestOrderBy(ListRpnV2CapableResourcesRequestOrderBy(tmp).String())
return nil
}
type ListRpnV2GroupLogsRequestOrderBy string
const (
ListRpnV2GroupLogsRequestOrderByCreatedAtAsc = ListRpnV2GroupLogsRequestOrderBy("created_at_asc")
ListRpnV2GroupLogsRequestOrderByCreatedAtDesc = ListRpnV2GroupLogsRequestOrderBy("created_at_desc")
)
func (enum ListRpnV2GroupLogsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnV2GroupLogsRequestOrderBy) Values() []ListRpnV2GroupLogsRequestOrderBy {
return []ListRpnV2GroupLogsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnV2GroupLogsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnV2GroupLogsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnV2GroupLogsRequestOrderBy(ListRpnV2GroupLogsRequestOrderBy(tmp).String())
return nil
}
type ListRpnV2GroupsRequestOrderBy string
const (
ListRpnV2GroupsRequestOrderByCreatedAtAsc = ListRpnV2GroupsRequestOrderBy("created_at_asc")
ListRpnV2GroupsRequestOrderByCreatedAtDesc = ListRpnV2GroupsRequestOrderBy("created_at_desc")
)
func (enum ListRpnV2GroupsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnV2GroupsRequestOrderBy) Values() []ListRpnV2GroupsRequestOrderBy {
return []ListRpnV2GroupsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnV2GroupsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnV2GroupsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnV2GroupsRequestOrderBy(ListRpnV2GroupsRequestOrderBy(tmp).String())
return nil
}
type ListRpnV2MembersRequestOrderBy string
const (
ListRpnV2MembersRequestOrderByCreatedAtAsc = ListRpnV2MembersRequestOrderBy("created_at_asc")
ListRpnV2MembersRequestOrderByCreatedAtDesc = ListRpnV2MembersRequestOrderBy("created_at_desc")
)
func (enum ListRpnV2MembersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRpnV2MembersRequestOrderBy) Values() []ListRpnV2MembersRequestOrderBy {
return []ListRpnV2MembersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRpnV2MembersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnV2MembersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnV2MembersRequestOrderBy(ListRpnV2MembersRequestOrderBy(tmp).String())
return nil
}
type ListRpnV2MembersRequestType string
const (
ListRpnV2MembersRequestTypeUnknownType = ListRpnV2MembersRequestType("unknown_type")
ListRpnV2MembersRequestTypeRpnv1Group = ListRpnV2MembersRequestType("rpnv1_group")
ListRpnV2MembersRequestTypeServer = ListRpnV2MembersRequestType("server")
)
func (enum ListRpnV2MembersRequestType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ListRpnV2MembersRequestType) Values() []ListRpnV2MembersRequestType {
return []ListRpnV2MembersRequestType{
"unknown_type",
"rpnv1_group",
"server",
}
}
func (enum ListRpnV2MembersRequestType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRpnV2MembersRequestType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRpnV2MembersRequestType(ListRpnV2MembersRequestType(tmp).String())
return nil
}
type ListServerDisksRequestOrderBy string
const (
ListServerDisksRequestOrderByCreatedAtAsc = ListServerDisksRequestOrderBy("created_at_asc")
ListServerDisksRequestOrderByCreatedAtDesc = ListServerDisksRequestOrderBy("created_at_desc")
)
func (enum ListServerDisksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerDisksRequestOrderBy) Values() []ListServerDisksRequestOrderBy {
return []ListServerDisksRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServerDisksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerDisksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerDisksRequestOrderBy(ListServerDisksRequestOrderBy(tmp).String())
return nil
}
type ListServerEventsRequestOrderBy string
const (
ListServerEventsRequestOrderByCreatedAtAsc = ListServerEventsRequestOrderBy("created_at_asc")
ListServerEventsRequestOrderByCreatedAtDesc = ListServerEventsRequestOrderBy("created_at_desc")
)
func (enum ListServerEventsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServerEventsRequestOrderBy) Values() []ListServerEventsRequestOrderBy {
return []ListServerEventsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServerEventsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServerEventsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServerEventsRequestOrderBy(ListServerEventsRequestOrderBy(tmp).String())
return nil
}
type ListServersRequestOrderBy string
const (
ListServersRequestOrderByCreatedAtAsc = ListServersRequestOrderBy("created_at_asc")
ListServersRequestOrderByCreatedAtDesc = ListServersRequestOrderBy("created_at_desc")
)
func (enum ListServersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServersRequestOrderBy) Values() []ListServersRequestOrderBy {
return []ListServersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServersRequestOrderBy(ListServersRequestOrderBy(tmp).String())
return nil
}
type ListServicesRequestOrderBy string
const (
ListServicesRequestOrderByCreatedAtAsc = ListServicesRequestOrderBy("created_at_asc")
ListServicesRequestOrderByCreatedAtDesc = ListServicesRequestOrderBy("created_at_desc")
)
func (enum ListServicesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListServicesRequestOrderBy) Values() []ListServicesRequestOrderBy {
return []ListServicesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListServicesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServicesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServicesRequestOrderBy(ListServicesRequestOrderBy(tmp).String())
return nil
}
type LogAction string
const (
LogActionUnknownLogAction = LogAction("unknown_log_action")
LogActionGroupCreated = LogAction("group_created")
LogActionGroupDeleted = LogAction("group_deleted")
LogActionMembersAdded = LogAction("members_added")
LogActionMembersDeleted = LogAction("members_deleted")
LogActionDescriptionUpdated = LogAction("description_updated")
LogActionRpnv1MembersAdded = LogAction("rpnv1_members_added")
LogActionRpnv1MembersDeleted = LogAction("rpnv1_members_deleted")
LogActionVlanUpdated = LogAction("vlan_updated")
LogActionVlanUpdatedOnAllServers = LogAction("vlan_updated_on_all_servers")
)
func (enum LogAction) String() string {
if enum == "" {
// return default value if empty
return "unknown_log_action"
}
return string(enum)
}
func (enum LogAction) Values() []LogAction {
return []LogAction{
"unknown_log_action",
"group_created",
"group_deleted",
"members_added",
"members_deleted",
"description_updated",
"rpnv1_members_added",
"rpnv1_members_deleted",
"vlan_updated",
"vlan_updated_on_all_servers",
}
}
func (enum LogAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LogAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LogAction(LogAction(tmp).String())
return nil
}
type LogStatus string
const (
LogStatusUnknownLogStatus = LogStatus("unknown_log_status")
LogStatusSuccess = LogStatus("success")
LogStatusInProgress = LogStatus("in_progress")
LogStatusError = LogStatus("error")
)
func (enum LogStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_log_status"
}
return string(enum)
}
func (enum LogStatus) Values() []LogStatus {
return []LogStatus{
"unknown_log_status",
"success",
"in_progress",
"error",
}
}
func (enum LogStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LogStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LogStatus(LogStatus(tmp).String())
return nil
}
type MemoryType string
const (
MemoryTypeDdr2 = MemoryType("ddr2")
MemoryTypeDdr3 = MemoryType("ddr3")
MemoryTypeDdr4 = MemoryType("ddr4")
MemoryTypeDdr5 = MemoryType("ddr5")
)
func (enum MemoryType) String() string {
if enum == "" {
// return default value if empty
return "ddr2"
}
return string(enum)
}
func (enum MemoryType) Values() []MemoryType {
return []MemoryType{
"ddr2",
"ddr3",
"ddr4",
"ddr5",
}
}
func (enum MemoryType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MemoryType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MemoryType(MemoryType(tmp).String())
return nil
}
type NetworkInterfaceInterfaceType string
const (
NetworkInterfaceInterfaceTypeUnknown = NetworkInterfaceInterfaceType("unknown")
NetworkInterfaceInterfaceTypeNormal = NetworkInterfaceInterfaceType("normal")
NetworkInterfaceInterfaceTypeIpmi = NetworkInterfaceInterfaceType("ipmi")
NetworkInterfaceInterfaceTypeVirtual = NetworkInterfaceInterfaceType("virtual")
)
func (enum NetworkInterfaceInterfaceType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NetworkInterfaceInterfaceType) Values() []NetworkInterfaceInterfaceType {
return []NetworkInterfaceInterfaceType{
"unknown",
"normal",
"ipmi",
"virtual",
}
}
func (enum NetworkInterfaceInterfaceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NetworkInterfaceInterfaceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NetworkInterfaceInterfaceType(NetworkInterfaceInterfaceType(tmp).String())
return nil
}
type OSArch string
const (
OSArchUnknownArch = OSArch("unknown_arch")
OSArchAmd64 = OSArch("amd64")
OSArchX86 = OSArch("x86")
OSArchArm = OSArch("arm")
OSArchArm64 = OSArch("arm64")
)
func (enum OSArch) String() string {
if enum == "" {
// return default value if empty
return "unknown_arch"
}
return string(enum)
}
func (enum OSArch) Values() []OSArch {
return []OSArch{
"unknown_arch",
"amd64",
"x86",
"arm",
"arm64",
}
}
func (enum OSArch) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OSArch) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OSArch(OSArch(tmp).String())
return nil
}
type OSType string
const (
OSTypeUnknownType = OSType("unknown_type")
OSTypeServer = OSType("server")
OSTypeVirtu = OSType("virtu")
OSTypePanel = OSType("panel")
OSTypeDesktop = OSType("desktop")
OSTypeCustom = OSType("custom")
OSTypeRescue = OSType("rescue")
)
func (enum OSType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum OSType) Values() []OSType {
return []OSType{
"unknown_type",
"server",
"virtu",
"panel",
"desktop",
"custom",
"rescue",
}
}
func (enum OSType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OSType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OSType(OSType(tmp).String())
return nil
}
type OfferAntiDosInfoType string
const (
OfferAntiDosInfoTypeMinimal = OfferAntiDosInfoType("minimal")
OfferAntiDosInfoTypePreventive = OfferAntiDosInfoType("preventive")
OfferAntiDosInfoTypeCurative = OfferAntiDosInfoType("curative")
)
func (enum OfferAntiDosInfoType) String() string {
if enum == "" {
// return default value if empty
return "minimal"
}
return string(enum)
}
func (enum OfferAntiDosInfoType) Values() []OfferAntiDosInfoType {
return []OfferAntiDosInfoType{
"minimal",
"preventive",
"curative",
}
}
func (enum OfferAntiDosInfoType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferAntiDosInfoType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferAntiDosInfoType(OfferAntiDosInfoType(tmp).String())
return nil
}
type OfferCatalog string
const (
OfferCatalogAll = OfferCatalog("all")
OfferCatalogDefault = OfferCatalog("default")
OfferCatalogBeta = OfferCatalog("beta")
OfferCatalogReseller = OfferCatalog("reseller")
OfferCatalogPremium = OfferCatalog("premium")
OfferCatalogVolume = OfferCatalog("volume")
OfferCatalogAdmin = OfferCatalog("admin")
OfferCatalogInactive = OfferCatalog("inactive")
)
func (enum OfferCatalog) String() string {
if enum == "" {
// return default value if empty
return "all"
}
return string(enum)
}
func (enum OfferCatalog) Values() []OfferCatalog {
return []OfferCatalog{
"all",
"default",
"beta",
"reseller",
"premium",
"volume",
"admin",
"inactive",
}
}
func (enum OfferCatalog) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferCatalog) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferCatalog(OfferCatalog(tmp).String())
return nil
}
type OfferPaymentFrequency string
const (
OfferPaymentFrequencyMonthly = OfferPaymentFrequency("monthly")
OfferPaymentFrequencyOneshot = OfferPaymentFrequency("oneshot")
)
func (enum OfferPaymentFrequency) String() string {
if enum == "" {
// return default value if empty
return "monthly"
}
return string(enum)
}
func (enum OfferPaymentFrequency) Values() []OfferPaymentFrequency {
return []OfferPaymentFrequency{
"monthly",
"oneshot",
}
}
func (enum OfferPaymentFrequency) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferPaymentFrequency) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferPaymentFrequency(OfferPaymentFrequency(tmp).String())
return nil
}
type OfferSANInfoType string
const (
OfferSANInfoTypeHdd = OfferSANInfoType("hdd")
OfferSANInfoTypeSSD = OfferSANInfoType("ssd")
)
func (enum OfferSANInfoType) String() string {
if enum == "" {
// return default value if empty
return "hdd"
}
return string(enum)
}
func (enum OfferSANInfoType) Values() []OfferSANInfoType {
return []OfferSANInfoType{
"hdd",
"ssd",
}
}
func (enum OfferSANInfoType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferSANInfoType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferSANInfoType(OfferSANInfoType(tmp).String())
return nil
}
type OfferServerInfoStock string
const (
OfferServerInfoStockEmpty = OfferServerInfoStock("empty")
OfferServerInfoStockLow = OfferServerInfoStock("low")
OfferServerInfoStockAvailable = OfferServerInfoStock("available")
)
func (enum OfferServerInfoStock) String() string {
if enum == "" {
// return default value if empty
return "empty"
}
return string(enum)
}
func (enum OfferServerInfoStock) Values() []OfferServerInfoStock {
return []OfferServerInfoStock{
"empty",
"low",
"available",
}
}
func (enum OfferServerInfoStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferServerInfoStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferServerInfoStock(OfferServerInfoStock(tmp).String())
return nil
}
type PartitionFileSystem string
const (
PartitionFileSystemUnknown = PartitionFileSystem("unknown")
PartitionFileSystemEfi = PartitionFileSystem("efi")
PartitionFileSystemSwap = PartitionFileSystem("swap")
PartitionFileSystemExt4 = PartitionFileSystem("ext4")
PartitionFileSystemExt3 = PartitionFileSystem("ext3")
PartitionFileSystemExt2 = PartitionFileSystem("ext2")
PartitionFileSystemXfs = PartitionFileSystem("xfs")
PartitionFileSystemNtfs = PartitionFileSystem("ntfs")
PartitionFileSystemFat32 = PartitionFileSystem("fat32")
PartitionFileSystemUfs = PartitionFileSystem("ufs")
)
func (enum PartitionFileSystem) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum PartitionFileSystem) Values() []PartitionFileSystem {
return []PartitionFileSystem{
"unknown",
"efi",
"swap",
"ext4",
"ext3",
"ext2",
"xfs",
"ntfs",
"fat32",
"ufs",
}
}
func (enum PartitionFileSystem) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PartitionFileSystem) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PartitionFileSystem(PartitionFileSystem(tmp).String())
return nil
}
type PartitionType string
const (
PartitionTypePrimary = PartitionType("primary")
PartitionTypeExtended = PartitionType("extended")
PartitionTypeLogical = PartitionType("logical")
)
func (enum PartitionType) String() string {
if enum == "" {
// return default value if empty
return "primary"
}
return string(enum)
}
func (enum PartitionType) Values() []PartitionType {
return []PartitionType{
"primary",
"extended",
"logical",
}
}
func (enum PartitionType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PartitionType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PartitionType(PartitionType(tmp).String())
return nil
}
type RaidArrayRaidLevel string
const (
RaidArrayRaidLevelNoRaid = RaidArrayRaidLevel("no_raid")
RaidArrayRaidLevelRaid0 = RaidArrayRaidLevel("raid0")
RaidArrayRaidLevelRaid1 = RaidArrayRaidLevel("raid1")
RaidArrayRaidLevelRaid5 = RaidArrayRaidLevel("raid5")
RaidArrayRaidLevelRaid6 = RaidArrayRaidLevel("raid6")
RaidArrayRaidLevelRaid10 = RaidArrayRaidLevel("raid10")
)
func (enum RaidArrayRaidLevel) String() string {
if enum == "" {
// return default value if empty
return "no_raid"
}
return string(enum)
}
func (enum RaidArrayRaidLevel) Values() []RaidArrayRaidLevel {
return []RaidArrayRaidLevel{
"no_raid",
"raid0",
"raid1",
"raid5",
"raid6",
"raid10",
}
}
func (enum RaidArrayRaidLevel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RaidArrayRaidLevel) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RaidArrayRaidLevel(RaidArrayRaidLevel(tmp).String())
return nil
}
type RefundMethod string
const (
RefundMethodUnknownRefundMethod = RefundMethod("unknown_refund_method")
RefundMethodCreditCard = RefundMethod("credit_card")
RefundMethodAmex = RefundMethod("amex")
RefundMethodPaypal = RefundMethod("paypal")
RefundMethodTransfer = RefundMethod("transfer")
)
func (enum RefundMethod) String() string {
if enum == "" {
// return default value if empty
return "unknown_refund_method"
}
return string(enum)
}
func (enum RefundMethod) Values() []RefundMethod {
return []RefundMethod{
"unknown_refund_method",
"credit_card",
"amex",
"paypal",
"transfer",
}
}
func (enum RefundMethod) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RefundMethod) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RefundMethod(RefundMethod(tmp).String())
return nil
}
type RefundStatus string
const (
RefundStatusUnknownRefundStatus = RefundStatus("unknown_refund_status")
RefundStatusUnpaid = RefundStatus("unpaid")
RefundStatusPaid = RefundStatus("paid")
RefundStatusErrored = RefundStatus("errored")
)
func (enum RefundStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_refund_status"
}
return string(enum)
}
func (enum RefundStatus) Values() []RefundStatus {
return []RefundStatus{
"unknown_refund_status",
"unpaid",
"paid",
"errored",
}
}
func (enum RefundStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RefundStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RefundStatus(RefundStatus(tmp).String())
return nil
}
type RescueProtocol string
const (
RescueProtocolVnc = RescueProtocol("vnc")
RescueProtocolSSH = RescueProtocol("ssh")
)
func (enum RescueProtocol) String() string {
if enum == "" {
// return default value if empty
return "vnc"
}
return string(enum)
}
func (enum RescueProtocol) Values() []RescueProtocol {
return []RescueProtocol{
"vnc",
"ssh",
}
}
func (enum RescueProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RescueProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RescueProtocol(RescueProtocol(tmp).String())
return nil
}
type RpnGroupMemberStatus string
const (
RpnGroupMemberStatusUnknownRpnMemberStatus = RpnGroupMemberStatus("unknown_rpn_member_status")
RpnGroupMemberStatusPendingInvitation = RpnGroupMemberStatus("pending_invitation")
RpnGroupMemberStatusActive = RpnGroupMemberStatus("active")
RpnGroupMemberStatusCreating = RpnGroupMemberStatus("creating")
RpnGroupMemberStatusDeleting = RpnGroupMemberStatus("deleting")
RpnGroupMemberStatusDeleted = RpnGroupMemberStatus("deleted")
)
func (enum RpnGroupMemberStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_rpn_member_status"
}
return string(enum)
}
func (enum RpnGroupMemberStatus) Values() []RpnGroupMemberStatus {
return []RpnGroupMemberStatus{
"unknown_rpn_member_status",
"pending_invitation",
"active",
"creating",
"deleting",
"deleted",
}
}
func (enum RpnGroupMemberStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnGroupMemberStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnGroupMemberStatus(RpnGroupMemberStatus(tmp).String())
return nil
}
type RpnGroupType string
const (
RpnGroupTypeUnknown = RpnGroupType("unknown")
RpnGroupTypeLocal = RpnGroupType("local")
RpnGroupTypeShared = RpnGroupType("shared")
)
func (enum RpnGroupType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RpnGroupType) Values() []RpnGroupType {
return []RpnGroupType{
"unknown",
"local",
"shared",
}
}
func (enum RpnGroupType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnGroupType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnGroupType(RpnGroupType(tmp).String())
return nil
}
type RpnSanIPType string
const (
RpnSanIPTypeUnknown = RpnSanIPType("unknown")
RpnSanIPTypeServerIP = RpnSanIPType("server_ip")
RpnSanIPTypeRpnv2Subnet = RpnSanIPType("rpnv2_subnet")
)
func (enum RpnSanIPType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RpnSanIPType) Values() []RpnSanIPType {
return []RpnSanIPType{
"unknown",
"server_ip",
"rpnv2_subnet",
}
}
func (enum RpnSanIPType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnSanIPType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnSanIPType(RpnSanIPType(tmp).String())
return nil
}
type RpnSanStatus string
const (
RpnSanStatusUnknownStatus = RpnSanStatus("unknown_status")
RpnSanStatusCreating = RpnSanStatus("creating")
RpnSanStatusActive = RpnSanStatus("active")
RpnSanStatusDeleting = RpnSanStatus("deleting")
RpnSanStatusMaintenance = RpnSanStatus("maintenance")
)
func (enum RpnSanStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum RpnSanStatus) Values() []RpnSanStatus {
return []RpnSanStatus{
"unknown_status",
"creating",
"active",
"deleting",
"maintenance",
}
}
func (enum RpnSanStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnSanStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnSanStatus(RpnSanStatus(tmp).String())
return nil
}
type RpnV2GroupStatus string
const (
RpnV2GroupStatusUnknownGroupStatus = RpnV2GroupStatus("unknown_group_status")
RpnV2GroupStatusCreating = RpnV2GroupStatus("creating")
RpnV2GroupStatusActive = RpnV2GroupStatus("active")
RpnV2GroupStatusUpdating = RpnV2GroupStatus("updating")
RpnV2GroupStatusDeleting = RpnV2GroupStatus("deleting")
)
func (enum RpnV2GroupStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_group_status"
}
return string(enum)
}
func (enum RpnV2GroupStatus) Values() []RpnV2GroupStatus {
return []RpnV2GroupStatus{
"unknown_group_status",
"creating",
"active",
"updating",
"deleting",
}
}
func (enum RpnV2GroupStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnV2GroupStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnV2GroupStatus(RpnV2GroupStatus(tmp).String())
return nil
}
type RpnV2GroupType string
const (
RpnV2GroupTypeUnknownType = RpnV2GroupType("unknown_type")
RpnV2GroupTypeStandard = RpnV2GroupType("standard")
RpnV2GroupTypeQinq = RpnV2GroupType("qinq")
)
func (enum RpnV2GroupType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum RpnV2GroupType) Values() []RpnV2GroupType {
return []RpnV2GroupType{
"unknown_type",
"standard",
"qinq",
}
}
func (enum RpnV2GroupType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnV2GroupType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnV2GroupType(RpnV2GroupType(tmp).String())
return nil
}
type RpnV2MemberStatus string
const (
RpnV2MemberStatusUnknownMemberStatus = RpnV2MemberStatus("unknown_member_status")
RpnV2MemberStatusCreating = RpnV2MemberStatus("creating")
RpnV2MemberStatusActive = RpnV2MemberStatus("active")
RpnV2MemberStatusUpdating = RpnV2MemberStatus("updating")
RpnV2MemberStatusDeleting = RpnV2MemberStatus("deleting")
)
func (enum RpnV2MemberStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_member_status"
}
return string(enum)
}
func (enum RpnV2MemberStatus) Values() []RpnV2MemberStatus {
return []RpnV2MemberStatus{
"unknown_member_status",
"creating",
"active",
"updating",
"deleting",
}
}
func (enum RpnV2MemberStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RpnV2MemberStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RpnV2MemberStatus(RpnV2MemberStatus(tmp).String())
return nil
}
type ServerDiskType string
const (
ServerDiskTypeSata = ServerDiskType("sata")
ServerDiskTypeSSD = ServerDiskType("ssd")
ServerDiskTypeSas = ServerDiskType("sas")
ServerDiskTypeSshd = ServerDiskType("sshd")
ServerDiskTypeUsb = ServerDiskType("usb")
ServerDiskTypeNvme = ServerDiskType("nvme")
)
func (enum ServerDiskType) String() string {
if enum == "" {
// return default value if empty
return "sata"
}
return string(enum)
}
func (enum ServerDiskType) Values() []ServerDiskType {
return []ServerDiskType{
"sata",
"ssd",
"sas",
"sshd",
"usb",
"nvme",
}
}
func (enum ServerDiskType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerDiskType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerDiskType(ServerDiskType(tmp).String())
return nil
}
type ServerInstallStatus string
const (
ServerInstallStatusUnknown = ServerInstallStatus("unknown")
ServerInstallStatusBooting = ServerInstallStatus("booting")
ServerInstallStatusSettingUpRaid = ServerInstallStatus("setting_up_raid")
ServerInstallStatusPartitioning = ServerInstallStatus("partitioning")
ServerInstallStatusFormatting = ServerInstallStatus("formatting")
ServerInstallStatusInstalling = ServerInstallStatus("installing")
ServerInstallStatusConfiguring = ServerInstallStatus("configuring")
ServerInstallStatusConfiguringBootloader = ServerInstallStatus("configuring_bootloader")
ServerInstallStatusRebooting = ServerInstallStatus("rebooting")
ServerInstallStatusInstalled = ServerInstallStatus("installed")
)
func (enum ServerInstallStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServerInstallStatus) Values() []ServerInstallStatus {
return []ServerInstallStatus{
"unknown",
"booting",
"setting_up_raid",
"partitioning",
"formatting",
"installing",
"configuring",
"configuring_bootloader",
"rebooting",
"installed",
}
}
func (enum ServerInstallStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerInstallStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerInstallStatus(ServerInstallStatus(tmp).String())
return nil
}
type ServerStatus string
const (
ServerStatusUnknown = ServerStatus("unknown")
ServerStatusDelivering = ServerStatus("delivering")
ServerStatusInstalling = ServerStatus("installing")
ServerStatusReady = ServerStatus("ready")
ServerStatusStopped = ServerStatus("stopped")
ServerStatusError = ServerStatus("error")
ServerStatusLocked = ServerStatus("locked")
ServerStatusRescue = ServerStatus("rescue")
ServerStatusBusy = ServerStatus("busy")
)
func (enum ServerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServerStatus) Values() []ServerStatus {
return []ServerStatus{
"unknown",
"delivering",
"installing",
"ready",
"stopped",
"error",
"locked",
"rescue",
"busy",
}
}
func (enum ServerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerStatus(ServerStatus(tmp).String())
return nil
}
type ServiceLevelLevel string
const (
ServiceLevelLevelUnknown = ServiceLevelLevel("unknown")
ServiceLevelLevelBasic = ServiceLevelLevel("basic")
ServiceLevelLevelBusiness = ServiceLevelLevel("business")
)
func (enum ServiceLevelLevel) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServiceLevelLevel) Values() []ServiceLevelLevel {
return []ServiceLevelLevel{
"unknown",
"basic",
"business",
}
}
func (enum ServiceLevelLevel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServiceLevelLevel) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServiceLevelLevel(ServiceLevelLevel(tmp).String())
return nil
}
type ServiceProvisioningStatus string
const (
ServiceProvisioningStatusUnknown = ServiceProvisioningStatus("unknown")
ServiceProvisioningStatusDelivering = ServiceProvisioningStatus("delivering")
ServiceProvisioningStatusReady = ServiceProvisioningStatus("ready")
ServiceProvisioningStatusError = ServiceProvisioningStatus("error")
ServiceProvisioningStatusExpiring = ServiceProvisioningStatus("expiring")
ServiceProvisioningStatusExpired = ServiceProvisioningStatus("expired")
)
func (enum ServiceProvisioningStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ServiceProvisioningStatus) Values() []ServiceProvisioningStatus {
return []ServiceProvisioningStatus{
"unknown",
"delivering",
"ready",
"error",
"expiring",
"expired",
}
}
func (enum ServiceProvisioningStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServiceProvisioningStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServiceProvisioningStatus(ServiceProvisioningStatus(tmp).String())
return nil
}
type ServiceType string
const (
ServiceTypeUnknownType = ServiceType("unknown_type")
ServiceTypeService = ServiceType("service")
ServiceTypeOrder = ServiceType("order")
)
func (enum ServiceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ServiceType) Values() []ServiceType {
return []ServiceType{
"unknown_type",
"service",
"order",
}
}
func (enum ServiceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServiceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServiceType(ServiceType(tmp).String())
return nil
}
// OfferAntiDosInfo: offer anti dos info.
type OfferAntiDosInfo struct {
// Type: default value: minimal
Type OfferAntiDosInfoType `json:"type"`
}
// OfferBackupInfo: offer backup info.
type OfferBackupInfo struct {
Size scw.Size `json:"size"`
}
// OfferBandwidthInfo: offer bandwidth info.
type OfferBandwidthInfo struct {
Speed uint32 `json:"speed"`
}
// OfferLicenseInfo: offer license info.
type OfferLicenseInfo struct {
BoundToIP bool `json:"bound_to_ip"`
}
// OfferRPNInfo: offer rpn info.
type OfferRPNInfo struct {
Speed uint32 `json:"speed"`
}
// OfferSANInfo: offer san info.
type OfferSANInfo struct {
// Size: sAN size (in bytes).
Size uint64 `json:"size"`
// Ha: high availabilty offer.
Ha bool `json:"ha"`
// DeviceType: type of SAN device (hdd / ssd).
// Default value: hdd
DeviceType OfferSANInfoType `json:"device_type"`
}
// OfferStorageInfo: offer storage info.
type OfferStorageInfo struct {
MaxQuota uint32 `json:"max_quota"`
Size scw.Size `json:"size"`
}
// IP: ip.
type IP struct {
// IPID: ID of the IP.
IPID uint64 `json:"ip_id"`
// Address: address of the IP.
Address net.IP `json:"address"`
// Reverse: reverse IP value.
Reverse string `json:"reverse"`
// Version: version of IP (v4 or v6).
// Default value: ipv4
Version IPVersion `json:"version"`
// Cidr: classless InterDomain Routing notation of the IP.
Cidr uint32 `json:"cidr"`
// Netmask: network mask of IP.
Netmask net.IP `json:"netmask"`
// Semantic: semantic of IP.
// Default value: unknown
Semantic IPSemantic `json:"semantic"`
// Gateway: gateway of IP.
Gateway net.IP `json:"gateway"`
// Status: status of the IP.
// Default value: unknown_status
Status IPStatus `json:"status"`
}
// Offer: offer.
type Offer struct {
// ID: ID of the offer.
ID uint64 `json:"id"`
// Name: name of the offer.
Name string `json:"name"`
// Catalog: catalog of the offer.
// Default value: all
Catalog OfferCatalog `json:"catalog"`
// PaymentFrequency: payment frequency of the offer.
// Default value: monthly
PaymentFrequency OfferPaymentFrequency `json:"payment_frequency"`
// Pricing: price of the offer.
Pricing *scw.Money `json:"pricing"`
// ServerInfo: server info if it is a server offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
ServerInfo *OfferServerInfo `json:"server_info,omitempty"`
// ServiceLevelInfo: service level info if it is a service level offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
ServiceLevelInfo *OfferServiceLevelInfo `json:"service_level_info,omitempty"`
// RpnInfo: rPN info if it is a RPN offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
RpnInfo *OfferRPNInfo `json:"rpn_info,omitempty"`
// SanInfo: sAN info if it is a SAN offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
SanInfo *OfferSANInfo `json:"san_info,omitempty"`
// AntidosInfo: antiDOS info if it is a antiDOS offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
AntidosInfo *OfferAntiDosInfo `json:"antidos_info,omitempty"`
// BackupInfo: backup info if it is a backup offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
BackupInfo *OfferBackupInfo `json:"backup_info,omitempty"`
// UsbStorageInfo: uSB storage info if it is a USB storage offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
UsbStorageInfo *OfferStorageInfo `json:"usb_storage_info,omitempty"`
// StorageInfo: storage info if it is a storage offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
StorageInfo *OfferStorageInfo `json:"storage_info,omitempty"`
// LicenseInfo: license info if it is a license offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
LicenseInfo *OfferLicenseInfo `json:"license_info,omitempty"`
// FailoverIPInfo: failover IP info if it is a failover IP offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
FailoverIPInfo *OfferFailoverIPInfo `json:"failover_ip_info,omitempty"`
// FailoverBlockInfo: failover block info if it is a failover block offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
FailoverBlockInfo *OfferFailoverBlockInfo `json:"failover_block_info,omitempty"`
// BandwidthInfo: bandwidth info if it is a bandwidth offer.
// Precisely one of ServerInfo, ServiceLevelInfo, RpnInfo, SanInfo, AntidosInfo, BackupInfo, UsbStorageInfo, StorageInfo, LicenseInfo, FailoverIPInfo, FailoverBlockInfo, BandwidthInfo must be set.
BandwidthInfo *OfferBandwidthInfo `json:"bandwidth_info,omitempty"`
}
// NetworkInterface: network interface.
type NetworkInterface struct {
// CardID: card ID of the network interface.
CardID uint64 `json:"card_id"`
// DeviceID: device ID of the network interface.
DeviceID uint64 `json:"device_id"`
// Mac: mAC address of the network interface.
Mac string `json:"mac"`
// Type: network interface type.
// Default value: unknown
Type NetworkInterfaceInterfaceType `json:"type"`
// IPs: iPs of the network interface.
IPs []*IP `json:"ips"`
}
// OS: os.
type OS struct {
// ID: ID of the OS.
ID uint64 `json:"id"`
// Name: name of the OS.
Name string `json:"name"`
// Type: type of the OS.
// Default value: unknown_type
Type OSType `json:"type"`
// Version: version of the OS.
Version string `json:"version"`
// Arch: architecture of the OS.
// Default value: unknown_arch
Arch OSArch `json:"arch"`
// AllowCustomPartitioning: true if the OS allow custom partitioning.
AllowCustomPartitioning bool `json:"allow_custom_partitioning"`
// AllowSSHKeys: true if the OS allow SSH Keys.
AllowSSHKeys bool `json:"allow_ssh_keys"`
// RequiresUser: true if the OS requires user.
RequiresUser bool `json:"requires_user"`
// RequiresAdminPassword: true if the OS requires admin password.
RequiresAdminPassword bool `json:"requires_admin_password"`
// RequiresPanelPassword: true if the OS requires panel password.
RequiresPanelPassword bool `json:"requires_panel_password"`
// AllowedFilesystems: true if the OS allow file systems.
AllowedFilesystems []PartitionFileSystem `json:"allowed_filesystems"`
// RequiresLicense: true if the OS requires license.
RequiresLicense bool `json:"requires_license"`
// LicenseOffers: license offers available with the OS.
LicenseOffers []*Offer `json:"license_offers"`
// MaxPartitions: maximum number of partitions which can be created.
MaxPartitions *uint32 `json:"max_partitions"`
// DisplayName: display name of the OS.
DisplayName string `json:"display_name"`
// PasswordRegex: regex used to validate the installation passwords.
PasswordRegex string `json:"password_regex"`
// PanelPasswordRegex: regex used to validate the panel installation password.
PanelPasswordRegex *string `json:"panel_password_regex"`
// RequiresValidHostname: if both requires_valid_hostname & hostname_regex are set, it means that at least one of the criterias must be valid.
RequiresValidHostname *bool `json:"requires_valid_hostname"`
// HostnameRegex: if both requires_valid_hostname & hostname_regex are set, it means that at least one of the criterias must be valid.
HostnameRegex *string `json:"hostname_regex"`
// HostnameMaxLength: hostname max length.
HostnameMaxLength uint32 `json:"hostname_max_length"`
// ReleasedAt: oS release date.
ReleasedAt *time.Time `json:"released_at"`
}
// ServerLocation: server location.
type ServerLocation struct {
Rack string `json:"rack"`
Room string `json:"room"`
DatacenterName string `json:"datacenter_name"`
}
// ServerOption: server option.
type ServerOption struct {
Offer *Offer `json:"offer"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
ExpiredAt *time.Time `json:"expired_at"`
Options []*ServerOption `json:"options"`
}
// ServiceLevel: service level.
type ServiceLevel struct {
// OfferID: offer ID of service level.
OfferID uint32 `json:"offer_id"`
// Level: level type of service level.
// Default value: unknown
Level ServiceLevelLevel `json:"level"`
}
// RpnSan: rpn san.
type RpnSan struct {
// ID: rPN SAN ID.
ID uint64 `json:"id"`
// DatacenterName: datacenter location.
DatacenterName string `json:"datacenter_name"`
// OrganizationID: organization ID.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// ServerHostname: rPN SAN server hostname.
ServerHostname string `json:"server_hostname"`
// IqnSuffix: iQN suffix.
IqnSuffix string `json:"iqn_suffix"`
// CreatedAt: date of creation of the RPN SAN.
CreatedAt *time.Time `json:"created_at"`
// OfferID: offer ID.
OfferID uint64 `json:"offer_id"`
// OfferName: offer description.
OfferName string `json:"offer_name"`
// Status: status.
// Default value: unknown_status
Status RpnSanStatus `json:"status"`
// StorageSize: rPN SAN storage size.
StorageSize scw.Size `json:"storage_size"`
Iqn string `json:"iqn"`
Offer *Offer `json:"offer"`
// Rpnv1Compatible: true if the SAN is compatible with the RPNv1 technology.
Rpnv1Compatible bool `json:"rpnv1_compatible"`
// Rpnv1Implicit: true if the offer supports the RPNv1 implicitly, false if it must to be added to a group to support RPNv1.
Rpnv1Implicit bool `json:"rpnv1_implicit"`
// DeliveredAt: rPN SAN delivery date.
DeliveredAt *time.Time `json:"delivered_at"`
// TerminatedAt: rPN SAN termination date.
TerminatedAt *time.Time `json:"terminated_at"`
// ExpiresAt: rPN SAN expiration date.
ExpiresAt *time.Time `json:"expires_at"`
}
// RpnGroup: rpn group.
type RpnGroup struct {
// ID: rpn group member ID.
ID uint64 `json:"id"`
// Name: rpn group name.
Name string `json:"name"`
// Type: rpn group type (local or shared).
// Default value: unknown
Type RpnGroupType `json:"type"`
// Active: whether the group is active or not.
Active bool `json:"active"`
// CreatedAt: rpn group creation date.
CreatedAt *time.Time `json:"created_at"`
// Owner: rPN group owner.
Owner string `json:"owner"`
// MembersCount: total number of members.
MembersCount uint32 `json:"members_count"`
// OrganizationID: rpn group organization ID.
OrganizationID string `json:"organization_id"`
// ProjectID: rpn group project ID.
ProjectID string `json:"project_id"`
}
// RpnV2GroupSubnet: rpn v2 group subnet.
type RpnV2GroupSubnet struct {
Address net.IP `json:"address"`
Cidr uint32 `json:"cidr"`
}
// Server: server.
type Server struct {
// ID: ID of the server.
ID uint64 `json:"id"`
// OrganizationID: organization ID the server is attached to.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the server is attached to.
ProjectID string `json:"project_id"`
// Hostname: hostname of the server.
Hostname string `json:"hostname"`
// RebootedAt: date of last reboot of the server.
RebootedAt *time.Time `json:"rebooted_at"`
// CreatedAt: date of creation of the server.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date of last modification of the server.
UpdatedAt *time.Time `json:"updated_at"`
// ExpiredAt: date of release of the server.
ExpiredAt *time.Time `json:"expired_at"`
// Offer: offer of the server.
Offer *Offer `json:"offer"`
// Status: status of the server.
// Default value: unknown
Status ServerStatus `json:"status"`
// Location: location of the server.
Location *ServerLocation `json:"location"`
// AbuseContact: abuse contact of the server.
AbuseContact string `json:"abuse_contact"`
// Os: oS installed on the server.
Os *OS `json:"os"`
// Interfaces: network interfaces of the server.
Interfaces []*NetworkInterface `json:"interfaces"`
// Zone: the zone in which is the server.
Zone scw.Zone `json:"zone"`
// Options: options subscribe on the server.
Options []*ServerOption `json:"options"`
// Level: service level of the server.
Level *ServiceLevel `json:"level"`
// HasBmc: boolean if the server has a BMC.
HasBmc bool `json:"has_bmc"`
// RescueOs: rescue OS of the server.
RescueOs *OS `json:"rescue_os"`
// Tags: array of customs tags attached to the server.
Tags []string `json:"tags"`
// IsOutsourced: whether the server is outsourced or not.
IsOutsourced bool `json:"is_outsourced"`
// IPv6Slaac: whether or not you can enable/disable the IPv6.
IPv6Slaac bool `json:"ipv6_slaac"`
// Qinq: whether the server is compatible with QinQ.
Qinq bool `json:"qinq"`
// IsRpnv2Member: whether or not the server is already part of an rpnv2 group.
IsRpnv2Member bool `json:"is_rpnv2_member"`
}
// FailoverBlock: failover block.
type FailoverBlock struct {
// ID: ID of the failover block.
ID uint64 `json:"id"`
// Address: IP of the failover block.
Address net.IP `json:"address"`
// Nameservers: name servers.
Nameservers []string `json:"nameservers"`
// IPVersion: IP version of the failover block.
// Default value: unknown_version
IPVersion FailoverBlockVersion `json:"ip_version"`
// Cidr: classless InterDomain Routing notation of the failover block.
Cidr uint32 `json:"cidr"`
// Netmask: netmask of the failover block.
Netmask net.IP `json:"netmask"`
// GatewayIP: gateway IP of the failover block.
GatewayIP net.IP `json:"gateway_ip"`
}
// RpnSanIPRpnV2Group: rpn san ip rpn v2 group.
type RpnSanIPRpnV2Group struct {
ID uint64 `json:"id"`
Name string `json:"name"`
}
// RpnSanIPServer: rpn san ip server.
type RpnSanIPServer struct {
ID uint64 `json:"id"`
Hostname string `json:"hostname"`
DatacenterName string `json:"datacenter_name"`
}
// RpnSanServer: rpn san server.
type RpnSanServer struct {
// ID: the RPN SAN server ID.
ID uint64 `json:"id"`
// DatacenterName: the RPN SAN server datacenter name.
DatacenterName string `json:"datacenter_name"`
// Hostname: the RPN SAN server hostname.
Hostname string `json:"hostname"`
// Sans: rPN SANs linked to the RPN SAN server.
Sans []*RpnSan `json:"sans"`
// Zone: the RPN SAN server zone.
Zone scw.Zone `json:"zone"`
}
// RpnV2Group: rpn v2 group.
type RpnV2Group struct {
// ID: rPN V2 group ID.
ID uint64 `json:"id"`
// Name: rPN V2 group name.
Name string `json:"name"`
// CompatibleRpnv1: whether or not the RPN V1 compatibility was enabled.
CompatibleRpnv1 bool `json:"compatible_rpnv1"`
// OrganizationID: organization ID of the RPN V2 group.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID of the RPN V2 group.
ProjectID string `json:"project_id"`
// Type: rPN V2 group type (qing / standard).
// Default value: unknown_type
Type RpnV2GroupType `json:"type"`
// Status: rPN V2 group status.
// Default value: unknown_group_status
Status RpnV2GroupStatus `json:"status"`
// Owner: rPN V2 group owner.
Owner string `json:"owner"`
// MembersCount: total number of members.
MembersCount uint32 `json:"members_count"`
// Subnet: rPN V2 subnet.
Subnet *RpnV2GroupSubnet `json:"subnet"`
// Gateway: rPN V2 gateway.
Gateway net.IP `json:"gateway"`
// Rpnv1Group: the RPNv1 group (if the compatibility was enabled).
Rpnv1Group *RpnGroup `json:"rpnv1_group"`
}
// RpnV2Member: rpn v2 member.
type RpnV2Member struct {
// ID: rPN V2 member ID.
ID uint64 `json:"id"`
// Status: rPN V2 member status.
// Default value: unknown_member_status
Status RpnV2MemberStatus `json:"status"`
// Vlan: rPN V2 member VLAN.
Vlan string `json:"vlan"`
// Server: server behind the member (may be empty).
// Precisely one of Server, Rpnv1Group must be set.
Server *Server `json:"server,omitempty"`
// Rpnv1Group: rPN V1 group member.
// Precisely one of Server, Rpnv1Group must be set.
Rpnv1Group *RpnGroup `json:"rpnv1_group,omitempty"`
// Speed: rPN speed.
Speed *uint32 `json:"speed"`
}
// ServerDisk: server disk.
type ServerDisk struct {
ID uint64 `json:"id"`
Connector string `json:"connector"`
// Type: default value: sata
Type ServerDiskType `json:"type"`
Capacity scw.Size `json:"capacity"`
IsAddon bool `json:"is_addon"`
}
// Service: service.
type Service struct {
// ID: ID of the service.
ID uint64 `json:"id"`
// ResourceID: resource ID of the service.
ResourceID *uint64 `json:"resource_id"`
// ProvisioningStatus: provisioning status of the service.
// Default value: unknown
ProvisioningStatus ServiceProvisioningStatus `json:"provisioning_status"`
// Offer: offer of the service.
Offer *Offer `json:"offer"`
// CreatedAt: creation date of the service.
CreatedAt *time.Time `json:"created_at"`
// DeliveredAt: delivery date of the service.
DeliveredAt *time.Time `json:"delivered_at"`
// TerminatedAt: terminatation date of the service.
TerminatedAt *time.Time `json:"terminated_at"`
// ExpiresAt: expiration date of the service.
ExpiresAt *time.Time `json:"expires_at"`
// Type: service type, either order or service.
// Default value: unknown_type
Type ServiceType `json:"type"`
}
// GetIPv6BlockQuotasResponseQuota: get i pv6 block quotas response quota.
type GetIPv6BlockQuotasResponseQuota struct {
Quota uint64 `json:"quota"`
Cidr uint32 `json:"cidr"`
}
// InstallPartition: install partition.
type InstallPartition struct {
// FileSystem: file system of the installation partition.
// Default value: unknown
FileSystem PartitionFileSystem `json:"file_system"`
// MountPoint: mount point of the installation partition.
MountPoint *string `json:"mount_point"`
// RaidLevel: rAID level of the installation partition.
// Default value: no_raid
RaidLevel RaidArrayRaidLevel `json:"raid_level"`
// Capacity: capacity of the installation partition.
Capacity scw.Size `json:"capacity"`
// Connectors: connectors of the installation partition.
Connectors []string `json:"connectors"`
}
// FailoverIP: failover ip.
type FailoverIP struct {
// ID: ID of the failover IP.
ID uint64 `json:"id"`
// Address: IP of the failover IP.
Address net.IP `json:"address"`
// Reverse: reverse IP value.
Reverse string `json:"reverse"`
// IPVersion: IP version of the failover IP.
// Default value: unknown_version
IPVersion FailoverIPVersion `json:"ip_version"`
// Cidr: classless InterDomain Routing notation of the failover IP.
Cidr uint32 `json:"cidr"`
// Netmask: netmask of the failover IP.
Netmask net.IP `json:"netmask"`
// GatewayIP: gateway IP of the failover IP.
GatewayIP net.IP `json:"gateway_ip"`
// Mac: mAC address of the IP failover.
Mac *string `json:"mac"`
// ServerID: server ID linked to the IP failover.
ServerID *uint64 `json:"server_id"`
// Status: status of the IP failover.
// Default value: unknown_status
Status FailoverIPStatus `json:"status"`
// Block: block of the IP failover.
Block *FailoverBlock `json:"block"`
// Type: the interface type.
// Default value: unknown
Type FailoverIPInterfaceType `json:"type"`
// ServerZone: the server zone (if assigned).
ServerZone *string `json:"server_zone"`
}
// RpnSanIP: rpn san ip.
type RpnSanIP struct {
// Server: basic server information behind the IP.
// Precisely one of Server, Rpnv2Group must be set.
Server *RpnSanIPServer `json:"server,omitempty"`
// Rpnv2Group: basic RPNv2 group information behind the IP.
// Precisely one of Server, Rpnv2Group must be set.
Rpnv2Group *RpnSanIPRpnV2Group `json:"rpnv2_group,omitempty"`
// IP: an IP object.
IP *IP `json:"ip"`
// Type: IP type (server | rpnv2_subnet).
// Default value: unknown
Type RpnSanIPType `json:"type"`
}
// ListIPv6BlockSubnetsAvailableResponseSubnet: list i pv6 block subnets available response subnet.
type ListIPv6BlockSubnetsAvailableResponseSubnet struct {
Address net.IP `json:"address"`
Cidr uint32 `json:"cidr"`
}
// InvoiceSummary: invoice summary.
type InvoiceSummary struct {
ID uint64 `json:"id"`
TotalWithTaxes *scw.Money `json:"total_with_taxes"`
TotalWithoutTaxes *scw.Money `json:"total_without_taxes"`
CreatedAt *time.Time `json:"created_at"`
PaidAt *time.Time `json:"paid_at"`
// Status: default value: unknown_invoice_status
Status InvoiceStatus `json:"status"`
// PaymentMethod: default value: unknown_payment_method
PaymentMethod InvoicePaymentMethod `json:"payment_method"`
TransactionID uint64 `json:"transaction_id"`
}
// RefundSummary: refund summary.
type RefundSummary struct {
ID uint64 `json:"id"`
TotalWithTaxes *scw.Money `json:"total_with_taxes"`
TotalWithoutTaxes *scw.Money `json:"total_without_taxes"`
CreatedAt *time.Time `json:"created_at"`
RefundedAt *time.Time `json:"refunded_at"`
// Status: default value: unknown_refund_status
Status RefundStatus `json:"status"`
// Method: default value: unknown_refund_method
Method RefundMethod `json:"method"`
}
// RpnGroupMember: rpn group member.
type RpnGroupMember struct {
// ID: rpn group member ID.
ID uint64 `json:"id"`
// Status: rPN group member status.
// Default value: unknown_rpn_member_status
Status RpnGroupMemberStatus `json:"status"`
// SanServer: authorized RPN SAN server.
SanServer *RpnSanServer `json:"san_server"`
// Server: authorized rpn v1 capable server.
Server *Server `json:"server"`
// GroupID: rPN group ID.
GroupID uint64 `json:"group_id"`
// GroupName: rPN group name.
GroupName string `json:"group_name"`
// GroupOwner: rPN group owner.
GroupOwner string `json:"group_owner"`
// Speed: rPN speed.
Speed *uint32 `json:"speed"`
// Owner: rPN member owner.
Owner string `json:"owner"`
}
// RpnSanSummary: rpn san summary.
type RpnSanSummary struct {
// ID: rPN SAN ID.
ID uint64 `json:"id"`
// DatacenterName: datacenter location.
DatacenterName string `json:"datacenter_name"`
// OrganizationID: organization ID.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// ServerHostname: rPN SAN server hostname.
ServerHostname string `json:"server_hostname"`
// IqnSuffix: iQN suffix.
IqnSuffix string `json:"iqn_suffix"`
// CreatedAt: date of creation of the RPN SAN.
CreatedAt *time.Time `json:"created_at"`
// OfferID: offer ID.
OfferID uint64 `json:"offer_id"`
// OfferName: offer description.
OfferName string `json:"offer_name"`
// Status: status.
// Default value: unknown_status
Status RpnSanStatus `json:"status"`
// StorageSize: rPN SAN storage size.
StorageSize scw.Size `json:"storage_size"`
// Rpnv1Compatible: true if the SAN is compatible with the RPNv1 technology.
Rpnv1Compatible bool `json:"rpnv1_compatible"`
// Rpnv1Implicit: true if the offer supports the RPNv1 implicitly, false if it must to be added to a group to support RPNv1.
Rpnv1Implicit bool `json:"rpnv1_implicit"`
// DeliveredAt: rPN SAN delivery date.
DeliveredAt *time.Time `json:"delivered_at"`
// TerminatedAt: rPN SAN termination date.
TerminatedAt *time.Time `json:"terminated_at"`
// ExpiresAt: rPN SAN expiration date.
ExpiresAt *time.Time `json:"expires_at"`
}
// RpnServerCapability: rpn server capability.
type RpnServerCapability struct {
// ID: server ID.
ID uint64 `json:"id"`
// Hostname: server hostname.
Hostname string `json:"hostname"`
// DatacenterName: server datacenter name.
DatacenterName string `json:"datacenter_name"`
// Zone: server zone.
Zone scw.Zone `json:"zone"`
// IPAddress: private IP address (if rpn compatiblle).
IPAddress *net.IP `json:"ip_address"`
// RpnVersion: supported rpn version.
RpnVersion *uint32 `json:"rpn_version"`
// CompatibleQinq: true if server is compatible with QinQ protocol (rpn v2).
CompatibleQinq bool `json:"compatible_qinq"`
// CanJoinQinqGroup: true if server can join a QinQ group.
CanJoinQinqGroup bool `json:"can_join_qinq_group"`
// Rpnv1GroupCount: times server is linked in a rpnv1 group.
Rpnv1GroupCount uint32 `json:"rpnv1_group_count"`
// Rpnv2GroupCount: times server is linked in a rpnv2 group.
Rpnv2GroupCount uint32 `json:"rpnv2_group_count"`
// CanJoinRpnv2Group: true if server can join an rpnv2 group.
CanJoinRpnv2Group bool `json:"can_join_rpnv2_group"`
}
// Log: log.
type Log struct {
// ID: rPN V2 log ID.
ID uint64 `json:"id"`
// Group: rPN V2 group.
Group *RpnV2Group `json:"group"`
// Member: rPN V2 member (if appliable).
Member *RpnV2Member `json:"member"`
// Action: which action was performed.
// Default value: unknown_log_action
Action LogAction `json:"action"`
// Status: action status.
// Default value: unknown_log_status
Status LogStatus `json:"status"`
// CreatedAt: creation date.
CreatedAt *time.Time `json:"created_at"`
// FinishedAt: completion date.
FinishedAt *time.Time `json:"finished_at"`
}
// ServerEvent: server event.
type ServerEvent struct {
// EventID: ID of the event.
EventID uint64 `json:"event_id"`
// Description: description of the event.
Description string `json:"description"`
// Date: date of the event.
Date *time.Time `json:"date"`
}
// ServerSummary: server summary.
type ServerSummary struct {
// ID: ID of the server.
ID uint64 `json:"id"`
// DatacenterName: datacenter of the server.
DatacenterName string `json:"datacenter_name"`
// OrganizationID: organization ID the server is attached to.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the server is attached to.
ProjectID string `json:"project_id"`
// Hostname: hostname of the server.
Hostname string `json:"hostname"`
// CreatedAt: date of creation of the server.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date of last modification of the server.
UpdatedAt *time.Time `json:"updated_at"`
// ExpiredAt: date of release of the server.
ExpiredAt *time.Time `json:"expired_at"`
// OfferID: offer ID of the server.
OfferID uint64 `json:"offer_id"`
// OfferName: offer name of the server.
OfferName string `json:"offer_name"`
// Status: status of the server.
// Default value: unknown
Status ServerStatus `json:"status"`
// OsID: oS ID installed on server.
OsID *uint64 `json:"os_id"`
// Interfaces: network interfaces of the server.
Interfaces []*NetworkInterface `json:"interfaces"`
// Zone: the zone in which is the server.
Zone scw.Zone `json:"zone"`
// Level: service level of the server.
Level *ServiceLevel `json:"level"`
// IsOutsourced: whether the server is outsourced or not.
IsOutsourced bool `json:"is_outsourced"`
// Qinq: whether the server is compatible with QinQ.
Qinq bool `json:"qinq"`
// RpnVersion: supported RPN version.
RpnVersion *uint32 `json:"rpn_version"`
}
// CPU: cpu.
type CPU struct {
// Name: name of CPU.
Name string `json:"name"`
// CoreCount: number of cores of the CPU.
CoreCount uint32 `json:"core_count"`
// ThreadCount: number of threads of the CPU.
ThreadCount uint32 `json:"thread_count"`
// Frequency: frequency of the CPU.
Frequency uint32 `json:"frequency"`
}
// Disk: disk.
type Disk struct {
// Capacity: capacity of the disk.
Capacity scw.Size `json:"capacity"`
// Type: type of the disk.
// Default value: sata
Type ServerDiskType `json:"type"`
}
// Memory: memory.
type Memory struct {
// Capacity: capacity of the memory.
Capacity scw.Size `json:"capacity"`
// Type: type of the memory.
// Default value: ddr2
Type MemoryType `json:"type"`
// Frequency: frequency of the memory.
Frequency uint32 `json:"frequency"`
// IsEcc: true if the memory is an error-correcting code memory.
IsEcc bool `json:"is_ecc"`
}
// PersistentMemory: persistent memory.
type PersistentMemory struct {
// Capacity: capacity of the persistent memory.
Capacity scw.Size `json:"capacity"`
// Frequency: frequency of the persistent memory.
Frequency uint32 `json:"frequency"`
// Model: model of the persistent memory.
Model string `json:"model"`
}
// RaidController: raid controller.
type RaidController struct {
// Model: model of the RAID controller.
Model string `json:"model"`
// RaidLevel: rAID level of the RAID controller.
RaidLevel []string `json:"raid_level"`
}
// RaidArray: raid array.
type RaidArray struct {
// RaidLevel: the RAID level.
// Default value: no_raid
RaidLevel RaidArrayRaidLevel `json:"raid_level"`
// Disks: disks on the RAID controller.
Disks []*ServerDisk `json:"disks"`
}
// Partition: partition.
type Partition struct {
// Type: type of the partition.
// Default value: primary
Type PartitionType `json:"type"`
// FileSystem: file system of the partition.
// Default value: unknown
FileSystem PartitionFileSystem `json:"file_system"`
// MountPoint: mount point of the partition.
MountPoint *string `json:"mount_point"`
// RaidLevel: raid level of the partition.
// Default value: no_raid
RaidLevel RaidArrayRaidLevel `json:"raid_level"`
// Capacity: capacity of the partition.
Capacity scw.Size `json:"capacity"`
// Connectors: connectors of the partition.
Connectors []string `json:"connectors"`
}
// UpdatableRaidArray: updatable raid array.
type UpdatableRaidArray struct {
// RaidLevel: the RAID level.
// Default value: no_raid
RaidLevel RaidArrayRaidLevel `json:"raid_level"`
// DiskIDs: the list of Disk ID of the updatable RAID.
DiskIDs []uint64 `json:"disk_ids"`
}
// AttachFailoverIPToMacAddressRequest: attach failover ip to mac address request.
type AttachFailoverIPToMacAddressRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the failover IP.
IPID uint64 `json:"-"`
// Type: a mac type.
// Default value: mac_type_unknown
Type AttachFailoverIPToMacAddressRequestMacType `json:"type"`
// Mac: a valid mac address (existing or not).
Mac *string `json:"mac,omitempty"`
}
// AttachFailoverIPsRequest: attach failover i ps request.
type AttachFailoverIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"server_id"`
// FipsIDs: list of ID of failovers IP to attach.
FipsIDs []uint64 `json:"fips_ids"`
}
// BMCAccess: bmc access.
type BMCAccess struct {
// URL: URL to access to the server console.
URL string `json:"url"`
// Login: the login to use for the BMC (Baseboard Management Controller) access authentification.
Login string `json:"login"`
// Password: the password to use for the BMC (Baseboard Management Controller) access authentification.
Password string `json:"password"`
// ExpiresAt: the date after which the BMC (Baseboard Management Controller) access will be closed.
ExpiresAt *time.Time `json:"expires_at"`
// Status: status of the connection.
// Default value: unknown
Status BMCAccessStatus `json:"status"`
}
// Backup: backup.
type Backup struct {
// ID: ID of the backup.
ID uint64 `json:"id"`
// Login: login of the backup.
Login string `json:"login"`
// Server: server of the backup.
Server string `json:"server"`
// Status: status of the backup.
// Default value: unknown_backup_status
Status BackupStatus `json:"status"`
// ACLEnabled: ACL enable boolean of the backup.
ACLEnabled bool `json:"acl_enabled"`
// Autologin: autologin boolean of the backup.
Autologin bool `json:"autologin"`
// QuotaSpace: total quota space of the backup.
QuotaSpace uint64 `json:"quota_space"`
// QuotaSpaceUsed: quota space used of the backup.
QuotaSpaceUsed uint64 `json:"quota_space_used"`
// QuotaFiles: total quota files of the backup.
QuotaFiles uint64 `json:"quota_files"`
// QuotaFilesUsed: quota files used of the backup.
QuotaFilesUsed uint64 `json:"quota_files_used"`
}
// BillingAPICanOrderRequest: billing api can order request.
type BillingAPICanOrderRequest struct {
ProjectID string `json:"-"`
}
// BillingAPIDownloadInvoiceRequest: billing api download invoice request.
type BillingAPIDownloadInvoiceRequest struct {
InvoiceID uint64 `json:"-"`
}
// BillingAPIDownloadRefundRequest: billing api download refund request.
type BillingAPIDownloadRefundRequest struct {
RefundID uint64 `json:"-"`
}
// BillingAPIGetInvoiceRequest: billing api get invoice request.
type BillingAPIGetInvoiceRequest struct {
InvoiceID uint64 `json:"-"`
}
// BillingAPIGetRefundRequest: billing api get refund request.
type BillingAPIGetRefundRequest struct {
RefundID uint64 `json:"-"`
}
// BillingAPIListInvoicesRequest: billing api list invoices request.
type BillingAPIListInvoicesRequest struct {
Page *uint32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListInvoicesRequestOrderBy `json:"-"`
ProjectID *string `json:"-"`
}
// BillingAPIListRefundsRequest: billing api list refunds request.
type BillingAPIListRefundsRequest struct {
Page *uint32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListRefundsRequestOrderBy `json:"-"`
ProjectID *string `json:"-"`
}
// CanOrderResponse: can order response.
type CanOrderResponse struct {
CanOrder bool `json:"can_order"`
Message *string `json:"message"`
QuotaOk bool `json:"quota_ok"`
PhoneConfirmed bool `json:"phone_confirmed"`
EmailConfirmed bool `json:"email_confirmed"`
UserConfirmed bool `json:"user_confirmed"`
PaymentMode bool `json:"payment_mode"`
BillingOk bool `json:"billing_ok"`
}
// CancelServerInstallRequest: cancel server install request.
type CancelServerInstallRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the server to cancel install.
ServerID uint64 `json:"-"`
}
// CreateFailoverIPsRequest: create failover i ps request.
type CreateFailoverIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: failover IP offer ID.
OfferID uint64 `json:"offer_id"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// Quantity: quantity.
Quantity uint32 `json:"quantity"`
}
// CreateFailoverIPsResponse: create failover i ps response.
type CreateFailoverIPsResponse struct {
TotalCount uint32 `json:"total_count"`
Services []*Service `json:"services"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *CreateFailoverIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *CreateFailoverIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*CreateFailoverIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Services = append(r.Services, results.Services...)
r.TotalCount += uint32(len(results.Services))
return uint32(len(results.Services)), nil
}
// CreateServerRequest: create server request.
type CreateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: offer ID of the new server.
OfferID uint64 `json:"offer_id"`
// ServerOptionIDs: server option IDs of the new server.
ServerOptionIDs []uint64 `json:"server_option_ids"`
// ProjectID: project ID of the new server.
ProjectID string `json:"project_id"`
// DatacenterName: datacenter name of the new server.
DatacenterName *string `json:"datacenter_name,omitempty"`
}
// DeleteFailoverIPRequest: delete failover ip request.
type DeleteFailoverIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the failover IP to delete.
IPID uint64 `json:"-"`
}
// DeleteServerRequest: delete server request.
type DeleteServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to delete.
ServerID uint64 `json:"-"`
}
// DeleteServiceRequest: delete service request.
type DeleteServiceRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServiceID: ID of the service.
ServiceID uint64 `json:"-"`
}
// DetachFailoverIPFromMacAddressRequest: detach failover ip from mac address request.
type DetachFailoverIPFromMacAddressRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the failover IP.
IPID uint64 `json:"-"`
}
// DetachFailoverIPsRequest: detach failover i ps request.
type DetachFailoverIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipsIDs: list of IDs of failovers IP to detach.
FipsIDs []uint64 `json:"fips_ids"`
}
// GetBMCAccessRequest: get bmc access request.
type GetBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to get BMC access.
ServerID uint64 `json:"-"`
}
// GetFailoverIPRequest: get failover ip request.
type GetFailoverIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the failover IP.
IPID uint64 `json:"-"`
}
// GetIPv6BlockQuotasResponse: get i pv6 block quotas response.
type GetIPv6BlockQuotasResponse struct {
// Quotas: quota for each CIDR of IPv6 block.
Quotas []*GetIPv6BlockQuotasResponseQuota `json:"quotas"`
// TotalCount: total count of quotas.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *GetIPv6BlockQuotasResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *GetIPv6BlockQuotasResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*GetIPv6BlockQuotasResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Quotas = append(r.Quotas, results.Quotas...)
r.TotalCount += uint32(len(results.Quotas))
return uint32(len(results.Quotas)), nil
}
// GetOSRequest: get os request.
type GetOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OsID: ID of the OS.
OsID uint64 `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"-"`
}
// GetOfferRequest: get offer request.
type GetOfferRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OfferID: ID of offer.
OfferID uint64 `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"project_id,omitempty"`
}
// GetOrderedServiceRequest: get ordered service request.
type GetOrderedServiceRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
OrderedServiceID uint64 `json:"-"`
}
// GetRaidRequest: get raid request.
type GetRaidRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"-"`
}
// GetRemainingQuotaRequest: get remaining quota request.
type GetRemainingQuotaRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"project_id,omitempty"`
}
// GetRemainingQuotaResponse: get remaining quota response.
type GetRemainingQuotaResponse struct {
// FailoverIPQuota: current failover IP quota.
FailoverIPQuota uint32 `json:"failover_ip_quota"`
// FailoverIPRemainingQuota: remaining failover IP quota.
FailoverIPRemainingQuota uint32 `json:"failover_ip_remaining_quota"`
// FailoverBlockQuota: current failover block quota.
FailoverBlockQuota uint32 `json:"failover_block_quota"`
// FailoverBlockRemainingQuota: remaining failover block quota.
FailoverBlockRemainingQuota uint32 `json:"failover_block_remaining_quota"`
}
// GetRescueRequest: get rescue request.
type GetRescueRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to get rescue.
ServerID uint64 `json:"-"`
}
// GetRpnStatusResponse: get rpn status response.
type GetRpnStatusResponse struct {
// Status: if status = 'operational', you can perform rpn actions in write.
// Default value: unknown_status
Status GetRpnStatusResponseStatus `json:"status"`
// OperationsLeft: number of operations left to perform before being operational.
OperationsLeft *uint32 `json:"operations_left"`
}
// GetServerBackupRequest: get server backup request.
type GetServerBackupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the backup.
ServerID uint64 `json:"-"`
}
// GetServerDefaultPartitioningRequest: get server default partitioning request.
type GetServerDefaultPartitioningRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"-"`
// OsID: oS ID of the default partitioning.
OsID uint64 `json:"-"`
}
// GetServerInstallRequest: get server install request.
type GetServerInstallRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the server to install.
ServerID uint64 `json:"-"`
}
// GetServerRequest: get server request.
type GetServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"-"`
}
// GetServiceRequest: get service request.
type GetServiceRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServiceID: ID of the service.
ServiceID uint64 `json:"-"`
}
// IPv6Block: i pv6 block.
type IPv6Block struct {
// ID: ID of the IPv6.
ID uint64 `json:"id"`
// Address: address of the IPv6.
Address net.IP `json:"address"`
// Duid: dUID of the IPv6.
Duid string `json:"duid"`
// Nameservers: DNS linked to the IPv6.
Nameservers []string `json:"nameservers"`
// Cidr: classless InterDomain Routing notation of the IPv6.
Cidr uint32 `json:"cidr"`
// Subnets: all IPv6 subnets.
Subnets []*IPv6Block `json:"subnets"`
// DelegationStatus: the nameservers delegation status.
// Default value: unknown_status
DelegationStatus IPv6BlockDelegationStatus `json:"delegation_status"`
}
// IPv6BlockAPICreateIPv6BlockRequest: i pv6 block api create i pv6 block request.
type IPv6BlockAPICreateIPv6BlockRequest struct {
// ProjectID: ID of the project.
ProjectID *string `json:"project_id,omitempty"`
}
// IPv6BlockAPICreateIPv6BlockSubnetRequest: i pv6 block api create i pv6 block subnet request.
type IPv6BlockAPICreateIPv6BlockSubnetRequest struct {
// BlockID: ID of the IPv6 block.
BlockID uint64 `json:"-"`
// Address: address of the IPv6.
Address net.IP `json:"address"`
// Cidr: classless InterDomain Routing notation of the IPv6.
Cidr uint32 `json:"cidr"`
}
// IPv6BlockAPIDeleteIPv6BlockRequest: i pv6 block api delete i pv6 block request.
type IPv6BlockAPIDeleteIPv6BlockRequest struct {
// BlockID: ID of the IPv6 block to delete.
BlockID uint64 `json:"-"`
}
// IPv6BlockAPIGetIPv6BlockQuotasRequest: i pv6 block api get i pv6 block quotas request.
type IPv6BlockAPIGetIPv6BlockQuotasRequest struct {
// ProjectID: ID of the project.
ProjectID *string `json:"-"`
}
// IPv6BlockAPIGetIPv6BlockRequest: i pv6 block api get i pv6 block request.
type IPv6BlockAPIGetIPv6BlockRequest struct {
// ProjectID: ID of the project.
ProjectID *string `json:"-"`
}
// IPv6BlockAPIListIPv6BlockSubnetsAvailableRequest: i pv6 block api list i pv6 block subnets available request.
type IPv6BlockAPIListIPv6BlockSubnetsAvailableRequest struct {
// BlockID: ID of the IPv6 block.
BlockID uint64 `json:"-"`
}
// IPv6BlockAPIUpdateIPv6BlockRequest: i pv6 block api update i pv6 block request.
type IPv6BlockAPIUpdateIPv6BlockRequest struct {
// BlockID: ID of the IPv6 block.
BlockID uint64 `json:"-"`
// Nameservers: DNS to link to the IPv6.
Nameservers *[]string `json:"nameservers,omitempty"`
}
// InstallServerRequest: install server request.
type InstallServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to install.
ServerID uint64 `json:"-"`
// OsID: oS ID to install on the server.
OsID uint64 `json:"os_id"`
// Hostname: hostname of the server.
Hostname string `json:"hostname"`
// UserLogin: user to install on the server.
UserLogin *string `json:"user_login,omitempty"`
// UserPassword: user password to install on the server.
UserPassword *string `json:"user_password,omitempty"`
// PanelPassword: panel password to install on the server.
PanelPassword *string `json:"panel_password,omitempty"`
// RootPassword: root password to install on the server.
RootPassword *string `json:"root_password,omitempty"`
// Partitions: partitions to install on the server.
Partitions []*InstallPartition `json:"partitions"`
// SSHKeyIDs: SSH key IDs authorized on the server.
SSHKeyIDs []string `json:"ssh_key_ids"`
// LicenseOfferID: offer ID of license to install on server.
LicenseOfferID *uint64 `json:"license_offer_id,omitempty"`
// IPID: IP to link at the license to install on server.
IPID *uint64 `json:"ip_id,omitempty"`
}
// Invoice: invoice.
type Invoice struct {
ID uint64 `json:"id"`
TotalWithTaxes *scw.Money `json:"total_with_taxes"`
TotalWithoutTaxes *scw.Money `json:"total_without_taxes"`
CreatedAt *time.Time `json:"created_at"`
PaidAt *time.Time `json:"paid_at"`
// Status: default value: unknown_invoice_status
Status InvoiceStatus `json:"status"`
// PaymentMethod: default value: unknown_payment_method
PaymentMethod InvoicePaymentMethod `json:"payment_method"`
Content string `json:"content"`
TransactionID uint64 `json:"transaction_id"`
}
// ListFailoverIPsRequest: list failover i ps request.
type ListFailoverIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of failovers IP per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the failovers IP.
// Default value: ip_asc
OrderBy ListFailoverIPsRequestOrderBy `json:"-"`
// ProjectID: filter failovers IP by project ID.
ProjectID *string `json:"-"`
// Search: filter failovers IP which matching with this field.
Search *string `json:"-"`
// OnlyAvailable: true: return all failovers IP not attached on server
// false: return all failovers IP attached on server.
OnlyAvailable *bool `json:"-"`
}
// ListFailoverIPsResponse: list failover i ps response.
type ListFailoverIPsResponse struct {
// TotalCount: total count of matching failovers IP.
TotalCount uint32 `json:"total_count"`
// FailoverIPs: list of failover IPs that match filters.
FailoverIPs []*FailoverIP `json:"failover_ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFailoverIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFailoverIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListFailoverIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.FailoverIPs = append(r.FailoverIPs, results.FailoverIPs...)
r.TotalCount += uint32(len(results.FailoverIPs))
return uint32(len(results.FailoverIPs)), nil
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
// TotalCount: total count of authorized IPs.
TotalCount uint32 `json:"total_count"`
// IPs: list of authorized IPs.
IPs []*RpnSanIP `json:"ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint32(len(results.IPs))
return uint32(len(results.IPs)), nil
}
// ListIPv6BlockSubnetsAvailableResponse: list i pv6 block subnets available response.
type ListIPv6BlockSubnetsAvailableResponse struct {
// SubnetAvailables: all available address and CIDR available in subnet.
SubnetAvailables []*ListIPv6BlockSubnetsAvailableResponseSubnet `json:"subnet_availables"`
// TotalCount: total count of available subnets.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPv6BlockSubnetsAvailableResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPv6BlockSubnetsAvailableResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListIPv6BlockSubnetsAvailableResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SubnetAvailables = append(r.SubnetAvailables, results.SubnetAvailables...)
r.TotalCount += uint32(len(results.SubnetAvailables))
return uint32(len(results.SubnetAvailables)), nil
}
// ListInvoicesResponse: list invoices response.
type ListInvoicesResponse struct {
TotalCount uint32 `json:"total_count"`
Invoices []*InvoiceSummary `json:"invoices"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInvoicesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInvoicesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListInvoicesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Invoices = append(r.Invoices, results.Invoices...)
r.TotalCount += uint32(len(results.Invoices))
return uint32(len(results.Invoices)), nil
}
// ListOSRequest: list os request.
type ListOSRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of OS per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the OS.
// Default value: created_at_asc
OrderBy ListOSRequestOrderBy `json:"-"`
// Type: type of the OS.
// Default value: unknown_type
Type OSType `json:"-"`
// ServerID: filter OS by compatible server ID.
ServerID uint64 `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"-"`
}
// ListOSResponse: list os response.
type ListOSResponse struct {
// TotalCount: total count of matching OS.
TotalCount uint32 `json:"total_count"`
// Os: oS that match filters.
Os []*OS `json:"os"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOSResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOSResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Os = append(r.Os, results.Os...)
r.TotalCount += uint32(len(results.Os))
return uint32(len(results.Os)), nil
}
// ListOffersRequest: list offers request.
type ListOffersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of offer per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the offers.
// Default value: created_at_asc
OrderBy ListOffersRequestOrderBy `json:"-"`
// CommercialRange: filter on commercial range.
CommercialRange *string `json:"-"`
// Catalog: filter on catalog.
// Default value: all
Catalog OfferCatalog `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"-"`
// IsFailoverIP: get the current failover IP offer.
IsFailoverIP *bool `json:"-"`
// IsFailoverBlock: get the current failover IP block offer.
IsFailoverBlock *bool `json:"-"`
// SoldIn: filter offers depending on their datacenter.
SoldIn []string `json:"-"`
// AvailableOnly: set this filter to true to only return available offers.
AvailableOnly *bool `json:"-"`
// IsRpnSan: get the RPN SAN offers.
IsRpnSan *bool `json:"-"`
}
// ListOffersResponse: list offers response.
type ListOffersResponse struct {
// TotalCount: total count of matching offers.
TotalCount uint32 `json:"total_count"`
// Offers: offers that match filters.
Offers []*Offer `json:"offers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListOffersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Offers = append(r.Offers, results.Offers...)
r.TotalCount += uint32(len(results.Offers))
return uint32(len(results.Offers)), nil
}
// ListRefundsResponse: list refunds response.
type ListRefundsResponse struct {
TotalCount uint32 `json:"total_count"`
Refunds []*RefundSummary `json:"refunds"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRefundsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRefundsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRefundsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Refunds = append(r.Refunds, results.Refunds...)
r.TotalCount += uint32(len(results.Refunds))
return uint32(len(results.Refunds)), nil
}
// ListRpnCapableSanServersResponse: list rpn capable san servers response.
type ListRpnCapableSanServersResponse struct {
// TotalCount: total count of rpn capable san servers.
TotalCount uint32 `json:"total_count"`
// SanServers: list of san servers.
SanServers []*RpnSanServer `json:"san_servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnCapableSanServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnCapableSanServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnCapableSanServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SanServers = append(r.SanServers, results.SanServers...)
r.TotalCount += uint32(len(results.SanServers))
return uint32(len(results.SanServers)), nil
}
// ListRpnCapableServersResponse: list rpn capable servers response.
type ListRpnCapableServersResponse struct {
// TotalCount: total count of rpn capable servers.
TotalCount uint32 `json:"total_count"`
// Servers: list of servers.
Servers []*Server `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnCapableServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnCapableServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnCapableServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListRpnGroupMembersResponse: list rpn group members response.
type ListRpnGroupMembersResponse struct {
// TotalCount: total count of rpn v1 group members.
TotalCount uint32 `json:"total_count"`
// Members: list of rpn v1 group members.
Members []*RpnGroupMember `json:"members"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnGroupMembersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnGroupMembersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnGroupMembersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Members = append(r.Members, results.Members...)
r.TotalCount += uint32(len(results.Members))
return uint32(len(results.Members)), nil
}
// ListRpnGroupsResponse: list rpn groups response.
type ListRpnGroupsResponse struct {
// TotalCount: total count of rpn groups.
TotalCount uint32 `json:"total_count"`
// RpnGroups: list of rpn v1 groups.
RpnGroups []*RpnGroup `json:"rpn_groups"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnGroupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnGroupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.RpnGroups = append(r.RpnGroups, results.RpnGroups...)
r.TotalCount += uint32(len(results.RpnGroups))
return uint32(len(results.RpnGroups)), nil
}
// ListRpnInvitesResponse: list rpn invites response.
type ListRpnInvitesResponse struct {
// TotalCount: total count of invites.
TotalCount uint32 `json:"total_count"`
// Members: list of invites.
Members []*RpnGroupMember `json:"members"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnInvitesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnInvitesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnInvitesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Members = append(r.Members, results.Members...)
r.TotalCount += uint32(len(results.Members))
return uint32(len(results.Members)), nil
}
// ListRpnSansResponse: list rpn sans response.
type ListRpnSansResponse struct {
// TotalCount: total count of matching RPN SANs.
TotalCount uint32 `json:"total_count"`
// RpnSans: list of RPN SANs that match filters.
RpnSans []*RpnSanSummary `json:"rpn_sans"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnSansResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnSansResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnSansResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.RpnSans = append(r.RpnSans, results.RpnSans...)
r.TotalCount += uint32(len(results.RpnSans))
return uint32(len(results.RpnSans)), nil
}
// ListRpnServerCapabilitiesResponse: list rpn server capabilities response.
type ListRpnServerCapabilitiesResponse struct {
// TotalCount: total count of servers.
TotalCount uint32 `json:"total_count"`
// Servers: list of servers and their RPN capabilities.
Servers []*RpnServerCapability `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnServerCapabilitiesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnServerCapabilitiesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnServerCapabilitiesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListRpnV2CapableResourcesResponse: list rpn v2 capable resources response.
type ListRpnV2CapableResourcesResponse struct {
// TotalCount: total count of matching rpn v2 capable resources.
TotalCount uint32 `json:"total_count"`
// Servers: list of rpn v2 capable resources that match filters.
Servers []*Server `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnV2CapableResourcesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnV2CapableResourcesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnV2CapableResourcesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListRpnV2GroupLogsResponse: list rpn v2 group logs response.
type ListRpnV2GroupLogsResponse struct {
// TotalCount: total count of matching rpn v2 logs.
TotalCount uint32 `json:"total_count"`
// Logs: list of rpn v2 logs that match filters.
Logs []*Log `json:"logs"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnV2GroupLogsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnV2GroupLogsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnV2GroupLogsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Logs = append(r.Logs, results.Logs...)
r.TotalCount += uint32(len(results.Logs))
return uint32(len(results.Logs)), nil
}
// ListRpnV2GroupsResponse: list rpn v2 groups response.
type ListRpnV2GroupsResponse struct {
// TotalCount: total count of matching rpn v2 groups.
TotalCount uint32 `json:"total_count"`
// RpnGroups: list of rpn v2 groups that match filters.
RpnGroups []*RpnV2Group `json:"rpn_groups"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnV2GroupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnV2GroupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnV2GroupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.RpnGroups = append(r.RpnGroups, results.RpnGroups...)
r.TotalCount += uint32(len(results.RpnGroups))
return uint32(len(results.RpnGroups)), nil
}
// ListRpnV2MembersResponse: list rpn v2 members response.
type ListRpnV2MembersResponse struct {
// TotalCount: total count of matching rpn v2 group members.
TotalCount uint32 `json:"total_count"`
// Members: list of rpn v2 group members that match filters.
Members []*RpnV2Member `json:"members"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRpnV2MembersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRpnV2MembersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRpnV2MembersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Members = append(r.Members, results.Members...)
r.TotalCount += uint32(len(results.Members))
return uint32(len(results.Members)), nil
}
// ListServerDisksRequest: list server disks request.
type ListServerDisksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the server disks.
ServerID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of server disk per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the server disks.
// Default value: created_at_asc
OrderBy ListServerDisksRequestOrderBy `json:"-"`
}
// ListServerDisksResponse: list server disks response.
type ListServerDisksResponse struct {
// TotalCount: total count of matching server disks.
TotalCount uint32 `json:"total_count"`
// Disks: server disks that match filters.
Disks []*ServerDisk `json:"disks"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerDisksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerDisksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServerDisksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Disks = append(r.Disks, results.Disks...)
r.TotalCount += uint32(len(results.Disks))
return uint32(len(results.Disks)), nil
}
// ListServerEventsRequest: list server events request.
type ListServerEventsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the server events.
ServerID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of server event per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the server events.
// Default value: created_at_asc
OrderBy ListServerEventsRequestOrderBy `json:"-"`
}
// ListServerEventsResponse: list server events response.
type ListServerEventsResponse struct {
// TotalCount: total count of matching server events.
TotalCount uint32 `json:"total_count"`
// Events: server events that match filters.
Events []*ServerEvent `json:"events"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServerEventsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServerEventsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServerEventsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Events = append(r.Events, results.Events...)
r.TotalCount += uint32(len(results.Events))
return uint32(len(results.Events)), nil
}
// ListServersRequest: list servers request.
type ListServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of server per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the servers.
// Default value: created_at_asc
OrderBy ListServersRequestOrderBy `json:"-"`
// ProjectID: filter servers by project ID.
ProjectID *string `json:"-"`
// Search: filter servers by hostname.
Search *string `json:"-"`
}
// ListServersResponse: list servers response.
type ListServersResponse struct {
// TotalCount: total count of matching servers.
TotalCount uint32 `json:"total_count"`
// Servers: servers that match filters.
Servers []*ServerSummary `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListServicesRequest: list services request.
type ListServicesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of service per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the services.
// Default value: created_at_asc
OrderBy ListServicesRequestOrderBy `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"-"`
}
// ListServicesResponse: list services response.
type ListServicesResponse struct {
// TotalCount: total count of matching services.
TotalCount uint32 `json:"total_count"`
// Services: services that match filters.
Services []*Service `json:"services"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServicesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServicesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServicesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Services = append(r.Services, results.Services...)
r.TotalCount += uint32(len(results.Services))
return uint32(len(results.Services)), nil
}
// ListSubscribableServerOptionsRequest: list subscribable server options request.
type ListSubscribableServerOptionsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the subscribable server options.
ServerID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of subscribable server option per page.
PageSize *uint32 `json:"-"`
}
// ListSubscribableServerOptionsResponse: list subscribable server options response.
type ListSubscribableServerOptionsResponse struct {
// TotalCount: total count of matching subscribable server options.
TotalCount uint32 `json:"total_count"`
// ServerOptions: server options that match filters.
ServerOptions []*Offer `json:"server_options"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSubscribableServerOptionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSubscribableServerOptionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSubscribableServerOptionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ServerOptions = append(r.ServerOptions, results.ServerOptions...)
r.TotalCount += uint32(len(results.ServerOptions))
return uint32(len(results.ServerOptions)), nil
}
// OfferFailoverBlockInfo: offer failover block info.
type OfferFailoverBlockInfo struct {
OnetimeFees *Offer `json:"onetime_fees"`
}
// OfferFailoverIPInfo: offer failover ip info.
type OfferFailoverIPInfo struct {
OnetimeFees *Offer `json:"onetime_fees"`
}
// OfferServerInfo: offer server info.
type OfferServerInfo struct {
Bandwidth uint64 `json:"bandwidth"`
// Stock: default value: empty
Stock OfferServerInfoStock `json:"stock"`
CommercialRange string `json:"commercial_range"`
Disks []*Disk `json:"disks"`
CPUs []*CPU `json:"cpus"`
Memories []*Memory `json:"memories"`
PersistentMemories []*PersistentMemory `json:"persistent_memories"`
RaidControllers []*RaidController `json:"raid_controllers"`
AvailableOptions []*Offer `json:"available_options"`
RpnVersion *uint32 `json:"rpn_version"`
Connectivity uint64 `json:"connectivity"`
OnetimeFees *Offer `json:"onetime_fees"`
StockByDatacenter map[string]OfferServerInfoStock `json:"stock_by_datacenter"`
}
// OfferServiceLevelInfo: offer service level info.
type OfferServiceLevelInfo struct {
SupportTicket bool `json:"support_ticket"`
SupportPhone bool `json:"support_phone"`
SalesSupport bool `json:"sales_support"`
Git string `json:"git"`
SLA float32 `json:"sla"`
PrioritySupport bool `json:"priority_support"`
HighRpnBandwidth bool `json:"high_rpn_bandwidth"`
Customization bool `json:"customization"`
Antidos bool `json:"antidos"`
ExtraFailoverQuota uint32 `json:"extra_failover_quota"`
AvailableOptions []*Offer `json:"available_options"`
}
// Raid: raid.
type Raid struct {
// RaidArrays: details about the RAID controller.
RaidArrays []*RaidArray `json:"raid_arrays"`
}
// RebootServerRequest: reboot server request.
type RebootServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to reboot.
ServerID uint64 `json:"-"`
}
// Refund: refund.
type Refund struct {
ID uint64 `json:"id"`
TotalWithTaxes *scw.Money `json:"total_with_taxes"`
TotalWithoutTaxes *scw.Money `json:"total_without_taxes"`
CreatedAt *time.Time `json:"created_at"`
RefundedAt *time.Time `json:"refunded_at"`
// Status: default value: unknown_refund_status
Status RefundStatus `json:"status"`
// Method: default value: unknown_refund_method
Method RefundMethod `json:"method"`
Content string `json:"content"`
}
// Rescue: rescue.
type Rescue struct {
// OsID: oS ID of the rescue.
OsID uint64 `json:"os_id"`
// Login: login of the rescue.
Login string `json:"login"`
// Password: password of the rescue.
Password string `json:"password"`
// Protocol: protocol of the resuce.
// Default value: vnc
Protocol RescueProtocol `json:"protocol"`
}
// RpnAPIGetRpnStatusRequest: rpn api get rpn status request.
type RpnAPIGetRpnStatusRequest struct {
// ProjectID: a project ID.
ProjectID *string `json:"-"`
// Rpnv1GroupID: an RPN v1 group ID.
Rpnv1GroupID *uint64 `json:"-"`
// Rpnv2GroupID: an RPN v2 group ID.
Rpnv2GroupID *uint64 `json:"-"`
}
// RpnAPIListRpnServerCapabilitiesRequest: rpn api list rpn server capabilities request.
type RpnAPIListRpnServerCapabilitiesRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of servers per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the servers.
// Default value: created_at_asc
OrderBy ListRpnServerCapabilitiesRequestOrderBy `json:"-"`
// ProjectID: filter servers by project ID.
ProjectID *string `json:"-"`
}
// RpnSanAPIAddIPRequest: rpn san api add ip request.
type RpnSanAPIAddIPRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
// IPIDs: an array of IP ID.
IPIDs []uint64 `json:"ip_ids"`
}
// RpnSanAPICreateRpnSanRequest: rpn san api create rpn san request.
type RpnSanAPICreateRpnSanRequest struct {
// OfferID: offer ID.
OfferID uint64 `json:"offer_id"`
// ProjectID: your project ID.
ProjectID string `json:"project_id"`
}
// RpnSanAPIDeleteRpnSanRequest: rpn san api delete rpn san request.
type RpnSanAPIDeleteRpnSanRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
}
// RpnSanAPIGetRpnSanRequest: rpn san api get rpn san request.
type RpnSanAPIGetRpnSanRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
}
// RpnSanAPIListAvailableIPsRequest: rpn san api list available i ps request.
type RpnSanAPIListAvailableIPsRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
// Type: filter by IP type (server | rpnv2_subnet).
// Default value: unknown
Type RpnSanIPType `json:"-"`
}
// RpnSanAPIListIPsRequest: rpn san api list i ps request.
type RpnSanAPIListIPsRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
// Type: filter by IP type (server | rpnv2_subnet).
// Default value: unknown
Type RpnSanIPType `json:"-"`
}
// RpnSanAPIListRpnSansRequest: rpn san api list rpn sans request.
type RpnSanAPIListRpnSansRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of RPN SANs per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the RPN SANs.
// Default value: created_at_asc
OrderBy ListRpnSansRequestOrderBy `json:"-"`
// ProjectID: filter RPN SANs by project ID.
ProjectID *string `json:"-"`
}
// RpnSanAPIRemoveIPRequest: rpn san api remove ip request.
type RpnSanAPIRemoveIPRequest struct {
// RpnSanID: rPN SAN ID.
RpnSanID uint64 `json:"-"`
// IPIDs: an array of IP ID.
IPIDs []uint64 `json:"ip_ids"`
}
// RpnV1ApiAcceptRpnInviteRequest: rpn v1 api accept rpn invite request.
type RpnV1ApiAcceptRpnInviteRequest struct {
// MemberID: the member ID.
MemberID uint64 `json:"-"`
}
// RpnV1ApiAddRpnGroupMembersRequest: rpn v1 api add rpn group members request.
type RpnV1ApiAddRpnGroupMembersRequest struct {
// GroupID: the rpn v1 group ID.
GroupID uint64 `json:"-"`
// ServerIDs: a collection of rpn v1 capable server IDs.
ServerIDs []uint64 `json:"server_ids"`
// SanServerIDs: a collection of rpn v1 capable RPN SAN server IDs.
SanServerIDs []uint64 `json:"san_server_ids"`
}
// RpnV1ApiCreateRpnGroupRequest: rpn v1 api create rpn group request.
type RpnV1ApiCreateRpnGroupRequest struct {
// Name: rpn v1 group name.
Name string `json:"name"`
// ServerIDs: a collection of rpn v1 capable servers.
ServerIDs []uint64 `json:"server_ids"`
// SanServerIDs: a collection of rpn v1 capable rpn sans servers.
SanServerIDs []uint64 `json:"san_server_ids"`
// ProjectID: a project ID.
ProjectID string `json:"project_id"`
}
// RpnV1ApiDeleteRpnGroupMembersRequest: rpn v1 api delete rpn group members request.
type RpnV1ApiDeleteRpnGroupMembersRequest struct {
// GroupID: the rpn v1 group ID.
GroupID uint64 `json:"-"`
// MemberIDs: a collection of rpn v1 group members IDs.
MemberIDs []uint64 `json:"member_ids"`
}
// RpnV1ApiDeleteRpnGroupRequest: rpn v1 api delete rpn group request.
type RpnV1ApiDeleteRpnGroupRequest struct {
// GroupID: rpn v1 group ID.
GroupID uint64 `json:"-"`
}
// RpnV1ApiGetRpnGroupRequest: rpn v1 api get rpn group request.
type RpnV1ApiGetRpnGroupRequest struct {
// GroupID: rpn v1 group ID.
GroupID uint64 `json:"-"`
}
// RpnV1ApiLeaveRpnGroupRequest: rpn v1 api leave rpn group request.
type RpnV1ApiLeaveRpnGroupRequest struct {
// GroupID: the RPN V1 group ID.
GroupID uint64 `json:"-"`
// ProjectID: a project ID.
ProjectID string `json:"project_id"`
// MemberIDs: a collection of rpn v1 group members IDs.
MemberIDs []uint64 `json:"member_ids"`
}
// RpnV1ApiListRpnCapableSanServersRequest: rpn v1 api list rpn capable san servers request.
type RpnV1ApiListRpnCapableSanServersRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn capable resources per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn capable resources.
// Default value: created_at_asc
OrderBy ListRpnCapableSanServersRequestOrderBy `json:"-"`
// ProjectID: filter rpn capable resources by project ID.
ProjectID *string `json:"-"`
}
// RpnV1ApiListRpnCapableServersRequest: rpn v1 api list rpn capable servers request.
type RpnV1ApiListRpnCapableServersRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn capable resources per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn capable resources.
// Default value: created_at_asc
OrderBy ListRpnCapableServersRequestOrderBy `json:"-"`
// ProjectID: filter rpn capable resources by project ID.
ProjectID *string `json:"-"`
}
// RpnV1ApiListRpnGroupMembersRequest: rpn v1 api list rpn group members request.
type RpnV1ApiListRpnGroupMembersRequest struct {
// GroupID: filter rpn v1 group members by group ID.
GroupID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v1 group members per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v1 group members.
// Default value: created_at_asc
OrderBy ListRpnGroupMembersRequestOrderBy `json:"-"`
// ProjectID: a project ID.
ProjectID *string `json:"-"`
}
// RpnV1ApiListRpnGroupsRequest: rpn v1 api list rpn groups request.
type RpnV1ApiListRpnGroupsRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v1 groups per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v1 groups.
// Default value: created_at_asc
OrderBy ListRpnGroupsRequestOrderBy `json:"-"`
// ProjectID: filter rpn v1 groups by project ID.
ProjectID *string `json:"-"`
}
// RpnV1ApiListRpnInvitesRequest: rpn v1 api list rpn invites request.
type RpnV1ApiListRpnInvitesRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn capable resources per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn capable resources.
// Default value: created_at_asc
OrderBy ListRpnInvitesRequestOrderBy `json:"-"`
// ProjectID: filter rpn capable resources by project ID.
ProjectID string `json:"-"`
}
// RpnV1ApiRefuseRpnInviteRequest: rpn v1 api refuse rpn invite request.
type RpnV1ApiRefuseRpnInviteRequest struct {
// MemberID: the member ID.
MemberID uint64 `json:"-"`
}
// RpnV1ApiRpnGroupInviteRequest: rpn v1 api rpn group invite request.
type RpnV1ApiRpnGroupInviteRequest struct {
// GroupID: the RPN V1 group ID.
GroupID uint64 `json:"-"`
// ServerIDs: a collection of external server IDs.
ServerIDs []uint64 `json:"server_ids"`
// ProjectID: a project ID.
ProjectID string `json:"project_id"`
}
// RpnV1ApiUpdateRpnGroupNameRequest: rpn v1 api update rpn group name request.
type RpnV1ApiUpdateRpnGroupNameRequest struct {
// GroupID: rpn v1 group ID.
GroupID uint64 `json:"-"`
// Name: new rpn v1 group name.
Name *string `json:"name,omitempty"`
}
// RpnV2ApiAddRpnV2MembersRequest: rpn v2 api add rpn v2 members request.
type RpnV2ApiAddRpnV2MembersRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// Servers: a collection of server IDs.
Servers []uint64 `json:"servers"`
}
// RpnV2ApiCreateRpnV2GroupRequest: rpn v2 api create rpn v2 group request.
type RpnV2ApiCreateRpnV2GroupRequest struct {
// ProjectID: project ID of the RPN V2 group.
ProjectID string `json:"project_id"`
// Type: rPN V2 group type (qing / standard).
// Default value: unknown_type
Type RpnV2GroupType `json:"type"`
// Name: rPN V2 group name.
Name string `json:"name"`
// Servers: a collection of server IDs.
Servers []uint64 `json:"servers"`
}
// RpnV2ApiDeleteRpnV2GroupRequest: rpn v2 api delete rpn v2 group request.
type RpnV2ApiDeleteRpnV2GroupRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
}
// RpnV2ApiDeleteRpnV2MembersRequest: rpn v2 api delete rpn v2 members request.
type RpnV2ApiDeleteRpnV2MembersRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// MemberIDs: a collection of member IDs.
MemberIDs []uint64 `json:"member_ids"`
}
// RpnV2ApiDisableRpnV2GroupCompatibilityRequest: rpn v2 api disable rpn v2 group compatibility request.
type RpnV2ApiDisableRpnV2GroupCompatibilityRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
}
// RpnV2ApiEnableRpnV2GroupCompatibilityRequest: rpn v2 api enable rpn v2 group compatibility request.
type RpnV2ApiEnableRpnV2GroupCompatibilityRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// Rpnv1GroupID: rPN V1 group ID.
Rpnv1GroupID uint64 `json:"rpnv1_group_id"`
}
// RpnV2ApiGetRpnV2GroupRequest: rpn v2 api get rpn v2 group request.
type RpnV2ApiGetRpnV2GroupRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
}
// RpnV2ApiListRpnV2CapableResourcesRequest: rpn v2 api list rpn v2 capable resources request.
type RpnV2ApiListRpnV2CapableResourcesRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v2 capable resources per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v2 capable resources.
// Default value: created_at_asc
OrderBy ListRpnV2CapableResourcesRequestOrderBy `json:"-"`
// ProjectID: filter rpn v2 capable resources by project ID.
ProjectID *string `json:"-"`
}
// RpnV2ApiListRpnV2GroupLogsRequest: rpn v2 api list rpn v2 group logs request.
type RpnV2ApiListRpnV2GroupLogsRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v2 group logs per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v2 group logs.
// Default value: created_at_asc
OrderBy ListRpnV2GroupLogsRequestOrderBy `json:"-"`
}
// RpnV2ApiListRpnV2GroupsRequest: rpn v2 api list rpn v2 groups request.
type RpnV2ApiListRpnV2GroupsRequest struct {
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v2 groups per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v2 groups.
// Default value: created_at_asc
OrderBy ListRpnV2GroupsRequestOrderBy `json:"-"`
// ProjectID: filter rpn v2 groups by project ID.
ProjectID *string `json:"-"`
}
// RpnV2ApiListRpnV2MembersRequest: rpn v2 api list rpn v2 members request.
type RpnV2ApiListRpnV2MembersRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// Page: page number.
Page *uint32 `json:"-"`
// PageSize: number of rpn v2 group members per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the rpn v2 group members.
// Default value: created_at_asc
OrderBy ListRpnV2MembersRequestOrderBy `json:"-"`
// Type: filter members by type.
// Default value: unknown_type
Type ListRpnV2MembersRequestType `json:"-"`
}
// RpnV2ApiUpdateRpnV2GroupNameRequest: rpn v2 api update rpn v2 group name request.
type RpnV2ApiUpdateRpnV2GroupNameRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// Name: rPN V2 group name.
Name *string `json:"name,omitempty"`
}
// RpnV2ApiUpdateRpnV2VlanForMembersRequest: rpn v2 api update rpn v2 vlan for members request.
type RpnV2ApiUpdateRpnV2VlanForMembersRequest struct {
// GroupID: rPN V2 group ID.
GroupID uint64 `json:"-"`
// MemberIDs: rPN V2 member IDs.
MemberIDs []uint64 `json:"member_ids"`
// Vlan: min: 0.
// Max: 3967.
Vlan *uint32 `json:"vlan,omitempty"`
}
// ServerDefaultPartitioning: server default partitioning.
type ServerDefaultPartitioning struct {
// Partitions: default partitions.
Partitions []*Partition `json:"partitions"`
}
// ServerInstall: server install.
type ServerInstall struct {
OsID uint64 `json:"os_id"`
Hostname string `json:"hostname"`
UserLogin *string `json:"user_login"`
Partitions []*Partition `json:"partitions"`
SSHKeyIDs []string `json:"ssh_key_ids"`
// Status: default value: unknown
Status ServerInstallStatus `json:"status"`
PanelURL *string `json:"panel_url"`
}
// StartBMCAccessRequest: start bmc access request.
type StartBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to start the BMC access.
ServerID uint64 `json:"-"`
// IP: the IP authorized to connect to the given server.
IP net.IP `json:"ip"`
}
// StartRescueRequest: start rescue request.
type StartRescueRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to start rescue.
ServerID uint64 `json:"-"`
// OsID: oS ID to use to start rescue.
OsID uint64 `json:"os_id"`
}
// StartServerRequest: start server request.
type StartServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to start.
ServerID uint64 `json:"-"`
}
// StopBMCAccessRequest: stop bmc access request.
type StopBMCAccessRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to stop BMC access.
ServerID uint64 `json:"-"`
}
// StopRescueRequest: stop rescue request.
type StopRescueRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server to stop rescue.
ServerID uint64 `json:"-"`
}
// StopServerRequest: stop server request.
type StopServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to stop.
ServerID uint64 `json:"-"`
}
// SubscribeServerOptionRequest: subscribe server option request.
type SubscribeServerOptionRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to subscribe server option.
ServerID uint64 `json:"-"`
// OptionID: option ID to subscribe.
OptionID uint64 `json:"option_id"`
}
// SubscribeStorageOptionsRequest: subscribe storage options request.
type SubscribeStorageOptionsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID of the storage options to subscribe.
ServerID uint64 `json:"-"`
// OptionsIDs: option IDs of the storage options to subscribe.
OptionsIDs []uint64 `json:"options_ids"`
}
// SubscribeStorageOptionsResponse: subscribe storage options response.
type SubscribeStorageOptionsResponse struct {
// Services: services subscribe storage options.
Services []*Service `json:"services"`
}
// UpdateRaidRequest: update raid request.
type UpdateRaidRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: ID of the server.
ServerID uint64 `json:"-"`
// RaidArrays: rAIDs to update.
RaidArrays []*UpdatableRaidArray `json:"raid_arrays"`
}
// UpdateReverseRequest: update reverse request.
type UpdateReverseRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP.
IPID uint64 `json:"-"`
// Reverse: reverse to apply on the IP.
Reverse string `json:"reverse"`
}
// UpdateServerBackupRequest: update server backup request.
type UpdateServerBackupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to update backup.
ServerID uint64 `json:"-"`
// Password: password of the server backup.
Password *string `json:"password,omitempty"`
// Autologin: autologin of the server backup.
Autologin *bool `json:"autologin,omitempty"`
// ACLEnabled: boolean to enable or disable ACL.
ACLEnabled *bool `json:"acl_enabled,omitempty"`
}
// UpdateServerRequest: update server request.
type UpdateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to update.
ServerID uint64 `json:"-"`
// Hostname: hostname of the server to update.
Hostname *string `json:"hostname,omitempty"`
// EnableIPv6: flag to enable or not the IPv6 of server.
EnableIPv6 *bool `json:"enable_ipv6,omitempty"`
}
// UpdateServerTagsRequest: update server tags request.
type UpdateServerTagsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: server ID to update the tags.
ServerID uint64 `json:"-"`
// Tags: tags of server to update.
Tags []string `json:"tags"`
}
// Dedibox Phoenix API.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1}
}
// ListServers: List baremetal servers for project.
func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "search", req.Search)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
Query: query,
}
var resp ListServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServer: Get the server associated with the given ID.
func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServerBackup:
func (s *API) GetServerBackup(req *GetServerBackupRequest, opts ...scw.RequestOption) (*Backup, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/backups",
}
var resp Backup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateServerBackup:
func (s *API) UpdateServerBackup(req *UpdateServerBackupRequest, opts ...scw.RequestOption) (*Backup, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/backups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSubscribableServerOptions: List subscribable options associated to the given server ID.
func (s *API) ListSubscribableServerOptions(req *ListSubscribableServerOptionsRequest, opts ...scw.RequestOption) (*ListSubscribableServerOptionsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/subscribable-server-options",
Query: query,
}
var resp ListSubscribableServerOptionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SubscribeServerOption: Subscribe option for the given server ID.
func (s *API) SubscribeServerOption(req *SubscribeServerOptionRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/subscribe-server-option",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateServer: Create a new baremetal server. The order return you a service ID to follow the provisionning status you could call GetService.
func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SubscribeStorageOptions: Subscribe storage option for the given server ID.
func (s *API) SubscribeStorageOptions(req *SubscribeStorageOptionsRequest, opts ...scw.RequestOption) (*SubscribeStorageOptionsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/subscribe-storage-options",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SubscribeStorageOptionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateServer: Update the server associated with the given ID.
func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateServerTags:
func (s *API) UpdateServerTags(req *UpdateServerTagsRequest, opts ...scw.RequestOption) (*Server, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/tags",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Server
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RebootServer: Reboot the server associated with the given ID, use boot param to reboot in rescue.
func (s *API) RebootServer(req *RebootServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/reboot",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// StartServer: Start the server associated with the given ID.
func (s *API) StartServer(req *StartServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/start",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// StopServer: Stop the server associated with the given ID.
func (s *API) StopServer(req *StopServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/stop",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// DeleteServer: Delete the server associated with the given ID.
func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListServerEvents: List events associated to the given server ID.
func (s *API) ListServerEvents(req *ListServerEventsRequest, opts ...scw.RequestOption) (*ListServerEventsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/events",
Query: query,
}
var resp ListServerEventsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerDisks: List disks associated to the given server ID.
func (s *API) ListServerDisks(req *ListServerDisksRequest, opts ...scw.RequestOption) (*ListServerDisksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/disks",
Query: query,
}
var resp ListServerDisksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOrderedService:
func (s *API) GetOrderedService(req *GetOrderedServiceRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OrderedServiceID) == "" {
return nil, errors.New("field OrderedServiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/ordered-services/" + fmt.Sprint(req.OrderedServiceID) + "",
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetService: Get the service associated with the given ID.
func (s *API) GetService(req *GetServiceRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServiceID) == "" {
return nil, errors.New("field ServiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/services/" + fmt.Sprint(req.ServiceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteService: Delete the service associated with the given ID.
func (s *API) DeleteService(req *DeleteServiceRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServiceID) == "" {
return nil, errors.New("field ServiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/services/" + fmt.Sprint(req.ServiceID) + "",
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServices: List services.
func (s *API) ListServices(req *ListServicesRequest, opts ...scw.RequestOption) (*ListServicesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/services",
Query: query,
}
var resp ListServicesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// InstallServer: Install an OS on the server associated with the given ID.
func (s *API) InstallServer(req *InstallServerRequest, opts ...scw.RequestOption) (*ServerInstall, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/install",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ServerInstall
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetServerInstall: Get the server installation status associated with the given server ID.
func (s *API) GetServerInstall(req *GetServerInstallRequest, opts ...scw.RequestOption) (*ServerInstall, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/install",
}
var resp ServerInstall
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CancelServerInstall: Cancels the current server installation associated with the given server ID.
func (s *API) CancelServerInstall(req *CancelServerInstallRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/cancel-install",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetServerDefaultPartitioning: Get the server default partitioning schema associated with the given server ID and OS ID.
func (s *API) GetServerDefaultPartitioning(req *GetServerDefaultPartitioningRequest, opts ...scw.RequestOption) (*ServerDefaultPartitioning, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.OsID) == "" {
return nil, errors.New("field OsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/partitioning/" + fmt.Sprint(req.OsID) + "",
}
var resp ServerDefaultPartitioning
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StartBMCAccess: Start BMC (Baseboard Management Controller) access associated with the given ID.
// The BMC (Baseboard Management Controller) access is available one hour after the installation of the server.
func (s *API) StartBMCAccess(req *StartBMCAccessRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetBMCAccess: Get the BMC (Baseboard Management Controller) access associated with the given ID.
func (s *API) GetBMCAccess(req *GetBMCAccessRequest, opts ...scw.RequestOption) (*BMCAccess, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
var resp BMCAccess
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StopBMCAccess: Stop BMC (Baseboard Management Controller) access associated with the given ID.
func (s *API) StopBMCAccess(req *StopBMCAccessRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/bmc-access",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListOffers: List all available server offers.
func (s *API) ListOffers(req *ListOffersRequest, opts ...scw.RequestOption) (*ListOffersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "commercial_range", req.CommercialRange)
parameter.AddToQuery(query, "catalog", req.Catalog)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "is_failover_ip", req.IsFailoverIP)
parameter.AddToQuery(query, "is_failover_block", req.IsFailoverBlock)
if len(req.SoldIn) != 0 {
parameter.AddToQuery(query, "sold_in", strings.Join(req.SoldIn, ","))
}
parameter.AddToQuery(query, "available_only", req.AvailableOnly)
parameter.AddToQuery(query, "is_rpn_san", req.IsRpnSan)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/offers",
Query: query,
}
var resp ListOffersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOffer: Return specific offer for the given ID.
func (s *API) GetOffer(req *GetOfferRequest, opts ...scw.RequestOption) (*Offer, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OfferID) == "" {
return nil, errors.New("field OfferID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/offers/" + fmt.Sprint(req.OfferID) + "",
Query: query,
}
var resp Offer
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOS: List all available OS that can be install on a baremetal server.
func (s *API) ListOS(req *ListOSRequest, opts ...scw.RequestOption) (*ListOSResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "server_id", req.ServerID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/os",
Query: query,
}
var resp ListOSResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOS: Return specific OS for the given ID.
func (s *API) GetOS(req *GetOSRequest, opts ...scw.RequestOption) (*OS, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "server_id", req.ServerID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.OsID) == "" {
return nil, errors.New("field OsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/os/" + fmt.Sprint(req.OsID) + "",
Query: query,
}
var resp OS
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateReverse: Update reverse of ip associated with the given ID.
func (s *API) UpdateReverse(req *UpdateReverseRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/reverses/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateFailoverIPs: Order X failover IPs.
func (s *API) CreateFailoverIPs(req *CreateFailoverIPsRequest, opts ...scw.RequestOption) (*CreateFailoverIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateFailoverIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachFailoverIPs: Attach failovers on the server associated with the given ID.
func (s *API) AttachFailoverIPs(req *AttachFailoverIPsRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/attach",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// DetachFailoverIPs: Detach failovers on the server associated with the given ID.
func (s *API) DetachFailoverIPs(req *DetachFailoverIPsRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/detach",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AttachFailoverIPToMacAddress: Attach a failover IP to a MAC address.
func (s *API) AttachFailoverIPToMacAddress(req *AttachFailoverIPToMacAddressRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/" + fmt.Sprint(req.IPID) + "/attach-to-mac-address",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachFailoverIPFromMacAddress: Detach a failover IP from a MAC address.
func (s *API) DetachFailoverIPFromMacAddress(req *DetachFailoverIPFromMacAddressRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/" + fmt.Sprint(req.IPID) + "/detach-from-mac-address",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteFailoverIP: Delete the failover associated with the given ID.
func (s *API) DeleteFailoverIP(req *DeleteFailoverIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/" + fmt.Sprint(req.IPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListFailoverIPs: List failovers servers for project.
func (s *API) ListFailoverIPs(req *ListFailoverIPsRequest, opts ...scw.RequestOption) (*ListFailoverIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "search", req.Search)
parameter.AddToQuery(query, "only_available", req.OnlyAvailable)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips",
Query: query,
}
var resp ListFailoverIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFailoverIP: Get the server associated with the given ID.
func (s *API) GetFailoverIP(req *GetFailoverIPRequest, opts ...scw.RequestOption) (*FailoverIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/failover-ips/" + fmt.Sprint(req.IPID) + "",
}
var resp FailoverIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRemainingQuota: Get remaining quota.
func (s *API) GetRemainingQuota(req *GetRemainingQuotaRequest, opts ...scw.RequestOption) (*GetRemainingQuotaResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/remaining-quota",
Query: query,
}
var resp GetRemainingQuotaResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRaid: Return raid for the given server ID.
func (s *API) GetRaid(req *GetRaidRequest, opts ...scw.RequestOption) (*Raid, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/raid",
}
var resp Raid
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRaid: Update RAID associated with the given server ID.
func (s *API) UpdateRaid(req *UpdateRaidRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/update-raid",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// StartRescue: Start in rescue the server associated with the given ID.
func (s *API) StartRescue(req *StartRescueRequest, opts ...scw.RequestOption) (*Rescue, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/rescue",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Rescue
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRescue: Return rescue information for the given server ID.
func (s *API) GetRescue(req *GetRescueRequest, opts ...scw.RequestOption) (*Rescue, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/rescue",
}
var resp Rescue
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StopRescue: Stop rescue on the server associated with the given ID.
func (s *API) StopRescue(req *StopRescueRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/rescue",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Dedibox Phoenix Billing API.
type BillingAPI struct {
client *scw.Client
}
// NewBillingAPI returns a BillingAPI object from a Scaleway client.
func NewBillingAPI(client *scw.Client) *BillingAPI {
return &BillingAPI{
client: client,
}
}
// ListInvoices:
func (s *BillingAPI) ListInvoices(req *BillingAPIListInvoicesRequest, opts ...scw.RequestOption) (*ListInvoicesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/invoices",
Query: query,
}
var resp ListInvoicesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInvoice:
func (s *BillingAPI) GetInvoice(req *BillingAPIGetInvoiceRequest, opts ...scw.RequestOption) (*Invoice, error) {
var err error
if fmt.Sprint(req.InvoiceID) == "" {
return nil, errors.New("field InvoiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/invoices/" + fmt.Sprint(req.InvoiceID) + "",
}
var resp Invoice
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DownloadInvoice:
func (s *BillingAPI) DownloadInvoice(req *BillingAPIDownloadInvoiceRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if fmt.Sprint(req.InvoiceID) == "" {
return nil, errors.New("field InvoiceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/invoices/" + fmt.Sprint(req.InvoiceID) + "/download",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRefunds:
func (s *BillingAPI) ListRefunds(req *BillingAPIListRefundsRequest, opts ...scw.RequestOption) (*ListRefundsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/refunds",
Query: query,
}
var resp ListRefundsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRefund:
func (s *BillingAPI) GetRefund(req *BillingAPIGetRefundRequest, opts ...scw.RequestOption) (*Refund, error) {
var err error
if fmt.Sprint(req.RefundID) == "" {
return nil, errors.New("field RefundID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/refunds/" + fmt.Sprint(req.RefundID) + "",
}
var resp Refund
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DownloadRefund:
func (s *BillingAPI) DownloadRefund(req *BillingAPIDownloadRefundRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if fmt.Sprint(req.RefundID) == "" {
return nil, errors.New("field RefundID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/refunds/" + fmt.Sprint(req.RefundID) + "/download",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CanOrder:
func (s *BillingAPI) CanOrder(req *BillingAPICanOrderRequest, opts ...scw.RequestOption) (*CanOrderResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/can-order",
Query: query,
}
var resp CanOrderResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Dedibox Phoenix IPv6 Block API.
type IPv6BlockAPI struct {
client *scw.Client
}
// NewIPv6BlockAPI returns a IPv6BlockAPI object from a Scaleway client.
func NewIPv6BlockAPI(client *scw.Client) *IPv6BlockAPI {
return &IPv6BlockAPI{
client: client,
}
}
// GetIPv6BlockQuotas: Get IPv6 block quota with the given project ID.
// /48 one per organization.
// /56 link to your number of server.
// /64 link to your number of failover IP.
func (s *IPv6BlockAPI) GetIPv6BlockQuotas(req *IPv6BlockAPIGetIPv6BlockQuotasRequest, opts ...scw.RequestOption) (*GetIPv6BlockQuotasResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/ipv6-block-quotas",
Query: query,
}
var resp GetIPv6BlockQuotasResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIPv6Block: Create IPv6 block associated with the given project ID.
func (s *IPv6BlockAPI) CreateIPv6Block(req *IPv6BlockAPICreateIPv6BlockRequest, opts ...scw.RequestOption) (*IPv6Block, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/ipv6-block",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IPv6Block
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIPv6Block: Get the IPv6 block associated with the given ID.
func (s *IPv6BlockAPI) GetIPv6Block(req *IPv6BlockAPIGetIPv6BlockRequest, opts ...scw.RequestOption) (*IPv6Block, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/ipv6-block",
Query: query,
}
var resp IPv6Block
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateIPv6Block: Update DNS associated to IPv6 block.
// If DNS is used, minimum of 2 is necessary and maximum of 5 (no duplicate).
func (s *IPv6BlockAPI) UpdateIPv6Block(req *IPv6BlockAPIUpdateIPv6BlockRequest, opts ...scw.RequestOption) (*IPv6Block, error) {
var err error
if fmt.Sprint(req.BlockID) == "" {
return nil, errors.New("field BlockID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/ipv6-blocks/" + fmt.Sprint(req.BlockID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IPv6Block
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteIPv6Block: Delete IPv6 block subnet with the given ID.
func (s *IPv6BlockAPI) DeleteIPv6Block(req *IPv6BlockAPIDeleteIPv6BlockRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.BlockID) == "" {
return errors.New("field BlockID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/ipv6-blocks/" + fmt.Sprint(req.BlockID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateIPv6BlockSubnet: Create IPv6 block subnet for the given IP ID.
// /48 could create subnet in /56 (quota link to your number of server).
// /56 could create subnet in /64 (quota link to your number of failover IP).
func (s *IPv6BlockAPI) CreateIPv6BlockSubnet(req *IPv6BlockAPICreateIPv6BlockSubnetRequest, opts ...scw.RequestOption) (*IPv6Block, error) {
var err error
if fmt.Sprint(req.BlockID) == "" {
return nil, errors.New("field BlockID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/ipv6-blocks/" + fmt.Sprint(req.BlockID) + "/subnets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IPv6Block
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPv6BlockSubnetsAvailable: List all available IPv6 block subnets for given IP ID.
func (s *IPv6BlockAPI) ListIPv6BlockSubnetsAvailable(req *IPv6BlockAPIListIPv6BlockSubnetsAvailableRequest, opts ...scw.RequestOption) (*ListIPv6BlockSubnetsAvailableResponse, error) {
var err error
if fmt.Sprint(req.BlockID) == "" {
return nil, errors.New("field BlockID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/ipv6-blocks/" + fmt.Sprint(req.BlockID) + "/subnets",
}
var resp ListIPv6BlockSubnetsAvailableResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Dedibox Phoenix RPN API.
type RpnAPI struct {
client *scw.Client
}
// NewRpnAPI returns a RpnAPI object from a Scaleway client.
func NewRpnAPI(client *scw.Client) *RpnAPI {
return &RpnAPI{
client: client,
}
}
// ListRpnServerCapabilities:
func (s *RpnAPI) ListRpnServerCapabilities(req *RpnAPIListRpnServerCapabilitiesRequest, opts ...scw.RequestOption) (*ListRpnServerCapabilitiesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn/server-capabilities",
Query: query,
}
var resp ListRpnServerCapabilitiesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRpnStatus:
func (s *RpnAPI) GetRpnStatus(req *RpnAPIGetRpnStatusRequest, opts ...scw.RequestOption) (*GetRpnStatusResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "rpnv1_group_id", req.Rpnv1GroupID)
parameter.AddToQuery(query, "rpnv2_group_id", req.Rpnv2GroupID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn/status",
Query: query,
}
var resp GetRpnStatusResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Dedibox Phoenix RPN SAN API.
type RpnSanAPI struct {
client *scw.Client
}
// NewRpnSanAPI returns a RpnSanAPI object from a Scaleway client.
func NewRpnSanAPI(client *scw.Client) *RpnSanAPI {
return &RpnSanAPI{
client: client,
}
}
// ListRpnSans:
func (s *RpnSanAPI) ListRpnSans(req *RpnSanAPIListRpnSansRequest, opts ...scw.RequestOption) (*ListRpnSansResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn-sans",
Query: query,
}
var resp ListRpnSansResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRpnSan:
func (s *RpnSanAPI) GetRpnSan(req *RpnSanAPIGetRpnSanRequest, opts ...scw.RequestOption) (*RpnSan, error) {
var err error
if fmt.Sprint(req.RpnSanID) == "" {
return nil, errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "",
}
var resp RpnSan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRpnSan:
func (s *RpnSanAPI) DeleteRpnSan(req *RpnSanAPIDeleteRpnSanRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.RpnSanID) == "" {
return errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateRpnSan:
func (s *RpnSanAPI) CreateRpnSan(req *RpnSanAPICreateRpnSanRequest, opts ...scw.RequestOption) (*Service, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpn-sans",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Service
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs:
func (s *RpnSanAPI) ListIPs(req *RpnSanAPIListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.RpnSanID) == "" {
return nil, errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddIP:
func (s *RpnSanAPI) AddIP(req *RpnSanAPIAddIPRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.RpnSanID) == "" {
return errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RemoveIP:
func (s *RpnSanAPI) RemoveIP(req *RpnSanAPIRemoveIPRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.RpnSanID) == "" {
return errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListAvailableIPs:
func (s *RpnSanAPI) ListAvailableIPs(req *RpnSanAPIListAvailableIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.RpnSanID) == "" {
return nil, errors.New("field RpnSanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpn-sans/" + fmt.Sprint(req.RpnSanID) + "/available-ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Dedibox Phoenix RPN v1 API.
type RpnV1API struct {
client *scw.Client
}
// NewRpnV1API returns a RpnV1API object from a Scaleway client.
func NewRpnV1API(client *scw.Client) *RpnV1API {
return &RpnV1API{
client: client,
}
}
// ListRpnGroups:
func (s *RpnV1API) ListRpnGroups(req *RpnV1ApiListRpnGroupsRequest, opts ...scw.RequestOption) (*ListRpnGroupsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/groups",
Query: query,
}
var resp ListRpnGroupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRpnGroup:
func (s *RpnV1API) GetRpnGroup(req *RpnV1ApiGetRpnGroupRequest, opts ...scw.RequestOption) (*RpnGroup, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "",
}
var resp RpnGroup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRpnGroup:
func (s *RpnV1API) CreateRpnGroup(req *RpnV1ApiCreateRpnGroupRequest, opts ...scw.RequestOption) (*RpnGroup, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/groups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnGroup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRpnGroup:
func (s *RpnV1API) DeleteRpnGroup(req *RpnV1ApiDeleteRpnGroupRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateRpnGroupName:
func (s *RpnV1API) UpdateRpnGroupName(req *RpnV1ApiUpdateRpnGroupNameRequest, opts ...scw.RequestOption) (*RpnGroup, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnGroup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnGroupMembers:
func (s *RpnV1API) ListRpnGroupMembers(req *RpnV1ApiListRpnGroupMembersRequest, opts ...scw.RequestOption) (*ListRpnGroupMembersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "/members",
Query: query,
}
var resp ListRpnGroupMembersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RpnGroupInvite:
func (s *RpnV1API) RpnGroupInvite(req *RpnV1ApiRpnGroupInviteRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "/invite",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// LeaveRpnGroup:
func (s *RpnV1API) LeaveRpnGroup(req *RpnV1ApiLeaveRpnGroupRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "/leave",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AddRpnGroupMembers:
func (s *RpnV1API) AddRpnGroupMembers(req *RpnV1ApiAddRpnGroupMembersRequest, opts ...scw.RequestOption) (*RpnGroup, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "/members",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnGroup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRpnGroupMembers:
func (s *RpnV1API) DeleteRpnGroupMembers(req *RpnV1ApiDeleteRpnGroupMembersRequest, opts ...scw.RequestOption) (*RpnGroup, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpnv1/groups/" + fmt.Sprint(req.GroupID) + "/members",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnGroup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnCapableServers:
func (s *RpnV1API) ListRpnCapableServers(req *RpnV1ApiListRpnCapableServersRequest, opts ...scw.RequestOption) (*ListRpnCapableServersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/capable-servers",
Query: query,
}
var resp ListRpnCapableServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnCapableSanServers:
func (s *RpnV1API) ListRpnCapableSanServers(req *RpnV1ApiListRpnCapableSanServersRequest, opts ...scw.RequestOption) (*ListRpnCapableSanServersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/capable-san-servers",
Query: query,
}
var resp ListRpnCapableSanServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnInvites:
func (s *RpnV1API) ListRpnInvites(req *RpnV1ApiListRpnInvitesRequest, opts ...scw.RequestOption) (*ListRpnInvitesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv1/invites",
Query: query,
}
var resp ListRpnInvitesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AcceptRpnInvite:
func (s *RpnV1API) AcceptRpnInvite(req *RpnV1ApiAcceptRpnInviteRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.MemberID) == "" {
return errors.New("field MemberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/invites/" + fmt.Sprint(req.MemberID) + "/accept",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RefuseRpnInvite:
func (s *RpnV1API) RefuseRpnInvite(req *RpnV1ApiRefuseRpnInviteRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.MemberID) == "" {
return errors.New("field MemberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv1/invites/" + fmt.Sprint(req.MemberID) + "/refuse",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Dedibox Phoenix RPN v2 API.
type RpnV2API struct {
client *scw.Client
}
// NewRpnV2API returns a RpnV2API object from a Scaleway client.
func NewRpnV2API(client *scw.Client) *RpnV2API {
return &RpnV2API{
client: client,
}
}
// ListRpnV2Groups:
func (s *RpnV2API) ListRpnV2Groups(req *RpnV2ApiListRpnV2GroupsRequest, opts ...scw.RequestOption) (*ListRpnV2GroupsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv2/groups",
Query: query,
}
var resp ListRpnV2GroupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnV2Members:
func (s *RpnV2API) ListRpnV2Members(req *RpnV2ApiListRpnV2MembersRequest, opts ...scw.RequestOption) (*ListRpnV2MembersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/members",
Query: query,
}
var resp ListRpnV2MembersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRpnV2Group:
func (s *RpnV2API) GetRpnV2Group(req *RpnV2ApiGetRpnV2GroupRequest, opts ...scw.RequestOption) (*RpnV2Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "",
}
var resp RpnV2Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRpnV2Group:
func (s *RpnV2API) CreateRpnV2Group(req *RpnV2ApiCreateRpnV2GroupRequest, opts ...scw.RequestOption) (*RpnV2Group, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv2/groups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnV2Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRpnV2Group:
func (s *RpnV2API) DeleteRpnV2Group(req *RpnV2ApiDeleteRpnV2GroupRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateRpnV2GroupName:
func (s *RpnV2API) UpdateRpnV2GroupName(req *RpnV2ApiUpdateRpnV2GroupNameRequest, opts ...scw.RequestOption) (*RpnV2Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RpnV2Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddRpnV2Members:
func (s *RpnV2API) AddRpnV2Members(req *RpnV2ApiAddRpnV2MembersRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/members",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// DeleteRpnV2Members:
func (s *RpnV2API) DeleteRpnV2Members(req *RpnV2ApiDeleteRpnV2MembersRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/members",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListRpnV2CapableResources:
func (s *RpnV2API) ListRpnV2CapableResources(req *RpnV2ApiListRpnV2CapableResourcesRequest, opts ...scw.RequestOption) (*ListRpnV2CapableResourcesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv2/groups/capable",
Query: query,
}
var resp ListRpnV2CapableResourcesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRpnV2GroupLogs:
func (s *RpnV2API) ListRpnV2GroupLogs(req *RpnV2ApiListRpnV2GroupLogsRequest, opts ...scw.RequestOption) (*ListRpnV2GroupLogsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/logs",
Query: query,
}
var resp ListRpnV2GroupLogsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRpnV2VlanForMembers:
func (s *RpnV2API) UpdateRpnV2VlanForMembers(req *RpnV2ApiUpdateRpnV2VlanForMembersRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/vlan",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// EnableRpnV2GroupCompatibility:
func (s *RpnV2API) EnableRpnV2GroupCompatibility(req *RpnV2ApiEnableRpnV2GroupCompatibilityRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/enable-compatibility",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// DisableRpnV2GroupCompatibility:
func (s *RpnV2API) DisableRpnV2GroupCompatibility(req *RpnV2ApiDisableRpnV2GroupCompatibilityRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/dedibox/v1/rpnv2/groups/" + fmt.Sprint(req.GroupID) + "/disable-compatibility",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/dedibox/v1/dedibox_utils.go 0000664 0000000 0000000 00000005204 14747113137 0030147 0 ustar 00root root 0000000 0000000 package dedibox
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = time.Second * 15
defaultTimeout = time.Minute * 30
)
type WaitForServiceRequest struct {
ServiceID uint64
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForService(req *WaitForServiceRequest, opts ...scw.RequestOption) (*Service, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServiceProvisioningStatus]struct{}{
ServiceProvisioningStatusReady: {},
ServiceProvisioningStatusError: {},
ServiceProvisioningStatusExpired: {},
}
service, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
service, err := s.GetService(&GetServiceRequest{
Zone: req.Zone,
ServiceID: req.ServiceID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[service.ProvisioningStatus]
return service, isTerminal, nil
},
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
Timeout: timeout,
})
if err != nil {
return nil, errors.Wrap(err, "waiting for service failed")
}
return service.(*Service), nil
}
type WaitForServerRequest struct {
ServerID uint64
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForServer(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerStatus]struct{}{
ServerStatusReady: {},
ServerStatusError: {},
ServerStatusLocked: {},
ServerStatusStopped: {},
ServerStatusBusy: {},
ServerStatusRescue: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
server, err := s.GetServer(&GetServerRequest{
Zone: req.Zone,
ServerID: req.ServerID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[server.Status]
return server, isTerminal, nil
},
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
Timeout: timeout,
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/documentdb/ 0000775 0000000 0000000 00000000000 14747113137 0025141 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/documentdb/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0026404 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/documentdb/v1beta1/documentdb_sdk.go 0000664 0000000 0000000 00000375053 14747113137 0031735 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package documentdb provides methods and message types of the documentdb v1beta1 API.
package documentdb
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ACLRuleAction string
const (
ACLRuleActionAllow = ACLRuleAction("allow")
ACLRuleActionDeny = ACLRuleAction("deny")
)
func (enum ACLRuleAction) String() string {
if enum == "" {
// return default value if empty
return "allow"
}
return string(enum)
}
func (enum ACLRuleAction) Values() []ACLRuleAction {
return []ACLRuleAction{
"allow",
"deny",
}
}
func (enum ACLRuleAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleAction(ACLRuleAction(tmp).String())
return nil
}
type ACLRuleDirection string
const (
ACLRuleDirectionInbound = ACLRuleDirection("inbound")
ACLRuleDirectionOutbound = ACLRuleDirection("outbound")
)
func (enum ACLRuleDirection) String() string {
if enum == "" {
// return default value if empty
return "inbound"
}
return string(enum)
}
func (enum ACLRuleDirection) Values() []ACLRuleDirection {
return []ACLRuleDirection{
"inbound",
"outbound",
}
}
func (enum ACLRuleDirection) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleDirection) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleDirection(ACLRuleDirection(tmp).String())
return nil
}
type ACLRuleProtocol string
const (
ACLRuleProtocolTCP = ACLRuleProtocol("tcp")
ACLRuleProtocolUDP = ACLRuleProtocol("udp")
ACLRuleProtocolIcmp = ACLRuleProtocol("icmp")
)
func (enum ACLRuleProtocol) String() string {
if enum == "" {
// return default value if empty
return "tcp"
}
return string(enum)
}
func (enum ACLRuleProtocol) Values() []ACLRuleProtocol {
return []ACLRuleProtocol{
"tcp",
"udp",
"icmp",
}
}
func (enum ACLRuleProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleProtocol(ACLRuleProtocol(tmp).String())
return nil
}
type EngineSettingPropertyType string
const (
EngineSettingPropertyTypeBOOLEAN = EngineSettingPropertyType("BOOLEAN")
EngineSettingPropertyTypeINT = EngineSettingPropertyType("INT")
EngineSettingPropertyTypeSTRING = EngineSettingPropertyType("STRING")
EngineSettingPropertyTypeFLOAT = EngineSettingPropertyType("FLOAT")
)
func (enum EngineSettingPropertyType) String() string {
if enum == "" {
// return default value if empty
return "BOOLEAN"
}
return string(enum)
}
func (enum EngineSettingPropertyType) Values() []EngineSettingPropertyType {
return []EngineSettingPropertyType{
"BOOLEAN",
"INT",
"STRING",
"FLOAT",
}
}
func (enum EngineSettingPropertyType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EngineSettingPropertyType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EngineSettingPropertyType(EngineSettingPropertyType(tmp).String())
return nil
}
type InstanceLogStatus string
const (
InstanceLogStatusUnknown = InstanceLogStatus("unknown")
InstanceLogStatusReady = InstanceLogStatus("ready")
InstanceLogStatusCreating = InstanceLogStatus("creating")
InstanceLogStatusError = InstanceLogStatus("error")
)
func (enum InstanceLogStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum InstanceLogStatus) Values() []InstanceLogStatus {
return []InstanceLogStatus{
"unknown",
"ready",
"creating",
"error",
}
}
func (enum InstanceLogStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceLogStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceLogStatus(InstanceLogStatus(tmp).String())
return nil
}
type InstanceStatus string
const (
InstanceStatusUnknown = InstanceStatus("unknown")
InstanceStatusReady = InstanceStatus("ready")
InstanceStatusProvisioning = InstanceStatus("provisioning")
InstanceStatusConfiguring = InstanceStatus("configuring")
InstanceStatusDeleting = InstanceStatus("deleting")
InstanceStatusError = InstanceStatus("error")
InstanceStatusAutohealing = InstanceStatus("autohealing")
InstanceStatusLocked = InstanceStatus("locked")
InstanceStatusInitializing = InstanceStatus("initializing")
InstanceStatusDiskFull = InstanceStatus("disk_full")
InstanceStatusBackuping = InstanceStatus("backuping")
InstanceStatusSnapshotting = InstanceStatus("snapshotting")
InstanceStatusRestarting = InstanceStatus("restarting")
)
func (enum InstanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum InstanceStatus) Values() []InstanceStatus {
return []InstanceStatus{
"unknown",
"ready",
"provisioning",
"configuring",
"deleting",
"error",
"autohealing",
"locked",
"initializing",
"disk_full",
"backuping",
"snapshotting",
"restarting",
}
}
func (enum InstanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceStatus(InstanceStatus(tmp).String())
return nil
}
type ListDatabasesRequestOrderBy string
const (
ListDatabasesRequestOrderByNameAsc = ListDatabasesRequestOrderBy("name_asc")
ListDatabasesRequestOrderByNameDesc = ListDatabasesRequestOrderBy("name_desc")
ListDatabasesRequestOrderBySizeAsc = ListDatabasesRequestOrderBy("size_asc")
ListDatabasesRequestOrderBySizeDesc = ListDatabasesRequestOrderBy("size_desc")
)
func (enum ListDatabasesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListDatabasesRequestOrderBy) Values() []ListDatabasesRequestOrderBy {
return []ListDatabasesRequestOrderBy{
"name_asc",
"name_desc",
"size_asc",
"size_desc",
}
}
func (enum ListDatabasesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabasesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabasesRequestOrderBy(ListDatabasesRequestOrderBy(tmp).String())
return nil
}
type ListInstanceLogsRequestOrderBy string
const (
ListInstanceLogsRequestOrderByCreatedAtAsc = ListInstanceLogsRequestOrderBy("created_at_asc")
ListInstanceLogsRequestOrderByCreatedAtDesc = ListInstanceLogsRequestOrderBy("created_at_desc")
)
func (enum ListInstanceLogsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInstanceLogsRequestOrderBy) Values() []ListInstanceLogsRequestOrderBy {
return []ListInstanceLogsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListInstanceLogsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInstanceLogsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInstanceLogsRequestOrderBy(ListInstanceLogsRequestOrderBy(tmp).String())
return nil
}
type ListInstancesRequestOrderBy string
const (
ListInstancesRequestOrderByCreatedAtAsc = ListInstancesRequestOrderBy("created_at_asc")
ListInstancesRequestOrderByCreatedAtDesc = ListInstancesRequestOrderBy("created_at_desc")
ListInstancesRequestOrderByNameAsc = ListInstancesRequestOrderBy("name_asc")
ListInstancesRequestOrderByNameDesc = ListInstancesRequestOrderBy("name_desc")
ListInstancesRequestOrderByRegion = ListInstancesRequestOrderBy("region")
ListInstancesRequestOrderByStatusAsc = ListInstancesRequestOrderBy("status_asc")
ListInstancesRequestOrderByStatusDesc = ListInstancesRequestOrderBy("status_desc")
)
func (enum ListInstancesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInstancesRequestOrderBy) Values() []ListInstancesRequestOrderBy {
return []ListInstancesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"region",
"status_asc",
"status_desc",
}
}
func (enum ListInstancesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInstancesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInstancesRequestOrderBy(ListInstancesRequestOrderBy(tmp).String())
return nil
}
type ListPrivilegesRequestOrderBy string
const (
ListPrivilegesRequestOrderByUserNameAsc = ListPrivilegesRequestOrderBy("user_name_asc")
ListPrivilegesRequestOrderByUserNameDesc = ListPrivilegesRequestOrderBy("user_name_desc")
ListPrivilegesRequestOrderByDatabaseNameAsc = ListPrivilegesRequestOrderBy("database_name_asc")
ListPrivilegesRequestOrderByDatabaseNameDesc = ListPrivilegesRequestOrderBy("database_name_desc")
)
func (enum ListPrivilegesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "user_name_asc"
}
return string(enum)
}
func (enum ListPrivilegesRequestOrderBy) Values() []ListPrivilegesRequestOrderBy {
return []ListPrivilegesRequestOrderBy{
"user_name_asc",
"user_name_desc",
"database_name_asc",
"database_name_desc",
}
}
func (enum ListPrivilegesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPrivilegesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPrivilegesRequestOrderBy(ListPrivilegesRequestOrderBy(tmp).String())
return nil
}
type ListSnapshotsRequestOrderBy string
const (
ListSnapshotsRequestOrderByCreatedAtAsc = ListSnapshotsRequestOrderBy("created_at_asc")
ListSnapshotsRequestOrderByCreatedAtDesc = ListSnapshotsRequestOrderBy("created_at_desc")
ListSnapshotsRequestOrderByNameAsc = ListSnapshotsRequestOrderBy("name_asc")
ListSnapshotsRequestOrderByNameDesc = ListSnapshotsRequestOrderBy("name_desc")
ListSnapshotsRequestOrderByExpiresAtAsc = ListSnapshotsRequestOrderBy("expires_at_asc")
ListSnapshotsRequestOrderByExpiresAtDesc = ListSnapshotsRequestOrderBy("expires_at_desc")
)
func (enum ListSnapshotsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSnapshotsRequestOrderBy) Values() []ListSnapshotsRequestOrderBy {
return []ListSnapshotsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"expires_at_asc",
"expires_at_desc",
}
}
func (enum ListSnapshotsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSnapshotsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSnapshotsRequestOrderBy(ListSnapshotsRequestOrderBy(tmp).String())
return nil
}
type ListUsersRequestOrderBy string
const (
ListUsersRequestOrderByNameAsc = ListUsersRequestOrderBy("name_asc")
ListUsersRequestOrderByNameDesc = ListUsersRequestOrderBy("name_desc")
ListUsersRequestOrderByIsAdminAsc = ListUsersRequestOrderBy("is_admin_asc")
ListUsersRequestOrderByIsAdminDesc = ListUsersRequestOrderBy("is_admin_desc")
)
func (enum ListUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListUsersRequestOrderBy) Values() []ListUsersRequestOrderBy {
return []ListUsersRequestOrderBy{
"name_asc",
"name_desc",
"is_admin_asc",
"is_admin_desc",
}
}
func (enum ListUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListUsersRequestOrderBy(ListUsersRequestOrderBy(tmp).String())
return nil
}
type MaintenanceStatus string
const (
MaintenanceStatusUnknown = MaintenanceStatus("unknown")
MaintenanceStatusPending = MaintenanceStatus("pending")
MaintenanceStatusDone = MaintenanceStatus("done")
MaintenanceStatusCanceled = MaintenanceStatus("canceled")
MaintenanceStatusOngoing = MaintenanceStatus("ongoing")
)
func (enum MaintenanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum MaintenanceStatus) Values() []MaintenanceStatus {
return []MaintenanceStatus{
"unknown",
"pending",
"done",
"canceled",
"ongoing",
}
}
func (enum MaintenanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MaintenanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MaintenanceStatus(MaintenanceStatus(tmp).String())
return nil
}
type NodeTypeGeneration string
const (
NodeTypeGenerationUnknownGeneration = NodeTypeGeneration("unknown_generation")
NodeTypeGenerationGenerationV1 = NodeTypeGeneration("generation_v1")
NodeTypeGenerationGenerationV2 = NodeTypeGeneration("generation_v2")
)
func (enum NodeTypeGeneration) String() string {
if enum == "" {
// return default value if empty
return "unknown_generation"
}
return string(enum)
}
func (enum NodeTypeGeneration) Values() []NodeTypeGeneration {
return []NodeTypeGeneration{
"unknown_generation",
"generation_v1",
"generation_v2",
}
}
func (enum NodeTypeGeneration) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeGeneration) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeGeneration(NodeTypeGeneration(tmp).String())
return nil
}
type NodeTypeStock string
const (
NodeTypeStockUnknown = NodeTypeStock("unknown")
NodeTypeStockLowStock = NodeTypeStock("low_stock")
NodeTypeStockOutOfStock = NodeTypeStock("out_of_stock")
NodeTypeStockAvailable = NodeTypeStock("available")
)
func (enum NodeTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NodeTypeStock) Values() []NodeTypeStock {
return []NodeTypeStock{
"unknown",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum NodeTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeStock(NodeTypeStock(tmp).String())
return nil
}
type Permission string
const (
PermissionReadonly = Permission("readonly")
PermissionReadwrite = Permission("readwrite")
PermissionAll = Permission("all")
PermissionCustom = Permission("custom")
PermissionNone = Permission("none")
)
func (enum Permission) String() string {
if enum == "" {
// return default value if empty
return "readonly"
}
return string(enum)
}
func (enum Permission) Values() []Permission {
return []Permission{
"readonly",
"readwrite",
"all",
"custom",
"none",
}
}
func (enum Permission) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Permission) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Permission(Permission(tmp).String())
return nil
}
type ReadReplicaStatus string
const (
ReadReplicaStatusUnknown = ReadReplicaStatus("unknown")
ReadReplicaStatusProvisioning = ReadReplicaStatus("provisioning")
ReadReplicaStatusInitializing = ReadReplicaStatus("initializing")
ReadReplicaStatusReady = ReadReplicaStatus("ready")
ReadReplicaStatusDeleting = ReadReplicaStatus("deleting")
ReadReplicaStatusError = ReadReplicaStatus("error")
ReadReplicaStatusLocked = ReadReplicaStatus("locked")
ReadReplicaStatusConfiguring = ReadReplicaStatus("configuring")
ReadReplicaStatusPromoting = ReadReplicaStatus("promoting")
)
func (enum ReadReplicaStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ReadReplicaStatus) Values() []ReadReplicaStatus {
return []ReadReplicaStatus{
"unknown",
"provisioning",
"initializing",
"ready",
"deleting",
"error",
"locked",
"configuring",
"promoting",
}
}
func (enum ReadReplicaStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ReadReplicaStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ReadReplicaStatus(ReadReplicaStatus(tmp).String())
return nil
}
type SnapshotStatus string
const (
SnapshotStatusUnknown = SnapshotStatus("unknown")
SnapshotStatusCreating = SnapshotStatus("creating")
SnapshotStatusReady = SnapshotStatus("ready")
SnapshotStatusRestoring = SnapshotStatus("restoring")
SnapshotStatusDeleting = SnapshotStatus("deleting")
SnapshotStatusError = SnapshotStatus("error")
SnapshotStatusLocked = SnapshotStatus("locked")
)
func (enum SnapshotStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum SnapshotStatus) Values() []SnapshotStatus {
return []SnapshotStatus{
"unknown",
"creating",
"ready",
"restoring",
"deleting",
"error",
"locked",
}
}
func (enum SnapshotStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotStatus(SnapshotStatus(tmp).String())
return nil
}
type StorageClass string
const (
StorageClassUnknownStorageClass = StorageClass("unknown_storage_class")
StorageClassLssd = StorageClass("lssd")
StorageClassBssd = StorageClass("bssd")
StorageClassSbs = StorageClass("sbs")
)
func (enum StorageClass) String() string {
if enum == "" {
// return default value if empty
return "unknown_storage_class"
}
return string(enum)
}
func (enum StorageClass) Values() []StorageClass {
return []StorageClass{
"unknown_storage_class",
"lssd",
"bssd",
"sbs",
}
}
func (enum StorageClass) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *StorageClass) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = StorageClass(StorageClass(tmp).String())
return nil
}
type VolumeType string
const (
VolumeTypeLssd = VolumeType("lssd")
VolumeTypeBssd = VolumeType("bssd")
VolumeTypeSbs5k = VolumeType("sbs_5k")
VolumeTypeSbs15k = VolumeType("sbs_15k")
)
func (enum VolumeType) String() string {
if enum == "" {
// return default value if empty
return "lssd"
}
return string(enum)
}
func (enum VolumeType) Values() []VolumeType {
return []VolumeType{
"lssd",
"bssd",
"sbs_5k",
"sbs_15k",
}
}
func (enum VolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeType(VolumeType(tmp).String())
return nil
}
// EndpointDirectAccessDetails: endpoint direct access details.
type EndpointDirectAccessDetails struct {
}
// EndpointLoadBalancerDetails: endpoint load balancer details.
type EndpointLoadBalancerDetails struct {
}
// EndpointPrivateNetworkDetails: endpoint private network details.
type EndpointPrivateNetworkDetails struct {
// PrivateNetworkID: UUID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: cIDR notation of the endpoint IPv4 address.
ServiceIP scw.IPNet `json:"service_ip"`
// Zone: private network zone.
Zone scw.Zone `json:"zone"`
}
// EndpointSpecPrivateNetworkIpamConfig: endpoint spec private network ipam config.
type EndpointSpecPrivateNetworkIpamConfig struct {
}
// ReadReplicaEndpointSpecPrivateNetworkIpamConfig: read replica endpoint spec private network ipam config.
type ReadReplicaEndpointSpecPrivateNetworkIpamConfig struct {
}
// EngineSetting: engine setting.
type EngineSetting struct {
// Name: setting name from the database engine.
Name string `json:"name"`
// DefaultValue: value set when not specified.
DefaultValue string `json:"default_value"`
// HotConfigurable: setting can be applied without restarting.
HotConfigurable bool `json:"hot_configurable"`
// Description: setting description.
Description string `json:"description"`
// PropertyType: setting type.
// Default value: BOOLEAN
PropertyType EngineSettingPropertyType `json:"property_type"`
// Unit: setting base unit.
Unit *string `json:"unit"`
// StringConstraint: validation regex for string type settings.
StringConstraint *string `json:"string_constraint"`
// IntMin: minimum value for int types.
IntMin *int32 `json:"int_min"`
// IntMax: maximum value for int types.
IntMax *int32 `json:"int_max"`
// FloatMin: minimum value for float types.
FloatMin *float32 `json:"float_min"`
// FloatMax: maximum value for float types.
FloatMax *float32 `json:"float_max"`
}
// Endpoint: endpoint.
type Endpoint struct {
// ID: UUID of the endpoint.
ID string `json:"id"`
// IP: iPv4 address of the endpoint.
// Precisely one of IP, Hostname must be set.
IP *net.IP `json:"ip,omitempty"`
// Port: TCP port of the endpoint.
Port uint32 `json:"port"`
// Name: name of the endpoint.
Name *string `json:"name"`
// PrivateNetwork: private Network details. One maximum per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
PrivateNetwork *EndpointPrivateNetworkDetails `json:"private_network,omitempty"`
// LoadBalancer: load Balancer details. Public endpoint for Database Instance which is systematically present. One per Database Instance.
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
LoadBalancer *EndpointLoadBalancerDetails `json:"load_balancer,omitempty"`
// DirectAccess: direct access details. Public endpoint reserved for Read Replicas. One per Read Replica.
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
DirectAccess *EndpointDirectAccessDetails `json:"direct_access,omitempty"`
// Hostname: hostname of the endpoint.
// Precisely one of IP, Hostname must be set.
Hostname *string `json:"hostname,omitempty"`
}
// EndpointSpecLoadBalancer: endpoint spec load balancer.
type EndpointSpecLoadBalancer struct {
}
// EndpointSpecPrivateNetwork: endpoint spec private network.
type EndpointSpecPrivateNetwork struct {
// PrivateNetworkID: UUID of the Private Network to be connected to the Database Instance.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: endpoint IPv4 address with a CIDR notation. Refer to the official Scaleway documentation to learn more about IP and subnet limitations.
// Precisely one of ServiceIP, IpamConfig must be set.
ServiceIP *scw.IPNet `json:"service_ip,omitempty"`
// IpamConfig: automated configuration of your Private Network endpoint with Scaleway IPAM service. One at the most per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of ServiceIP, IpamConfig must be set.
IpamConfig *EndpointSpecPrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
}
// ReadReplicaEndpointSpecDirectAccess: read replica endpoint spec direct access.
type ReadReplicaEndpointSpecDirectAccess struct {
}
// ReadReplicaEndpointSpecPrivateNetwork: read replica endpoint spec private network.
type ReadReplicaEndpointSpecPrivateNetwork struct {
// PrivateNetworkID: UUID of the Private Network to be connected to the Read Replica.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: endpoint IPv4 address with a CIDR notation. Refer to the official Scaleway documentation to learn more about IP and subnet limitations.
// Precisely one of ServiceIP, IpamConfig must be set.
ServiceIP *scw.IPNet `json:"service_ip,omitempty"`
// IpamConfig: automated configuration of your Private Network endpoint with Scaleway IPAM service. One at the most per Database Instance or Read Replica (a Database Instance and its Read Replica can have different private networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of ServiceIP, IpamConfig must be set.
IpamConfig *ReadReplicaEndpointSpecPrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
}
// EngineVersion: engine version.
type EngineVersion struct {
// Version: database engine version.
Version string `json:"version"`
// Name: database engine name.
Name string `json:"name"`
// EndOfLife: end of life date.
EndOfLife *time.Time `json:"end_of_life"`
// AvailableSettings: engine settings available to be set.
AvailableSettings []*EngineSetting `json:"available_settings"`
// Disabled: disabled versions cannot be created.
Disabled bool `json:"disabled"`
// Beta: beta status of engine version.
Beta bool `json:"beta"`
// AvailableInitSettings: engine settings available to be set at database initialization.
AvailableInitSettings []*EngineSetting `json:"available_init_settings"`
}
// BackupSchedule: backup schedule.
type BackupSchedule struct {
// Frequency: frequency of the backup schedule (in hours).
Frequency uint32 `json:"frequency"`
// Retention: default retention period of backups (in days).
Retention uint32 `json:"retention"`
// Disabled: defines whether the backup schedule feature is disabled.
Disabled bool `json:"disabled"`
// NextRunAt: next run of the backup schedule (accurate to 10 minutes).
NextRunAt *time.Time `json:"next_run_at"`
}
// InstanceSetting: instance setting.
type InstanceSetting struct {
Name string `json:"name"`
Value string `json:"value"`
}
// LogsPolicy: logs policy.
type LogsPolicy struct {
// MaxAgeRetention: max age (in days) of remote logs to keep on the Database Instance.
MaxAgeRetention *uint32 `json:"max_age_retention"`
// TotalDiskRetention: max disk size of remote logs to keep on the Database Instance.
TotalDiskRetention *scw.Size `json:"total_disk_retention"`
}
// Maintenance: maintenance.
type Maintenance struct {
// StartsAt: start date of the maintenance window.
StartsAt *time.Time `json:"starts_at"`
// StopsAt: end date of the maintenance window.
StopsAt *time.Time `json:"stops_at"`
// ClosedAt: closed maintenance date.
ClosedAt *time.Time `json:"closed_at"`
// Reason: maintenance information message.
Reason string `json:"reason"`
// Status: status of the maintenance.
// Default value: unknown
Status MaintenanceStatus `json:"status"`
// ForcedAt: time when Scaleway-side maintenance will be applied.
ForcedAt *time.Time `json:"forced_at"`
}
// ReadReplica: read replica.
type ReadReplica struct {
// ID: UUID of the Read Replica.
ID string `json:"id"`
// Endpoints: display Read Replica connection information.
Endpoints []*Endpoint `json:"endpoints"`
// Status: read replica status.
// Default value: unknown
Status ReadReplicaStatus `json:"status"`
// Region: region the Read Replica is in.
Region scw.Region `json:"region"`
// SameZone: whether the replica is in the same Availability Zone as the main Database Instance nodes or not.
SameZone bool `json:"same_zone"`
}
// UpgradableVersion: upgradable version.
type UpgradableVersion struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
MinorVersion string `json:"minor_version"`
}
// Volume: volume.
type Volume struct {
// Type: default value: lssd
Type VolumeType `json:"type"`
Size scw.Size `json:"size"`
// Class: default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// NodeTypeVolumeConstraintSizes: node type volume constraint sizes.
type NodeTypeVolumeConstraintSizes struct {
// MinSize: [deprecated] Mimimum size required for the Volume.
MinSize scw.Size `json:"min_size"`
// MaxSize: [deprecated] Maximum size required for the Volume.
MaxSize scw.Size `json:"max_size"`
}
// NodeTypeVolumeType: node type volume type.
type NodeTypeVolumeType struct {
// Type: volume Type.
// Default value: lssd
Type VolumeType `json:"type"`
// Description: the description of the Volume.
Description string `json:"description"`
// MinSize: mimimum size required for the Volume.
MinSize scw.Size `json:"min_size"`
// MaxSize: maximum size required for the Volume.
MaxSize scw.Size `json:"max_size"`
// ChunkSize: minimum increment level for a Block Storage volume size.
ChunkSize scw.Size `json:"chunk_size"`
// Class: the storage class of the volume.
// Default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// SnapshotVolumeType: snapshot volume type.
type SnapshotVolumeType struct {
// Type: default value: lssd
Type VolumeType `json:"type"`
// Class: default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// ACLRuleRequest: acl rule request.
type ACLRuleRequest struct {
IP scw.IPNet `json:"ip"`
Description string `json:"description"`
}
// ACLRule: acl rule.
type ACLRule struct {
IP scw.IPNet `json:"ip"`
// Deprecated
Port *uint32 `json:"port,omitempty"`
// Protocol: default value: tcp
Protocol ACLRuleProtocol `json:"protocol"`
// Direction: default value: inbound
Direction ACLRuleDirection `json:"direction"`
// Action: default value: allow
Action ACLRuleAction `json:"action"`
Description string `json:"description"`
}
// EndpointSpec: endpoint spec.
type EndpointSpec struct {
// LoadBalancer: load Balancer endpoint specifications. Public endpoint for Database Instance which is systematically present. One per Document Database Instance.
// Precisely one of LoadBalancer, PrivateNetwork must be set.
LoadBalancer *EndpointSpecLoadBalancer `json:"load_balancer,omitempty"`
// PrivateNetwork: private Network endpoint specifications. One maximum per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of LoadBalancer, PrivateNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetwork `json:"private_network,omitempty"`
}
// ReadReplicaEndpointSpec: read replica endpoint spec.
type ReadReplicaEndpointSpec struct {
// DirectAccess: direct access endpoint specifications. Public endpoint reserved for Read Replicas. One per Read Replica.
// Precisely one of DirectAccess, PrivateNetwork must be set.
DirectAccess *ReadReplicaEndpointSpecDirectAccess `json:"direct_access,omitempty"`
// PrivateNetwork: private Network endpoint specifications. One at most, per Read Replica. Cannot be updated (has to be deleted and recreated).
// Precisely one of DirectAccess, PrivateNetwork must be set.
PrivateNetwork *ReadReplicaEndpointSpecPrivateNetwork `json:"private_network,omitempty"`
}
// DatabaseEngine: database engine.
type DatabaseEngine struct {
// Name: engine name.
Name string `json:"name"`
// LogoURL: engine logo URL.
LogoURL string `json:"logo_url"`
// Versions: available versions.
Versions []*EngineVersion `json:"versions"`
// Region: region of this Database Instance.
Region scw.Region `json:"region"`
}
// Database: database.
type Database struct {
// Name: name of the database.
Name string `json:"name"`
// Owner: name of the database owner.
Owner string `json:"owner"`
// Managed: defines whether the database is managed or not.
Managed bool `json:"managed"`
// Size: size of the database.
Size scw.Size `json:"size"`
}
// ListInstanceLogsDetailsResponseInstanceLogDetail: list instance logs details response instance log detail.
type ListInstanceLogsDetailsResponseInstanceLogDetail struct {
LogName string `json:"log_name"`
Size uint64 `json:"size"`
}
// InstanceLog: instance log.
type InstanceLog struct {
// DownloadURL: presigned Object Storage URL to download your log file.
DownloadURL *string `json:"download_url"`
// ID: UUID of the Database Instance log.
ID string `json:"id"`
// Status: status of the logs in a Database Instance.
// Default value: unknown
Status InstanceLogStatus `json:"status"`
// NodeName: name of the underlying node.
NodeName string `json:"node_name"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// Region: region the Database Instance is in.
Region scw.Region `json:"region"`
}
// Instance: instance.
type Instance struct {
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// Volume: volumes of the Database Instance.
Volume *Volume `json:"volume"`
// Region: region the Database Instance is in.
Region scw.Region `json:"region"`
// ID: UUID of the Database Instance.
ID string `json:"id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// OrganizationID: organization ID the Database Instance belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the Database Instance belongs to.
ProjectID string `json:"project_id"`
// Status: status of the Database Instance.
// Default value: unknown
Status InstanceStatus `json:"status"`
// Engine: database engine of the database.
Engine string `json:"engine"`
// UpgradableVersion: available database engine versions for upgrade.
UpgradableVersion []*UpgradableVersion `json:"upgradable_version"`
// Deprecated: Endpoint: endpoint of the Database Instance.
Endpoint *Endpoint `json:"endpoint,omitempty"`
// Tags: list of tags applied to the Database Instance.
Tags []string `json:"tags"`
// Settings: advanced settings of the Database Instance.
Settings []*InstanceSetting `json:"settings"`
// BackupSchedule: backup schedule of the Database Instance.
BackupSchedule *BackupSchedule `json:"backup_schedule"`
// IsHaCluster: defines whether or not High-Availability is enabled.
IsHaCluster bool `json:"is_ha_cluster"`
// ReadReplicas: read Replicas of the Database Instance.
ReadReplicas []*ReadReplica `json:"read_replicas"`
// NodeType: node type of the Database Instance.
NodeType string `json:"node_type"`
// InitSettings: list of engine settings to be set at Database Instance initialization.
InitSettings []*InstanceSetting `json:"init_settings"`
// Endpoints: list of Database Instance endpoints.
Endpoints []*Endpoint `json:"endpoints"`
// LogsPolicy: logs policy of the Database Instance.
LogsPolicy *LogsPolicy `json:"logs_policy"`
// BackupSameRegion: store logical backups in the same region as the Database Instance.
BackupSameRegion bool `json:"backup_same_region"`
// Maintenances: list of Database Instance maintenance events.
Maintenances []*Maintenance `json:"maintenances"`
}
// NodeType: node type.
type NodeType struct {
// Name: node Type name identifier.
Name string `json:"name"`
// StockStatus: current stock status for the Node Type.
// Default value: unknown
StockStatus NodeTypeStock `json:"stock_status"`
// Description: current specs of the offer.
Description string `json:"description"`
// Vcpus: number of virtual CPUs.
Vcpus uint32 `json:"vcpus"`
// Memory: quantity of RAM.
Memory scw.Size `json:"memory"`
// Deprecated: VolumeConstraint: [deprecated] Node Type volume constraints.
VolumeConstraint *NodeTypeVolumeConstraintSizes `json:"volume_constraint,omitempty"`
// Deprecated: IsBssdCompatible: the Node Type is compliant with Block Storage.
IsBssdCompatible *bool `json:"is_bssd_compatible,omitempty"`
// Disabled: the Node Type is currently disabled.
Disabled bool `json:"disabled"`
// Beta: the Node Type is currently in beta.
Beta bool `json:"beta"`
// AvailableVolumeTypes: available storage options for the Node Type.
AvailableVolumeTypes []*NodeTypeVolumeType `json:"available_volume_types"`
// IsHaRequired: the Node Type can be used only with the High Availability option.
IsHaRequired bool `json:"is_ha_required"`
// Generation: generation associated the NodeType offer.
// Default value: unknown_generation
Generation NodeTypeGeneration `json:"generation"`
// InstanceRange: instance range associated with the NodeType offer.
InstanceRange string `json:"instance_range"`
// Region: region the Node Type is in.
Region scw.Region `json:"region"`
}
// Privilege: privilege.
type Privilege struct {
// Permission: permission (Read, Read/Write, All, Custom).
// Default value: readonly
Permission Permission `json:"permission"`
// DatabaseName: name of the database.
DatabaseName string `json:"database_name"`
// UserName: name of the user.
UserName string `json:"user_name"`
}
// Snapshot: snapshot.
type Snapshot struct {
// ID: UUID of the snapshot.
ID string `json:"id"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// Name: name of the snapshot.
Name string `json:"name"`
// Status: status of the snapshot.
// Default value: unknown
Status SnapshotStatus `json:"status"`
// Size: size of the snapshot.
Size *scw.Size `json:"size"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: updated date (must follow the ISO 8601 format).
UpdatedAt *time.Time `json:"updated_at"`
// InstanceName: name of the Database Instance of the snapshot.
InstanceName string `json:"instance_name"`
// NodeType: source node type.
NodeType string `json:"node_type"`
// VolumeType: type of volume where data is stored (lssd, bssd or sbs).
VolumeType *SnapshotVolumeType `json:"volume_type"`
// Region: region of this snapshot.
Region scw.Region `json:"region"`
}
// User: user.
type User struct {
// Name: name of the user (Length must be between 1 and 63 characters. First character must be an alphabet character (a-zA-Z). Your username cannot start with '_rdb' or 'pg_'. Only a-zA-Z0-9_$- characters are accepted).
Name string `json:"name"`
// IsAdmin: defines whether or not a user got administrative privileges on the Database Instance.
IsAdmin bool `json:"is_admin"`
}
// UpgradeInstanceRequestMajorUpgradeWorkflow: upgrade instance request major upgrade workflow.
type UpgradeInstanceRequestMajorUpgradeWorkflow struct {
// UpgradableVersionID: this will create a new Database Instance with same specifications as the current one and perform a Database Engine upgrade.
UpgradableVersionID string `json:"upgradable_version_id"`
// WithEndpoints: at the end of the migration procedure this option let you migrate all your database endpoint to the upgraded instance.
WithEndpoints bool `json:"with_endpoints"`
}
// AddInstanceACLRulesRequest: add instance acl rules request.
type AddInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to add ACL rules to.
InstanceID string `json:"-"`
// Rules: ACL rules to add to the Database Instance.
Rules []*ACLRuleRequest `json:"rules"`
}
// AddInstanceACLRulesResponse: add instance acl rules response.
type AddInstanceACLRulesResponse struct {
// Rules: ACL Rules enabled for the Database Instance.
Rules []*ACLRule `json:"rules"`
}
// AddInstanceSettingsRequest: add instance settings request.
type AddInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to add settings to.
InstanceID string `json:"-"`
// Settings: settings to add to the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// AddInstanceSettingsResponse: add instance settings response.
type AddInstanceSettingsResponse struct {
// Settings: settings available on the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// ApplyInstanceMaintenanceRequest: apply instance maintenance request.
type ApplyInstanceMaintenanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to which you want to apply maintenance.
InstanceID string `json:"-"`
}
// CloneInstanceRequest: clone instance request.
type CloneInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to clone.
InstanceID string `json:"-"`
// Name: name of the Database Instance clone.
Name string `json:"name"`
// NodeType: node type of the clone.
NodeType *string `json:"node_type,omitempty"`
}
// CreateDatabaseRequest: create database request.
type CreateDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where to create the database.
InstanceID string `json:"-"`
// Name: name of the database.
Name string `json:"name"`
}
// CreateEndpointRequest: create endpoint request.
type CreateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you to which you want to add an endpoint.
InstanceID string `json:"-"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec *EndpointSpec `json:"endpoint_spec,omitempty"`
}
// CreateInstanceFromSnapshotRequest: create instance from snapshot request.
type CreateInstanceFromSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: block snapshot of the Database Instance.
SnapshotID string `json:"-"`
// InstanceName: name of the Database Instance created with the snapshot.
InstanceName string `json:"instance_name"`
// IsHaCluster: defines whether or not High Availability is enabled on the new Database Instance.
IsHaCluster *bool `json:"is_ha_cluster,omitempty"`
// NodeType: the node type used to restore the snapshot.
NodeType *string `json:"node_type,omitempty"`
}
// CreateInstanceRequest: create instance request.
type CreateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Deprecated: OrganizationID: please use project_id instead.
// Precisely one of OrganizationID, ProjectID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: the Project ID on which the Database Instance will be created.
// Precisely one of OrganizationID, ProjectID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Name: name of the Database Instance.
Name string `json:"name"`
// Engine: database engine of the Database Instance.
Engine string `json:"engine"`
// UserName: username created when the Database Instance is created.
UserName string `json:"user_name"`
// Password: password of the user.
Password string `json:"password"`
// NodeType: type of node to use for the Database Instance.
NodeType string `json:"node_type"`
// IsHaCluster: defines whether or not High-Availability is enabled.
IsHaCluster bool `json:"is_ha_cluster"`
// DisableBackup: defines whether or not backups are disabled.
DisableBackup bool `json:"disable_backup"`
// Tags: tags to apply to the Database Instance.
Tags []string `json:"tags"`
// InitSettings: list of engine settings to be set upon Database Instance initialization.
InitSettings []*InstanceSetting `json:"init_settings"`
// VolumeType: type of volume where data is stored (lssd, bssd, ...).
// Default value: lssd
VolumeType VolumeType `json:"volume_type"`
// VolumeSize: volume size when volume_type is not lssd.
VolumeSize scw.Size `json:"volume_size"`
// InitEndpoints: one or multiple EndpointSpec used to expose your Database Instance. A load_balancer public endpoint is systematically created.
InitEndpoints []*EndpointSpec `json:"init_endpoints"`
// BackupSameRegion: defines whether to or not to store logical backups in the same region as the Database Instance.
BackupSameRegion bool `json:"backup_same_region"`
}
// CreateReadReplicaEndpointRequest: create read replica endpoint request.
type CreateReadReplicaEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec []*ReadReplicaEndpointSpec `json:"endpoint_spec"`
}
// CreateReadReplicaRequest: create read replica request.
type CreateReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to create a Read Replica from.
InstanceID string `json:"instance_id"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec []*ReadReplicaEndpointSpec `json:"endpoint_spec"`
// SameZone: defines whether or not to create the replica in the same Availability Zone as the main Database Instance nodes.
SameZone *bool `json:"same_zone,omitempty"`
}
// CreateSnapshotRequest: create snapshot request.
type CreateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// Name: name of the snapshot.
Name string `json:"name"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateUserRequest: create user request.
type CreateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance in which you want to create a user.
InstanceID string `json:"-"`
// Name: name of the user you want to create.
Name string `json:"name"`
// Password: password of the user you want to create.
Password string `json:"password"`
// IsAdmin: defines whether the user will have administrative privileges.
IsAdmin bool `json:"is_admin"`
}
// DeleteDatabaseRequest: delete database request.
type DeleteDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where to delete the database.
InstanceID string `json:"-"`
// Name: name of the database to delete.
Name string `json:"-"`
}
// DeleteEndpointRequest: delete endpoint request.
type DeleteEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: this endpoint can also be used to delete a Read Replica endpoint.
EndpointID string `json:"-"`
}
// DeleteInstanceACLRulesRequest: delete instance acl rules request.
type DeleteInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to delete an ACL rule from.
InstanceID string `json:"-"`
// ACLRuleIPs: IP addresses defined in the ACL rules of the Database Instance.
ACLRuleIPs []string `json:"acl_rule_ips"`
}
// DeleteInstanceACLRulesResponse: delete instance acl rules response.
type DeleteInstanceACLRulesResponse struct {
// Rules: IP addresses defined in the ACL rules of the Database Instance.
Rules []*ACLRule `json:"rules"`
}
// DeleteInstanceRequest: delete instance request.
type DeleteInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete.
InstanceID string `json:"-"`
}
// DeleteInstanceSettingsRequest: delete instance settings request.
type DeleteInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete settings from.
InstanceID string `json:"-"`
// SettingNames: settings names to delete.
SettingNames []string `json:"setting_names"`
}
// DeleteInstanceSettingsResponse: delete instance settings response.
type DeleteInstanceSettingsResponse struct {
// Settings: settings names to delete from the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// DeleteReadReplicaRequest: delete read replica request.
type DeleteReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// DeleteSnapshotRequest: delete snapshot request.
type DeleteSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot to delete.
SnapshotID string `json:"-"`
}
// DeleteUserRequest: delete user request.
type DeleteUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete the user from.
InstanceID string `json:"-"`
// Name: name of the user.
Name string `json:"-"`
}
// GetEndpointRequest: get endpoint request.
type GetEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: UUID of the endpoint you want to get.
EndpointID string `json:"-"`
}
// GetInstanceCertificateRequest: get instance certificate request.
type GetInstanceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetInstanceLogRequest: get instance log request.
type GetInstanceLogRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceLogID: UUID of the instance_log you want.
InstanceLogID string `json:"-"`
}
// GetInstanceMetricsRequest: get instance metrics request.
type GetInstanceMetricsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// StartDate: start date to gather metrics from.
StartDate *time.Time `json:"-"`
// EndDate: end date to gather metrics from.
EndDate *time.Time `json:"-"`
// MetricName: name of the metric to gather.
MetricName *string `json:"-"`
}
// GetInstanceRequest: get instance request.
type GetInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetReadReplicaRequest: get read replica request.
type GetReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// GetSnapshotRequest: get snapshot request.
type GetSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// InstanceMetrics: instance metrics.
type InstanceMetrics struct {
// Timeseries: time series of metrics of a Database Instance.
Timeseries []*scw.TimeSeries `json:"timeseries"`
}
// ListDatabaseEnginesRequest: list database engines request.
type ListDatabaseEnginesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the database engine.
Name *string `json:"-"`
// Version: version of the database engine.
Version *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListDatabaseEnginesResponse: list database engines response.
type ListDatabaseEnginesResponse struct {
// Engines: list of the available database engines.
Engines []*DatabaseEngine `json:"engines"`
// TotalCount: total count of database engines available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabaseEnginesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabaseEnginesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDatabaseEnginesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Engines = append(r.Engines, results.Engines...)
r.TotalCount += uint32(len(results.Engines))
return uint32(len(results.Engines)), nil
}
// ListDatabasesRequest: list databases request.
type ListDatabasesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to list the databases of.
InstanceID string `json:"-"`
// Name: name of the database.
Name *string `json:"-"`
// Managed: defines whether or not the database is managed.
Managed *bool `json:"-"`
// Owner: user that owns this database.
Owner *string `json:"-"`
// OrderBy: criteria to use when ordering database listing.
// Default value: name_asc
OrderBy ListDatabasesRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListDatabasesResponse: list databases response.
type ListDatabasesResponse struct {
// Databases: list of the databases.
Databases []*Database `json:"databases"`
// TotalCount: total count of databases present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDatabasesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Databases = append(r.Databases, results.Databases...)
r.TotalCount += uint32(len(results.Databases))
return uint32(len(results.Databases)), nil
}
// ListInstanceACLRulesRequest: list instance acl rules request.
type ListInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListInstanceACLRulesResponse: list instance acl rules response.
type ListInstanceACLRulesResponse struct {
// Rules: list of ACL rules present on a Database Instance.
Rules []*ACLRule `json:"rules"`
// TotalCount: total count of ACL rules present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInstanceACLRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInstanceACLRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListInstanceACLRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint32(len(results.Rules))
return uint32(len(results.Rules)), nil
}
// ListInstanceLogsDetailsRequest: list instance logs details request.
type ListInstanceLogsDetailsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
}
// ListInstanceLogsDetailsResponse: list instance logs details response.
type ListInstanceLogsDetailsResponse struct {
// Details: remote Database Instance logs details.
Details []*ListInstanceLogsDetailsResponseInstanceLogDetail `json:"details"`
}
// ListInstanceLogsRequest: list instance logs request.
type ListInstanceLogsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
// OrderBy: criteria to use when ordering Database Instance logs listing.
// Default value: created_at_asc
OrderBy ListInstanceLogsRequestOrderBy `json:"order_by"`
}
// ListInstanceLogsResponse: list instance logs response.
type ListInstanceLogsResponse struct {
// InstanceLogs: available logs in a Database Instance.
InstanceLogs []*InstanceLog `json:"instance_logs"`
}
// ListInstancesRequest: list instances request.
type ListInstancesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Tags: list Database Instances that have a given tag.
Tags []string `json:"-"`
// Name: lists Database Instances that match a name pattern.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering Database Instance listings.
// Default value: created_at_asc
OrderBy ListInstancesRequestOrderBy `json:"-"`
// OrganizationID: please use project_id instead.
OrganizationID *string `json:"-"`
// ProjectID: project ID to list the Database Instance of.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListInstancesResponse: list instances response.
type ListInstancesResponse struct {
// Instances: list of all Database Instances available in an Organization or Project.
Instances []*Instance `json:"instances"`
// TotalCount: total count of Database Instances available in a Organization or Project.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListInstancesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Instances = append(r.Instances, results.Instances...)
r.TotalCount += uint32(len(results.Instances))
return uint32(len(results.Instances)), nil
}
// ListNodeTypesRequest: list node types request.
type ListNodeTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IncludeDisabledTypes: defines whether or not to include disabled types.
IncludeDisabledTypes bool `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListNodeTypesResponse: list node types response.
type ListNodeTypesResponse struct {
// NodeTypes: types of the node.
NodeTypes []*NodeType `json:"node_types"`
// TotalCount: total count of node-types available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNodeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NodeTypes = append(r.NodeTypes, results.NodeTypes...)
r.TotalCount += uint32(len(results.NodeTypes))
return uint32(len(results.NodeTypes)), nil
}
// ListPrivilegesRequest: list privileges request.
type ListPrivilegesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// OrderBy: criteria to use when ordering privileges listing.
// Default value: user_name_asc
OrderBy ListPrivilegesRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// DatabaseName: name of the database.
DatabaseName *string `json:"-"`
// UserName: name of the user.
UserName *string `json:"-"`
}
// ListPrivilegesResponse: list privileges response.
type ListPrivilegesResponse struct {
// Privileges: privileges of a user in a database in a Database Instance.
Privileges []*Privilege `json:"privileges"`
// TotalCount: total count of privileges present on a database.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPrivilegesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPrivilegesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPrivilegesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Privileges = append(r.Privileges, results.Privileges...)
r.TotalCount += uint32(len(results.Privileges))
return uint32(len(results.Privileges)), nil
}
// ListSnapshotsRequest: list snapshots request.
type ListSnapshotsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the snapshot.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering snapshot listing.
// Default value: created_at_asc
OrderBy ListSnapshotsRequestOrderBy `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID *string `json:"-"`
// OrganizationID: organization ID the snapshots belongs to.
OrganizationID *string `json:"-"`
// ProjectID: project ID the snapshots belongs to.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListSnapshotsResponse: list snapshots response.
type ListSnapshotsResponse struct {
// Snapshots: list of snapshots.
Snapshots []*Snapshot `json:"snapshots"`
// TotalCount: total count of snapshots available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSnapshotsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Snapshots = append(r.Snapshots, results.Snapshots...)
r.TotalCount += uint32(len(results.Snapshots))
return uint32(len(results.Snapshots)), nil
}
// ListUsersRequest: list users request.
type ListUsersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// Name: name of the user.
Name *string `json:"-"`
// OrderBy: criteria to use when requesting user listing.
// Default value: name_asc
OrderBy ListUsersRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListUsersResponse: list users response.
type ListUsersResponse struct {
// Users: list of users in a Database Instance.
Users []*User `json:"users"`
// TotalCount: total count of users present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Users = append(r.Users, results.Users...)
r.TotalCount += uint32(len(results.Users))
return uint32(len(results.Users)), nil
}
// MigrateEndpointRequest: migrate endpoint request.
type MigrateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: UUID of the endpoint you want to migrate.
EndpointID string `json:"-"`
// InstanceID: UUID of the instance you want to attach the endpoint to.
InstanceID string `json:"instance_id"`
}
// PromoteReadReplicaRequest: promote read replica request.
type PromoteReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// PurgeInstanceLogsRequest: purge instance logs request.
type PurgeInstanceLogsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
// LogName: given log name to purge.
LogName *string `json:"log_name,omitempty"`
}
// RenewInstanceCertificateRequest: renew instance certificate request.
type RenewInstanceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
}
// ResetReadReplicaRequest: reset read replica request.
type ResetReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// RestartInstanceRequest: restart instance request.
type RestartInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to restart.
InstanceID string `json:"-"`
}
// SetInstanceACLRulesRequest: set instance acl rules request.
type SetInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where the ACL rules must be set.
InstanceID string `json:"-"`
// Rules: ACL rules to define for the Database Instance.
Rules []*ACLRuleRequest `json:"rules"`
}
// SetInstanceACLRulesResponse: set instance acl rules response.
type SetInstanceACLRulesResponse struct {
// Rules: aCLs rules configured for a Database Instance.
Rules []*ACLRule `json:"rules"`
}
// SetInstanceSettingsRequest: set instance settings request.
type SetInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where the settings must be set.
InstanceID string `json:"-"`
// Settings: settings to define for the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// SetInstanceSettingsResponse: set instance settings response.
type SetInstanceSettingsResponse struct {
// Settings: settings configured for a Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// SetPrivilegeRequest: set privilege request.
type SetPrivilegeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// DatabaseName: name of the database.
DatabaseName string `json:"database_name"`
// UserName: name of the user.
UserName string `json:"user_name"`
// Permission: permission to set (Read, Read/Write, All, Custom).
// Default value: readonly
Permission Permission `json:"permission"`
}
// UpdateInstanceRequest: update instance request.
type UpdateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to update.
InstanceID string `json:"-"`
// BackupScheduleFrequency: in hours.
BackupScheduleFrequency *uint32 `json:"backup_schedule_frequency,omitempty"`
// BackupScheduleRetention: in days.
BackupScheduleRetention *uint32 `json:"backup_schedule_retention,omitempty"`
// IsBackupScheduleDisabled: defines whether or not the backup schedule is disabled.
IsBackupScheduleDisabled *bool `json:"is_backup_schedule_disabled,omitempty"`
// Name: name of the Database Instance.
Name *string `json:"name,omitempty"`
// Tags: tags of a Database Instance.
Tags *[]string `json:"tags,omitempty"`
// LogsPolicy: logs policy of the Database Instance.
LogsPolicy *LogsPolicy `json:"logs_policy,omitempty"`
// BackupSameRegion: store logical backups in the same region as the Database Instance.
BackupSameRegion *bool `json:"backup_same_region,omitempty"`
// BackupScheduleStartHour: defines the start time of the autobackup.
BackupScheduleStartHour *uint32 `json:"backup_schedule_start_hour,omitempty"`
}
// UpdateSnapshotRequest: update snapshot request.
type UpdateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot to update.
SnapshotID string `json:"-"`
// Name: name of the snapshot.
Name *string `json:"name,omitempty"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// UpdateUserRequest: update user request.
type UpdateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance the user belongs to.
InstanceID string `json:"-"`
// Name: name of the database user.
Name string `json:"-"`
// Password: password of the database user.
Password *string `json:"password,omitempty"`
// IsAdmin: defines whether or not this user got administrative privileges.
IsAdmin *bool `json:"is_admin,omitempty"`
}
// UpgradeInstanceRequest: upgrade instance request.
type UpgradeInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to upgrade.
InstanceID string `json:"-"`
// NodeType: node type of the Database Instance you want to upgrade to.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
NodeType *string `json:"node_type,omitempty"`
// EnableHa: defines whether or not High Availability should be enabled on the Database Instance.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
EnableHa *bool `json:"enable_ha,omitempty"`
// VolumeSize: increase your Block volume size.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
VolumeSize *uint64 `json:"volume_size,omitempty"`
// VolumeType: change your Database Instance storage type.
// Default value: lssd
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
VolumeType *VolumeType `json:"volume_type,omitempty"`
// UpgradableVersionID: this will create a new Database Instance with same specifications as the current one and perform a Database Engine upgrade.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
UpgradableVersionID *string `json:"upgradable_version_id,omitempty"`
// MajorUpgradeWorkflow: upgrade your database engine to a new major version including instance endpoints.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow must be set.
MajorUpgradeWorkflow *UpgradeInstanceRequestMajorUpgradeWorkflow `json:"major_upgrade_workflow,omitempty"`
}
// This API allows you to manage your Document Databases.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListDatabaseEngines: List the FerretDB database engines available at Scaleway.
func (s *API) ListDatabaseEngines(req *ListDatabaseEnginesRequest, opts ...scw.RequestOption) (*ListDatabaseEnginesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "version", req.Version)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/database-engines",
Query: query,
}
var resp ListDatabaseEnginesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNodeTypes: List all available node types. By default, the node types returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListNodeTypes(req *ListNodeTypesRequest, opts ...scw.RequestOption) (*ListNodeTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "include_disabled_types", req.IncludeDisabledTypes)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/node-types",
Query: query,
}
var resp ListNodeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradeInstance: Upgrade your current Database Instance specifications like node type, high availability, volume, or the database engine version. Note that upon upgrade the `enable_ha` parameter can only be set to `true`.
func (s *API) UpgradeInstance(req *UpgradeInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstances: List all Database Instances in the specified region, for a given Scaleway Organization or Scaleway Project. By default, the Database Instances returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `tags` and `name`. For the `name` parameter, the value you include will be checked against the whole name string to see if it includes the string you put in the parameter.
func (s *API) ListInstances(req *ListInstancesRequest, opts ...scw.RequestOption) (*ListInstancesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances",
Query: query,
}
var resp ListInstancesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstance: Retrieve information about a given Database Instance, specified by the `region` and `instance_id` parameters. Its full details, including name, status, IP address and port, are returned in the response object.
func (s *API) GetInstance(req *GetInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateInstance: Create a new Database Instance. You must set the `engine`, `user_name`, `password` and `node_type` parameters. Optionally, you can specify the volume type and size.
func (s *API) CreateInstance(req *CreateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.OrganizationID == nil && req.ProjectID == nil {
req.OrganizationID = &defaultOrganizationID
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.OrganizationID == nil && req.ProjectID == nil {
req.ProjectID = &defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("ins")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateInstance: Update the parameters of a Database Instance, including name, tags and backup schedule details.
func (s *API) UpdateInstance(req *UpdateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstance: Delete a given Database Instance, specified by the `region` and `instance_id` parameters. Deleting a Database Instance is permanent, and cannot be undone. Note that upon deletion all your data will be lost.
func (s *API) DeleteInstance(req *DeleteInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CloneInstance: Clone a given Database Instance, specified by the `region` and `instance_id` parameters. The clone feature allows you to create a new Database Instance from an existing one. The clone includes all existing databases, users and permissions. You can create a clone on a Database Instance bigger than your current one.
func (s *API) CloneInstance(req *CloneInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/clone",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestartInstance: Restart a given Database Instance, specified by the `region` and `instance_id` parameters. The status of the Database Instance returned in the response.
func (s *API) RestartInstance(req *RestartInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/restart",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstanceCertificate: Retrieve information about the TLS certificate of a given Database Instance. Details like name and content are returned in the response.
func (s *API) GetInstanceCertificate(req *GetInstanceCertificateRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/certificate",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RenewInstanceCertificate: Renew a TLS for a Database Instance. Renewing a certificate means that you will not be able to connect to your Database Instance using the previous certificate. You will also need to download and update the new certificate for all database clients.
func (s *API) RenewInstanceCertificate(req *RenewInstanceCertificateRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/renew-certificate",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetInstanceMetrics: Retrieve the time series metrics of a given Database Instance. You can define the period from which to retrieve metrics by specifying the `start_date` and `end_date`.
func (s *API) GetInstanceMetrics(req *GetInstanceMetricsRequest, opts ...scw.RequestOption) (*InstanceMetrics, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "start_date", req.StartDate)
parameter.AddToQuery(query, "end_date", req.EndDate)
parameter.AddToQuery(query, "metric_name", req.MetricName)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/metrics",
Query: query,
}
var resp InstanceMetrics
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateReadReplica: Create a new Read Replica of a Database Instance. You must specify the `region` and the `instance_id`. You can only create a maximum of 3 Read Replicas per Database Instance.
func (s *API) CreateReadReplica(req *CreateReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetReadReplica: Retrieve information about a Database Instance Read Replica. Full details about the Read Replica, like `endpoints`, `status` and `region` are returned in the response.
func (s *API) GetReadReplica(req *GetReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "",
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteReadReplica: Delete a Read Replica of a Database Instance. You must specify the `region` and `read_replica_id` parameters of the Read Replica you want to delete.
func (s *API) DeleteReadReplica(req *DeleteReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "",
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ResetReadReplica: When you resync a Read Replica, first it is reset, then its data is resynchronized from the primary node. Your Read Replica remains unavailable during the resync process. The duration of this process is proportional to the size of your Database Instance.
// The configured endpoints do not change.
func (s *API) ResetReadReplica(req *ResetReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/reset",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PromoteReadReplica: Promote a Read Replica to Database Instance automatically.
func (s *API) PromoteReadReplica(req *PromoteReadReplicaRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/promote",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateReadReplicaEndpoint: Create a new endpoint for a Read Replica. Read Replicas can have at most one direct access and one Private Network endpoint.
func (s *API) CreateReadReplicaEndpoint(req *CreateReadReplicaEndpointRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstanceLogs: List the available logs of a Database Instance. By default, the logs returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListInstanceLogs(req *ListInstanceLogsRequest, opts ...scw.RequestOption) (*ListInstanceLogsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/logs",
Query: query,
}
var resp ListInstanceLogsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstanceLog: Retrieve information about the logs of a Database Instance. Specify the `instance_log_id` and `region` in your request to get information such as `download_url`, `status`, `expires_at` and `created_at` about your logs in the response.
func (s *API) GetInstanceLog(req *GetInstanceLogRequest, opts ...scw.RequestOption) (*InstanceLog, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceLogID) == "" {
return nil, errors.New("field InstanceLogID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/logs/" + fmt.Sprint(req.InstanceLogID) + "",
}
var resp InstanceLog
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PurgeInstanceLogs: Purge a given remote log from a Database Instance. You can specify the `log_name` of the log you wish to clean from your Database Instance.
func (s *API) PurgeInstanceLogs(req *PurgeInstanceLogsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/purge-logs",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListInstanceLogsDetails: List remote log details. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListInstanceLogsDetails(req *ListInstanceLogsDetailsRequest, opts ...scw.RequestOption) (*ListInstanceLogsDetailsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/logs-details",
}
var resp ListInstanceLogsDetailsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddInstanceSettings: Add an advanced setting to a Database Instance. You must set the `name` and the `value` of each setting.
func (s *API) AddInstanceSettings(req *AddInstanceSettingsRequest, opts ...scw.RequestOption) (*AddInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstanceSettings: Delete an advanced setting in a Database Instance. You must specify the names of the settings you want to delete in the request.
func (s *API) DeleteInstanceSettings(req *DeleteInstanceSettingsRequest, opts ...scw.RequestOption) (*DeleteInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DeleteInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetInstanceSettings: Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.
func (s *API) SetInstanceSettings(req *SetInstanceSettingsRequest, opts ...scw.RequestOption) (*SetInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstanceACLRules: List the ACL rules for a given Database Instance. The response is an array of ACL objects, each one representing an ACL that denies, allows or redirects traffic based on certain conditions.
func (s *API) ListInstanceACLRules(req *ListInstanceACLRulesRequest, opts ...scw.RequestOption) (*ListInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
Query: query,
}
var resp ListInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddInstanceACLRules: Add an additional ACL rule to a Database Instance.
func (s *API) AddInstanceACLRules(req *AddInstanceACLRulesRequest, opts ...scw.RequestOption) (*AddInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetInstanceACLRules: Replace all the ACL rules of a Database Instance.
func (s *API) SetInstanceACLRules(req *SetInstanceACLRulesRequest, opts ...scw.RequestOption) (*SetInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstanceACLRules: Delete one or more ACL rules of a Database Instance.
func (s *API) DeleteInstanceACLRules(req *DeleteInstanceACLRulesRequest, opts ...scw.RequestOption) (*DeleteInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DeleteInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListUsers: List all users of a given Database Instance. By default, the users returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListUsers(req *ListUsersRequest, opts ...scw.RequestOption) (*ListUsersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
Query: query,
}
var resp ListUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateUser: Create a new user for a Database Instance. You must define the `name`, `password` and `is_admin` parameters.
func (s *API) CreateUser(req *CreateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUser: Update the parameters of a user on a Database Instance. You can update the `password` and `is_admin` parameters, but you cannot change the name of the user.
func (s *API) UpdateUser(req *UpdateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return nil, errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteUser: Delete a given user on a Database Instance. You must specify, in the endpoint, the `region`, `instance_id` and `name` parameters of the user you want to delete.
func (s *API) DeleteUser(req *DeleteUserRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDatabases: List all databases of a given Database Instance. By default, the databases returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `name`, `managed` and `owner`.
func (s *API) ListDatabases(req *ListDatabasesRequest, opts ...scw.RequestOption) (*ListDatabasesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "managed", req.Managed)
parameter.AddToQuery(query, "owner", req.Owner)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases",
Query: query,
}
var resp ListDatabasesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDatabase: Create a new database. You must define the `name` parameter in the request.
func (s *API) CreateDatabase(req *CreateDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabase: Delete a given database on a Database Instance. You must specify, in the endpoint, the `region`, `instance_id` and `name` parameters of the database you want to delete.
func (s *API) DeleteDatabase(req *DeleteDatabaseRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases/" + fmt.Sprint(req.Name) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPrivileges: List privileges of a user on a database. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `database_name` and `user_name`.
func (s *API) ListPrivileges(req *ListPrivilegesRequest, opts ...scw.RequestOption) (*ListPrivilegesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "database_name", req.DatabaseName)
parameter.AddToQuery(query, "user_name", req.UserName)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/privileges",
Query: query,
}
var resp ListPrivilegesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPrivilege: Set the privileges of a user on a database. You must define `database_name`, `user_name` and `permission` in the request body.
func (s *API) SetPrivilege(req *SetPrivilegeRequest, opts ...scw.RequestOption) (*Privilege, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/privileges",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Privilege
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSnapshots: List snapshots. You can include the `instance_id` or `project_id` in your query to get the list of snapshots for specific Database Instances and/or Projects. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "instance_id", req.InstanceID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/snapshots",
Query: query,
}
var resp ListSnapshotsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnapshot: Retrieve information about a given snapshot, specified by its `snapshot_id` and `region`. Full details about the snapshot, like size and expiration date, are returned in the response.
func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnapshot: Create a new snapshot of a Database Instance. You must define the `name` parameter in the request.
func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("snp")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/snapshots",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSnapshot: Update the parameters of a snapshot of a Database Instance. You can update the `name` and `expires_at` parameters.
func (s *API) UpdateSnapshot(req *UpdateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnapshot: Delete a given snapshot of a Database Instance. You must specify, in the endpoint, the `region` and `snapshot_id` parameters of the snapshot you want to delete.
func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateInstanceFromSnapshot: Restore a snapshot. When you restore a snapshot, a new Instance is created and billed to your account. Note that is possible to select a larger node type for your new Database Instance. However, the Block volume size will be the same as the size of the restored snapshot. All Instance settings will be restored if you chose a node type with the same or more memory size than the initial Instance. Settings will be reset to the default if your node type has less memory.
func (s *API) CreateInstanceFromSnapshot(req *CreateInstanceFromSnapshotRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "/create-instance",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateEndpoint: Create a new endpoint for a Database Instance. You can add `load_balancer` and `private_network` specifications to the body of the request.
func (s *API) CreateEndpoint(req *CreateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteEndpoint: Delete the endpoint of a Database Instance. You must specify the `region` and `endpoint_id` parameters of the endpoint you want to delete. Note that might need to update any environment configurations that point to the deleted endpoint.
func (s *API) DeleteEndpoint(req *DeleteEndpointRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetEndpoint: Retrieve information about a Database Instance endpoint. Full details about the endpoint, like `ip`, `port`, `private_network` and `load_balancer` specifications are returned in the response.
func (s *API) GetEndpoint(req *GetEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// MigrateEndpoint: Migrate an existing Database Instance endpoint to another Database Instance.
func (s *API) MigrateEndpoint(req *MigrateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "/migrate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ApplyInstanceMaintenance: Apply a pending instance maintenance on your instance. This action can generate some service interruption.
func (s *API) ApplyInstanceMaintenance(req *ApplyInstanceMaintenanceRequest, opts ...scw.RequestOption) (*Maintenance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/document-db/v1beta1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/apply-maintenance",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Maintenance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/documentdb/v1beta1/documentdb_utils.go 0000664 0000000 0000000 00000010441 14747113137 0032277 0 ustar 00root root 0000000 0000000 package documentdb
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 15 * time.Minute
)
// WaitForInstanceRequest is used by WaitForInstance method.
type WaitForInstanceRequest struct {
InstanceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForInstance waits for the instance to be in a "terminal state" before returning.
// This function can be used to wait for an instance to be ready for example.
func (s *API) WaitForInstance(req *WaitForInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[InstanceStatus]struct{}{
InstanceStatusReady: {},
InstanceStatusDiskFull: {},
InstanceStatusError: {},
}
instance, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetInstance(&GetInstanceRequest{
InstanceID: req.InstanceID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for instance failed")
}
return instance.(*Instance), nil
}
type WaitForInstanceLogRequest struct {
InstanceLogID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForInstanceLog waits for the instance logs to be in a "terminal state" before returning.
// This function can be used to wait for an instance logs to be ready for example.
func (s *API) WaitForInstanceLog(req *WaitForInstanceLogRequest, opts ...scw.RequestOption) (*InstanceLog, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[InstanceLogStatus]struct{}{
InstanceLogStatusReady: {},
InstanceLogStatusError: {},
}
logs, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetInstanceLog(&GetInstanceLogRequest{
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for instance logs failed")
}
return logs.(*InstanceLog), nil
}
// WaitForReadReplicaRequest is used by WaitForReadReplica method.
type WaitForReadReplicaRequest struct {
ReadReplicaID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForReadReplica waits for the read replica to be in a "terminal state" before returning.
// This function can be used to wait for a read replica to be ready for example.
func (s *API) WaitForReadReplica(req *WaitForReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ReadReplicaStatus]struct{}{
ReadReplicaStatusReady: {},
ReadReplicaStatusError: {},
}
readReplica, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetReadReplica(&GetReadReplicaRequest{
ReadReplicaID: req.ReadReplicaID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for read replica failed")
}
return readReplica.(*ReadReplica), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/domain/ 0000775 0000000 0000000 00000000000 14747113137 0024264 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/domain/v2beta1/ 0000775 0000000 0000000 00000000000 14747113137 0025530 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/domain/v2beta1/domain_sdk.go 0000664 0000000 0000000 00000414530 14747113137 0030176 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package domain provides methods and message types of the domain v2beta1 API.
package domain
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
std "github.com/scaleway/scaleway-sdk-go/api/std"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ContactEmailStatus string
const (
// If unspecified, the status is unknown by default.
ContactEmailStatusEmailStatusUnknown = ContactEmailStatus("email_status_unknown")
// The contact email has been validated.
ContactEmailStatusValidated = ContactEmailStatus("validated")
// The contact email has not been validated.
ContactEmailStatusNotValidated = ContactEmailStatus("not_validated")
// The contact email is invalid.
ContactEmailStatusInvalidEmail = ContactEmailStatus("invalid_email")
)
func (enum ContactEmailStatus) String() string {
if enum == "" {
// return default value if empty
return "email_status_unknown"
}
return string(enum)
}
func (enum ContactEmailStatus) Values() []ContactEmailStatus {
return []ContactEmailStatus{
"email_status_unknown",
"validated",
"not_validated",
"invalid_email",
}
}
func (enum ContactEmailStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContactEmailStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContactEmailStatus(ContactEmailStatus(tmp).String())
return nil
}
type ContactExtensionFRMode string
const (
// If unspecified, the status is unknown by default.
ContactExtensionFRModeModeUnknown = ContactExtensionFRMode("mode_unknown")
// The contact is a physical person (only for .fr domains).
ContactExtensionFRModeIndividual = ContactExtensionFRMode("individual")
// The contact is a company with a SIRET/SIREN code (only for .fr domains).
ContactExtensionFRModeCompanyIdentificationCode = ContactExtensionFRMode("company_identification_code")
// The contact has a Data Universal Numbering System code (only for .fr domains).
ContactExtensionFRModeDuns = ContactExtensionFRMode("duns")
// The contact has a local or a country ID (only for .fr domains).
ContactExtensionFRModeLocal = ContactExtensionFRMode("local")
// The contact is an association (only for .fr domains).
ContactExtensionFRModeAssociation = ContactExtensionFRMode("association")
// The contact is a brand (only for .fr domains).
ContactExtensionFRModeTrademark = ContactExtensionFRMode("trademark")
// The contact has an intervention code (DSIA) from AFNIC (only for .fr domains).
ContactExtensionFRModeCodeAuthAfnic = ContactExtensionFRMode("code_auth_afnic")
)
func (enum ContactExtensionFRMode) String() string {
if enum == "" {
// return default value if empty
return "mode_unknown"
}
return string(enum)
}
func (enum ContactExtensionFRMode) Values() []ContactExtensionFRMode {
return []ContactExtensionFRMode{
"mode_unknown",
"individual",
"company_identification_code",
"duns",
"local",
"association",
"trademark",
"code_auth_afnic",
}
}
func (enum ContactExtensionFRMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContactExtensionFRMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContactExtensionFRMode(ContactExtensionFRMode(tmp).String())
return nil
}
type ContactExtensionNLLegalForm string
const (
// If unspecified, the status is unknown by default.
ContactExtensionNLLegalFormLegalFormUnknown = ContactExtensionNLLegalForm("legal_form_unknown")
// The contact's legal form is not listed below (only for .nl domains).
ContactExtensionNLLegalFormOther = ContactExtensionNLLegalForm("other")
// The contact is a non-Dutch EC company (only for .nl domains).
ContactExtensionNLLegalFormNonDutchEuCompany = ContactExtensionNLLegalForm("non_dutch_eu_company")
// The contact is a non-Dutch legal form/enterprise/subsidiary (only for .nl domains).
ContactExtensionNLLegalFormNonDutchLegalFormEnterpriseSubsidiary = ContactExtensionNLLegalForm("non_dutch_legal_form_enterprise_subsidiary")
// The contact is a limited company (only for .nl domains).
ContactExtensionNLLegalFormLimitedCompany = ContactExtensionNLLegalForm("limited_company")
// The contact is a limited company in formation (only for .nl domains).
ContactExtensionNLLegalFormLimitedCompanyInFormation = ContactExtensionNLLegalForm("limited_company_in_formation")
// The contact is a cooperative (only for .nl domains).
ContactExtensionNLLegalFormCooperative = ContactExtensionNLLegalForm("cooperative")
// The contact is a limited Partnership (only for .nl domains).
ContactExtensionNLLegalFormLimitedPartnership = ContactExtensionNLLegalForm("limited_partnership")
// The contact is a sole trader (only for .nl domains).
ContactExtensionNLLegalFormSoleCompany = ContactExtensionNLLegalForm("sole_company")
// The contact is a European Economic Interest Group (only for .nl domains).
ContactExtensionNLLegalFormEuropeanEconomicInterestGroup = ContactExtensionNLLegalForm("european_economic_interest_group")
// The contact is a religious society (only for .nl domains).
ContactExtensionNLLegalFormReligiousEntity = ContactExtensionNLLegalForm("religious_entity")
// The contact is a partnership (only for .nl domains).
ContactExtensionNLLegalFormPartnership = ContactExtensionNLLegalForm("partnership")
// The contact is a public Company (only for .nl domains).
ContactExtensionNLLegalFormPublicCompany = ContactExtensionNLLegalForm("public_company")
// The contact is a mutual benefit company (only for .nl domains).
ContactExtensionNLLegalFormMutualBenefitCompany = ContactExtensionNLLegalForm("mutual_benefit_company")
// The contact is a natural person (only for .nl domains).
ContactExtensionNLLegalFormResidential = ContactExtensionNLLegalForm("residential")
// The contact is a shipping company (only for .nl domains).
ContactExtensionNLLegalFormShippingCompany = ContactExtensionNLLegalForm("shipping_company")
// The contact is a foundation (only for .nl domains).
ContactExtensionNLLegalFormFoundation = ContactExtensionNLLegalForm("foundation")
// The contact is a association (only for .nl domains).
ContactExtensionNLLegalFormAssociation = ContactExtensionNLLegalForm("association")
// The contact is a trading partnership (only for .nl domains).
ContactExtensionNLLegalFormTradingPartnership = ContactExtensionNLLegalForm("trading_partnership")
// The contact is a physical person (only for .nl domains).
ContactExtensionNLLegalFormNaturalPerson = ContactExtensionNLLegalForm("natural_person")
)
func (enum ContactExtensionNLLegalForm) String() string {
if enum == "" {
// return default value if empty
return "legal_form_unknown"
}
return string(enum)
}
func (enum ContactExtensionNLLegalForm) Values() []ContactExtensionNLLegalForm {
return []ContactExtensionNLLegalForm{
"legal_form_unknown",
"other",
"non_dutch_eu_company",
"non_dutch_legal_form_enterprise_subsidiary",
"limited_company",
"limited_company_in_formation",
"cooperative",
"limited_partnership",
"sole_company",
"european_economic_interest_group",
"religious_entity",
"partnership",
"public_company",
"mutual_benefit_company",
"residential",
"shipping_company",
"foundation",
"association",
"trading_partnership",
"natural_person",
}
}
func (enum ContactExtensionNLLegalForm) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContactExtensionNLLegalForm) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContactExtensionNLLegalForm(ContactExtensionNLLegalForm(tmp).String())
return nil
}
type ContactLegalForm string
const (
// If unspecified, the status is unknown by default.
ContactLegalFormLegalFormUnknown = ContactLegalForm("legal_form_unknown")
// The contact is a physical person.
ContactLegalFormIndividual = ContactLegalForm("individual")
// The contact is a corporate or a society.
ContactLegalFormCorporate = ContactLegalForm("corporate")
// The contact is an association.
ContactLegalFormAssociation = ContactLegalForm("association")
// The contact is not represented by a physical person, a corporate or an association.
ContactLegalFormOther = ContactLegalForm("other")
)
func (enum ContactLegalForm) String() string {
if enum == "" {
// return default value if empty
return "legal_form_unknown"
}
return string(enum)
}
func (enum ContactLegalForm) Values() []ContactLegalForm {
return []ContactLegalForm{
"legal_form_unknown",
"individual",
"corporate",
"association",
"other",
}
}
func (enum ContactLegalForm) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContactLegalForm) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContactLegalForm(ContactLegalForm(tmp).String())
return nil
}
type ContactStatus string
const (
// If unspecified, the status is unknown by default.
ContactStatusStatusUnknown = ContactStatus("status_unknown")
// The contact is active and can be edited.
ContactStatusActive = ContactStatus("active")
// The contact is temporarily locked (ie. while being edited).
ContactStatusPending = ContactStatus("pending")
)
func (enum ContactStatus) String() string {
if enum == "" {
// return default value if empty
return "status_unknown"
}
return string(enum)
}
func (enum ContactStatus) Values() []ContactStatus {
return []ContactStatus{
"status_unknown",
"active",
"pending",
}
}
func (enum ContactStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ContactStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ContactStatus(ContactStatus(tmp).String())
return nil
}
type DNSZoneStatus string
const (
// If unspecified, the DNS zone's status is unknown by default.
DNSZoneStatusUnknown = DNSZoneStatus("unknown")
// The DNS zone is active and healthy.
DNSZoneStatusActive = DNSZoneStatus("active")
// The DNS zone is updating.
DNSZoneStatusPending = DNSZoneStatus("pending")
// An error occurred after updating the DNS zone.
DNSZoneStatusError = DNSZoneStatus("error")
// The DNS zone is locked and cannot be updated anymore.
DNSZoneStatusLocked = DNSZoneStatus("locked")
)
func (enum DNSZoneStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DNSZoneStatus) Values() []DNSZoneStatus {
return []DNSZoneStatus{
"unknown",
"active",
"pending",
"error",
"locked",
}
}
func (enum DNSZoneStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSZoneStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSZoneStatus(DNSZoneStatus(tmp).String())
return nil
}
type DSRecordAlgorithm string
const (
// Code 1, algorithm: 'RSAMD5'.
DSRecordAlgorithmRsamd5 = DSRecordAlgorithm("rsamd5")
// Code 2, algorithm: 'DIFFIE_HELLMAN'.
DSRecordAlgorithmDh = DSRecordAlgorithm("dh")
// Code 3, algorithm: 'DSA_SHA1'.
DSRecordAlgorithmDsa = DSRecordAlgorithm("dsa")
// Code 5, algorithm: 'RSA_SHA1'.
DSRecordAlgorithmRsasha1 = DSRecordAlgorithm("rsasha1")
// Code 6, algorithm: 'DSA_NSEC3_SHA1'.
DSRecordAlgorithmDsaNsec3Sha1 = DSRecordAlgorithm("dsa_nsec3_sha1")
// Code 7, algorithm: 'RSASHA1_NSEC3_SHA1'.
DSRecordAlgorithmRsasha1Nsec3Sha1 = DSRecordAlgorithm("rsasha1_nsec3_sha1")
// Code 8, algorithm: 'RSASHA256'.
DSRecordAlgorithmRsasha256 = DSRecordAlgorithm("rsasha256")
// Code 10, algorithm: 'RSASHA512'.
DSRecordAlgorithmRsasha512 = DSRecordAlgorithm("rsasha512")
// Code 12, algorithm: 'ECC_GOST'.
DSRecordAlgorithmEccGost = DSRecordAlgorithm("ecc_gost")
// Code 13, algorithm: 'ECDSAP256SHA256'.
DSRecordAlgorithmEcdsap256sha256 = DSRecordAlgorithm("ecdsap256sha256")
// Code 14, algorithm: 'ECDSAP384SHA384'.
DSRecordAlgorithmEcdsap384sha384 = DSRecordAlgorithm("ecdsap384sha384")
// Code 15, algorithm: 'ED25519'.
DSRecordAlgorithmEd25519 = DSRecordAlgorithm("ed25519")
// Code 16, algorithm: 'ED448'.
DSRecordAlgorithmEd448 = DSRecordAlgorithm("ed448")
)
func (enum DSRecordAlgorithm) String() string {
if enum == "" {
// return default value if empty
return "rsamd5"
}
return string(enum)
}
func (enum DSRecordAlgorithm) Values() []DSRecordAlgorithm {
return []DSRecordAlgorithm{
"rsamd5",
"dh",
"dsa",
"rsasha1",
"dsa_nsec3_sha1",
"rsasha1_nsec3_sha1",
"rsasha256",
"rsasha512",
"ecc_gost",
"ecdsap256sha256",
"ecdsap384sha384",
"ed25519",
"ed448",
}
}
func (enum DSRecordAlgorithm) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DSRecordAlgorithm) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DSRecordAlgorithm(DSRecordAlgorithm(tmp).String())
return nil
}
type DSRecordDigestType string
const (
// Code 1, digest type: 'SHA_1'.
DSRecordDigestTypeSha1 = DSRecordDigestType("sha_1")
// Code 2, digest type: 'SHA_256'.
DSRecordDigestTypeSha256 = DSRecordDigestType("sha_256")
// Code 3, digest type: 'GOST_R_34_11_94'.
DSRecordDigestTypeGostR34_11_94 = DSRecordDigestType("gost_r_34_11_94")
// Code 4, digest type: 'SHA_384'.
DSRecordDigestTypeSha384 = DSRecordDigestType("sha_384")
)
func (enum DSRecordDigestType) String() string {
if enum == "" {
// return default value if empty
return "sha_1"
}
return string(enum)
}
func (enum DSRecordDigestType) Values() []DSRecordDigestType {
return []DSRecordDigestType{
"sha_1",
"sha_256",
"gost_r_34_11_94",
"sha_384",
}
}
func (enum DSRecordDigestType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DSRecordDigestType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DSRecordDigestType(DSRecordDigestType(tmp).String())
return nil
}
type DomainFeatureStatus string
const (
// Default unknown status.
DomainFeatureStatusFeatureStatusUnknown = DomainFeatureStatus("feature_status_unknown")
// A feature (auto renew, DNSSEC) is being enabled.
DomainFeatureStatusEnabling = DomainFeatureStatus("enabling")
// A feature (auto renew, DNSSEC) has been enabled.
DomainFeatureStatusEnabled = DomainFeatureStatus("enabled")
// A feature (auto renew, DNSSEC) is being disabled.
DomainFeatureStatusDisabling = DomainFeatureStatus("disabling")
// A feature (auto renew, DNSSEC) has been disabled.
DomainFeatureStatusDisabled = DomainFeatureStatus("disabled")
)
func (enum DomainFeatureStatus) String() string {
if enum == "" {
// return default value if empty
return "feature_status_unknown"
}
return string(enum)
}
func (enum DomainFeatureStatus) Values() []DomainFeatureStatus {
return []DomainFeatureStatus{
"feature_status_unknown",
"enabling",
"enabled",
"disabling",
"disabled",
}
}
func (enum DomainFeatureStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainFeatureStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainFeatureStatus(DomainFeatureStatus(tmp).String())
return nil
}
type DomainRegistrationStatusTransferStatus string
const (
// If unspecified, the status is unknown by default.
DomainRegistrationStatusTransferStatusStatusUnknown = DomainRegistrationStatusTransferStatus("status_unknown")
// The domain transfer is being initialized.
DomainRegistrationStatusTransferStatusPending = DomainRegistrationStatusTransferStatus("pending")
// The domain transfer has started. The process can be accelerated if you accept the vote.
DomainRegistrationStatusTransferStatusWaitingVote = DomainRegistrationStatusTransferStatus("waiting_vote")
// The domain transfer has been rejected.
DomainRegistrationStatusTransferStatusRejected = DomainRegistrationStatusTransferStatus("rejected")
// The domain transfer has been accepted. Your resources are being created.
DomainRegistrationStatusTransferStatusProcessing = DomainRegistrationStatusTransferStatus("processing")
// The domain transfer is complete.
DomainRegistrationStatusTransferStatusDone = DomainRegistrationStatusTransferStatus("done")
)
func (enum DomainRegistrationStatusTransferStatus) String() string {
if enum == "" {
// return default value if empty
return "status_unknown"
}
return string(enum)
}
func (enum DomainRegistrationStatusTransferStatus) Values() []DomainRegistrationStatusTransferStatus {
return []DomainRegistrationStatusTransferStatus{
"status_unknown",
"pending",
"waiting_vote",
"rejected",
"processing",
"done",
}
}
func (enum DomainRegistrationStatusTransferStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainRegistrationStatusTransferStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainRegistrationStatusTransferStatus(DomainRegistrationStatusTransferStatus(tmp).String())
return nil
}
type DomainStatus string
const (
// If unspecified, the status is unknown by default.
DomainStatusStatusUnknown = DomainStatus("status_unknown")
// The domain is active.
DomainStatusActive = DomainStatus("active")
// The domain is in the process of being created.
DomainStatusCreating = DomainStatus("creating")
// An error occurred during the domain's creation process.
DomainStatusCreateError = DomainStatus("create_error")
// The domain is being renewed.
DomainStatusRenewing = DomainStatus("renewing")
// An error occurred during the domain's renewal process.
DomainStatusRenewError = DomainStatus("renew_error")
// The domain is being transferred to Scaleway Domains and DNS.
DomainStatusXfering = DomainStatus("xfering")
// An error occurred during the domain's transfer process.
DomainStatusXferError = DomainStatus("xfer_error")
// The domain is expired but it can be renewed.
DomainStatusExpired = DomainStatus("expired")
// The domain is expiring but it is still renewable.
DomainStatusExpiring = DomainStatus("expiring")
// The domain's information is updating.
DomainStatusUpdating = DomainStatus("updating")
// The external domain has not yet been validated. It will be automatically removed after 48 hours if it still has not been validated by then.
DomainStatusChecking = DomainStatus("checking")
// The domain is locked. Contact Scaleway's support team for more information.
DomainStatusLocked = DomainStatus("locked")
// The domain will be deleted soon. This process cannot be canceled.
DomainStatusDeleting = DomainStatus("deleting")
)
func (enum DomainStatus) String() string {
if enum == "" {
// return default value if empty
return "status_unknown"
}
return string(enum)
}
func (enum DomainStatus) Values() []DomainStatus {
return []DomainStatus{
"status_unknown",
"active",
"creating",
"create_error",
"renewing",
"renew_error",
"xfering",
"xfer_error",
"expired",
"expiring",
"updating",
"checking",
"locked",
"deleting",
}
}
func (enum DomainStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainStatus(DomainStatus(tmp).String())
return nil
}
type HostStatus string
const (
// If unspecified, the status is unknown by default.
HostStatusUnknownStatus = HostStatus("unknown_status")
// The host is active.
HostStatusActive = HostStatus("active")
// The host is being updated.
HostStatusUpdating = HostStatus("updating")
// The host is being deleted.
HostStatusDeleting = HostStatus("deleting")
)
func (enum HostStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum HostStatus) Values() []HostStatus {
return []HostStatus{
"unknown_status",
"active",
"updating",
"deleting",
}
}
func (enum HostStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HostStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HostStatus(HostStatus(tmp).String())
return nil
}
type LinkedProduct string
const (
// If unspecified, no Scaleway product uses the resources.
LinkedProductUnknownProduct = LinkedProduct("unknown_product")
// Resources are used by Scaleway VPC.
LinkedProductVpc = LinkedProduct("vpc")
)
func (enum LinkedProduct) String() string {
if enum == "" {
// return default value if empty
return "unknown_product"
}
return string(enum)
}
func (enum LinkedProduct) Values() []LinkedProduct {
return []LinkedProduct{
"unknown_product",
"vpc",
}
}
func (enum LinkedProduct) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LinkedProduct) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LinkedProduct(LinkedProduct(tmp).String())
return nil
}
type ListContactsRequestRole string
const (
ListContactsRequestRoleUnknownRole = ListContactsRequestRole("unknown_role")
// The contact is a domain's owner.
ListContactsRequestRoleOwner = ListContactsRequestRole("owner")
// The contact is a domain's administrative contact.
ListContactsRequestRoleAdministrative = ListContactsRequestRole("administrative")
// The contact is a domain's technical contact.
ListContactsRequestRoleTechnical = ListContactsRequestRole("technical")
)
func (enum ListContactsRequestRole) String() string {
if enum == "" {
// return default value if empty
return "unknown_role"
}
return string(enum)
}
func (enum ListContactsRequestRole) Values() []ListContactsRequestRole {
return []ListContactsRequestRole{
"unknown_role",
"owner",
"administrative",
"technical",
}
}
func (enum ListContactsRequestRole) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListContactsRequestRole) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListContactsRequestRole(ListContactsRequestRole(tmp).String())
return nil
}
type ListDNSZoneRecordsRequestOrderBy string
const (
// Order by record name (ascending).
ListDNSZoneRecordsRequestOrderByNameAsc = ListDNSZoneRecordsRequestOrderBy("name_asc")
// Order by record name (descending).
ListDNSZoneRecordsRequestOrderByNameDesc = ListDNSZoneRecordsRequestOrderBy("name_desc")
)
func (enum ListDNSZoneRecordsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListDNSZoneRecordsRequestOrderBy) Values() []ListDNSZoneRecordsRequestOrderBy {
return []ListDNSZoneRecordsRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListDNSZoneRecordsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDNSZoneRecordsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDNSZoneRecordsRequestOrderBy(ListDNSZoneRecordsRequestOrderBy(tmp).String())
return nil
}
type ListDNSZonesRequestOrderBy string
const (
// Order by domain name (ascending).
ListDNSZonesRequestOrderByDomainAsc = ListDNSZonesRequestOrderBy("domain_asc")
// Order by domain name (descending).
ListDNSZonesRequestOrderByDomainDesc = ListDNSZonesRequestOrderBy("domain_desc")
// Order by subdomain name (ascending).
ListDNSZonesRequestOrderBySubdomainAsc = ListDNSZonesRequestOrderBy("subdomain_asc")
// Order by subdomain name (descending).
ListDNSZonesRequestOrderBySubdomainDesc = ListDNSZonesRequestOrderBy("subdomain_desc")
// Order by created date (ascending).
ListDNSZonesRequestOrderByCreatedAtAsc = ListDNSZonesRequestOrderBy("created_at_asc")
// Order by created date (descending).
ListDNSZonesRequestOrderByCreatedAtDesc = ListDNSZonesRequestOrderBy("created_at_desc")
// Order by updated date (ascending).
ListDNSZonesRequestOrderByUpdatedAtAsc = ListDNSZonesRequestOrderBy("updated_at_asc")
// Order by updated date (descending).
ListDNSZonesRequestOrderByUpdatedAtDesc = ListDNSZonesRequestOrderBy("updated_at_desc")
)
func (enum ListDNSZonesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "domain_asc"
}
return string(enum)
}
func (enum ListDNSZonesRequestOrderBy) Values() []ListDNSZonesRequestOrderBy {
return []ListDNSZonesRequestOrderBy{
"domain_asc",
"domain_desc",
"subdomain_asc",
"subdomain_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListDNSZonesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDNSZonesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDNSZonesRequestOrderBy(ListDNSZonesRequestOrderBy(tmp).String())
return nil
}
type ListDomainsRequestOrderBy string
const (
// Order by domain name (ascending).
ListDomainsRequestOrderByDomainAsc = ListDomainsRequestOrderBy("domain_asc")
// Order by domain name (descending).
ListDomainsRequestOrderByDomainDesc = ListDomainsRequestOrderBy("domain_desc")
)
func (enum ListDomainsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "domain_asc"
}
return string(enum)
}
func (enum ListDomainsRequestOrderBy) Values() []ListDomainsRequestOrderBy {
return []ListDomainsRequestOrderBy{
"domain_asc",
"domain_desc",
}
}
func (enum ListDomainsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDomainsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDomainsRequestOrderBy(ListDomainsRequestOrderBy(tmp).String())
return nil
}
type ListRenewableDomainsRequestOrderBy string
const (
// Order by domain name (ascending).
ListRenewableDomainsRequestOrderByDomainAsc = ListRenewableDomainsRequestOrderBy("domain_asc")
// Order by domain name (descending).
ListRenewableDomainsRequestOrderByDomainDesc = ListRenewableDomainsRequestOrderBy("domain_desc")
)
func (enum ListRenewableDomainsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "domain_asc"
}
return string(enum)
}
func (enum ListRenewableDomainsRequestOrderBy) Values() []ListRenewableDomainsRequestOrderBy {
return []ListRenewableDomainsRequestOrderBy{
"domain_asc",
"domain_desc",
}
}
func (enum ListRenewableDomainsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRenewableDomainsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRenewableDomainsRequestOrderBy(ListRenewableDomainsRequestOrderBy(tmp).String())
return nil
}
type ListTasksRequestOrderBy string
const (
// Order by domain name (descending).
ListTasksRequestOrderByDomainDesc = ListTasksRequestOrderBy("domain_desc")
// Order by domain name (ascending).
ListTasksRequestOrderByDomainAsc = ListTasksRequestOrderBy("domain_asc")
// Order by type (ascending).
ListTasksRequestOrderByTypeAsc = ListTasksRequestOrderBy("type_asc")
// Order by type (descending).
ListTasksRequestOrderByTypeDesc = ListTasksRequestOrderBy("type_desc")
// Order by status (ascending).
ListTasksRequestOrderByStatusAsc = ListTasksRequestOrderBy("status_asc")
// Order by status (descending).
ListTasksRequestOrderByStatusDesc = ListTasksRequestOrderBy("status_desc")
// Order by updated date (ascending).
ListTasksRequestOrderByUpdatedAtAsc = ListTasksRequestOrderBy("updated_at_asc")
// Order by updated date (descending).
ListTasksRequestOrderByUpdatedAtDesc = ListTasksRequestOrderBy("updated_at_desc")
)
func (enum ListTasksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "domain_desc"
}
return string(enum)
}
func (enum ListTasksRequestOrderBy) Values() []ListTasksRequestOrderBy {
return []ListTasksRequestOrderBy{
"domain_desc",
"domain_asc",
"type_asc",
"type_desc",
"status_asc",
"status_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListTasksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTasksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTasksRequestOrderBy(ListTasksRequestOrderBy(tmp).String())
return nil
}
type ListTldsRequestOrderBy string
const (
// Order by TLD name (ascending).
ListTldsRequestOrderByNameAsc = ListTldsRequestOrderBy("name_asc")
// Order by TLD name (descending).
ListTldsRequestOrderByNameDesc = ListTldsRequestOrderBy("name_desc")
)
func (enum ListTldsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListTldsRequestOrderBy) Values() []ListTldsRequestOrderBy {
return []ListTldsRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListTldsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTldsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTldsRequestOrderBy(ListTldsRequestOrderBy(tmp).String())
return nil
}
type RawFormat string
const (
// If unspecified, the format is unknown by default.
RawFormatUnknownRawFormat = RawFormat("unknown_raw_format")
// Export the DNS zone in text bind format.
RawFormatBind = RawFormat("bind")
)
func (enum RawFormat) String() string {
if enum == "" {
// return default value if empty
return "unknown_raw_format"
}
return string(enum)
}
func (enum RawFormat) Values() []RawFormat {
return []RawFormat{
"unknown_raw_format",
"bind",
}
}
func (enum RawFormat) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RawFormat) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RawFormat(RawFormat(tmp).String())
return nil
}
type RecordHTTPServiceConfigStrategy string
const (
// Returns a random IP based of the list of IPs available.
RecordHTTPServiceConfigStrategyRandom = RecordHTTPServiceConfigStrategy("random")
// Based on the hash of bestwho, returns a random functioning IP out of the best IPs available.
RecordHTTPServiceConfigStrategyHashed = RecordHTTPServiceConfigStrategy("hashed")
// Return all functioning IPs available.
RecordHTTPServiceConfigStrategyAll = RecordHTTPServiceConfigStrategy("all")
)
func (enum RecordHTTPServiceConfigStrategy) String() string {
if enum == "" {
// return default value if empty
return "random"
}
return string(enum)
}
func (enum RecordHTTPServiceConfigStrategy) Values() []RecordHTTPServiceConfigStrategy {
return []RecordHTTPServiceConfigStrategy{
"random",
"hashed",
"all",
}
}
func (enum RecordHTTPServiceConfigStrategy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RecordHTTPServiceConfigStrategy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RecordHTTPServiceConfigStrategy(RecordHTTPServiceConfigStrategy(tmp).String())
return nil
}
type RecordType string
const (
// If unspecified, the record's type is unknown by default.
RecordTypeUnknown = RecordType("unknown")
// An A record contains an IP address. Example: '203.0.113.210'.
RecordTypeA = RecordType("A")
// An AAAA record contains an IPv6 address. Example: '2001:DB8:2000:bf0::1'.
RecordTypeAAAA = RecordType("AAAA")
// A CNAME record specifies the canonical name of a record. Example 'webserver-01.yourcompany.com'.
RecordTypeCNAME = RecordType("CNAME")
// A TXT record can be used to attach textual data to a domain. Example 'v=spf1 include:_spf.tem.scw.cloud -all'.
RecordTypeTXT = RecordType("TXT")
// SRV records can be used to encode the location and port of services on a domain name. Example : '20 443 sipdir.scaleway.example.com'.
RecordTypeSRV = RecordType("SRV")
// TLSA records are used to bind SSL/TLS certificates to named hosts and ports.
RecordTypeTLSA = RecordType("TLSA")
// An MX record specifies a mail exchanger host for a domain. Example '10 mx.example.net.'.
RecordTypeMX = RecordType("MX")
// Specifies nameservers for a domain. Example: 'ns1.yourcompany.com'.
RecordTypeNS = RecordType("NS")
// A reverse pointer is used to specify the hostname that belongs to an IP or an IPv6 address. Example: 'www.yourcompany.com.'.
RecordTypePTR = RecordType("PTR")
// A 'Certification Authority Authorization' record is used to specify certificate authorities that may issue certificates for a domain. Example: '0 issue ca.yourcompany.com'.
RecordTypeCAA = RecordType("CAA")
// The ALIAS pseudo-record type is supported to provide CNAME-like mechanisms on a zone's apex.
RecordTypeALIAS = RecordType("ALIAS")
// A LOC record is a way of expressing geographic location information for a domain name. It contains WGS84 latitude, longitude and altitude. Example: '51 56 0.123 N 5 54 0.000 E 4.00m 1.00m 10000.00m 10.00m'.
RecordTypeLOC = RecordType("LOC")
// An SSHFP record type is used for storing Secure Shell (SSH) fingerprints. Example: '2 1 123456789abcdef67890123456789abcdef67890'.
RecordTypeSSHFP = RecordType("SSHFP")
// A Hardware Info record is used to specify the CPU and operating system you are using. Example: 'i386 Linux'.
RecordTypeHINFO = RecordType("HINFO")
// A Responsible Person record stores the mailbox name and the more-information pointer. Example: 'michel.yourcompany.com michel.people.yourcompany.com', to indicate that michel@yourcompany.com is responsible and that more information about Michel is available by querying the `TXT` record of 'michel.people.yourcompany.com'.
RecordTypeRP = RecordType("RP")
// A URI record, is used to publish mappings from hostnames to URIs. Example: '10 1 'ftp://ftp.yourcompany.com/public'.
RecordTypeURI = RecordType("URI")
// DS records (Delegation Signer) are used to secure delegations (DNSSEC). Example: '2371 13 2 1F987CC6583E92DF0890718C42'.
RecordTypeDS = RecordType("DS")
// A Naming Authority Pointer record is used to set rules for how websites process requests. Example: '100 50 "s" "z3950+I2L+I2C" "" _z3950._tcp.yourcompany.com'.
RecordTypeNAPTR = RecordType("NAPTR")
// A DNAME record provides redirection from one part of the DNS name tree to another part of the DNS name tree. DNAME and CNAME records both cause a lookup to (potentially) return data corresponding to a different domain name from the queried domain name. Example: 'yourcompany.com'.
RecordTypeDNAME = RecordType("DNAME")
// A SVCB (Service Binding) record provides information about a service endpoint associated with a domain name.
RecordTypeSVCB = RecordType("SVCB")
// An HTTPS record is a special type of SVCB record for HTTPS service endpoints.
RecordTypeHTTPS = RecordType("HTTPS")
)
func (enum RecordType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RecordType) Values() []RecordType {
return []RecordType{
"unknown",
"A",
"AAAA",
"CNAME",
"TXT",
"SRV",
"TLSA",
"MX",
"NS",
"PTR",
"CAA",
"ALIAS",
"LOC",
"SSHFP",
"HINFO",
"RP",
"URI",
"DS",
"NAPTR",
"DNAME",
"SVCB",
"HTTPS",
}
}
func (enum RecordType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RecordType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RecordType(RecordType(tmp).String())
return nil
}
type RenewableDomainStatus string
const (
// If unspecified, the status is unknown by default.
RenewableDomainStatusUnknown = RenewableDomainStatus("unknown")
// The domain can be renewed.
RenewableDomainStatusRenewable = RenewableDomainStatus("renewable")
// The domain is expired, but it still can be late renewed.
RenewableDomainStatusLateReneweable = RenewableDomainStatus("late_reneweable")
// The domain cannot be renewed.
RenewableDomainStatusNotRenewable = RenewableDomainStatus("not_renewable")
)
func (enum RenewableDomainStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RenewableDomainStatus) Values() []RenewableDomainStatus {
return []RenewableDomainStatus{
"unknown",
"renewable",
"late_reneweable",
"not_renewable",
}
}
func (enum RenewableDomainStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RenewableDomainStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RenewableDomainStatus(RenewableDomainStatus(tmp).String())
return nil
}
type SSLCertificateStatus string
const (
// If unspecified, the SSL certificate's status is unknown by default.
SSLCertificateStatusUnknown = SSLCertificateStatus("unknown")
// The SSL certificate has been created but it has not been processed yet.
SSLCertificateStatusNew = SSLCertificateStatus("new")
// The SSL certificate's status is pending.
SSLCertificateStatusPending = SSLCertificateStatus("pending")
// The SSL certificate has been created and processed.
SSLCertificateStatusSuccess = SSLCertificateStatus("success")
// An error occurred during the SSL certificate's creation.
SSLCertificateStatusError = SSLCertificateStatus("error")
)
func (enum SSLCertificateStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum SSLCertificateStatus) Values() []SSLCertificateStatus {
return []SSLCertificateStatus{
"unknown",
"new",
"pending",
"success",
"error",
}
}
func (enum SSLCertificateStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SSLCertificateStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SSLCertificateStatus(SSLCertificateStatus(tmp).String())
return nil
}
type TaskStatus string
const (
// If unspecified, the status is unavailable by default.
TaskStatusUnavailable = TaskStatus("unavailable")
// The task has been created but it has not yet started.
TaskStatusNew = TaskStatus("new")
// The task is waiting for a payment to be validated.
TaskStatusWaitingPayment = TaskStatus("waiting_payment")
// The task is pending.
TaskStatusPending = TaskStatus("pending")
// The task has been completed.
TaskStatusSuccess = TaskStatus("success")
// The task is in an error state.
TaskStatusError = TaskStatus("error")
)
func (enum TaskStatus) String() string {
if enum == "" {
// return default value if empty
return "unavailable"
}
return string(enum)
}
func (enum TaskStatus) Values() []TaskStatus {
return []TaskStatus{
"unavailable",
"new",
"waiting_payment",
"pending",
"success",
"error",
}
}
func (enum TaskStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TaskStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TaskStatus(TaskStatus(tmp).String())
return nil
}
type TaskType string
const (
// If unspecified, the status is unknown by default.
TaskTypeUnknown = TaskType("unknown")
// Create a new internal domain.
TaskTypeCreateDomain = TaskType("create_domain")
// Create a new external domain.
TaskTypeCreateExternalDomain = TaskType("create_external_domain")
// Renew a domain.
TaskTypeRenewDomain = TaskType("renew_domain")
// Transfer a domain to Scaleway Domains and DNS.
TaskTypeTransferDomain = TaskType("transfer_domain")
// Trade a domain to a new owner.
TaskTypeTradeDomain = TaskType("trade_domain")
// Lock the transfer of a domain for protection.
TaskTypeLockDomainTransfer = TaskType("lock_domain_transfer")
// Unlock the transfer of a domain.
TaskTypeUnlockDomainTransfer = TaskType("unlock_domain_transfer")
// Enable DNSSEC for a domain.
TaskTypeEnableDnssec = TaskType("enable_dnssec")
// Disable DNSSEC for a domain.
TaskTypeDisableDnssec = TaskType("disable_dnssec")
// Update the domain's information.
TaskTypeUpdateDomain = TaskType("update_domain")
// Change the technical or administrative contact.
TaskTypeUpdateContact = TaskType("update_contact")
// Delete a domain and destroy its zone versions, zones, and SSL certificates.
TaskTypeDeleteDomain = TaskType("delete_domain")
// Cancel a task that has not yet started.
TaskTypeCancelTask = TaskType("cancel_task")
// Generate a new SSL certificate.
TaskTypeGenerateSslCertificate = TaskType("generate_ssl_certificate")
// Renew an SSL certificate.
TaskTypeRenewSslCertificate = TaskType("renew_ssl_certificate")
// Send a message. For most cases, it will be followed by an email.
TaskTypeSendMessage = TaskType("send_message")
// Delete a domain that has expired and not been restored for at least 3 months.
TaskTypeDeleteDomainExpired = TaskType("delete_domain_expired")
// Delete a newly registered external domain that has not been validated after 48 hours or when the external domain fails to point to our name servers for more than 14 days.
TaskTypeDeleteExternalDomain = TaskType("delete_external_domain")
// Create domain's hostname with glue IPs.
TaskTypeCreateHost = TaskType("create_host")
// Update domain's hostname with glue IPs.
TaskTypeUpdateHost = TaskType("update_host")
// Delete domain's hostname.
TaskTypeDeleteHost = TaskType("delete_host")
// Move a domain to another Project.
TaskTypeMoveProject = TaskType("move_project")
// Transfer a domain from Online to Scaleway Domains and DNS.
TaskTypeTransferOnlineDomain = TaskType("transfer_online_domain")
)
func (enum TaskType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum TaskType) Values() []TaskType {
return []TaskType{
"unknown",
"create_domain",
"create_external_domain",
"renew_domain",
"transfer_domain",
"trade_domain",
"lock_domain_transfer",
"unlock_domain_transfer",
"enable_dnssec",
"disable_dnssec",
"update_domain",
"update_contact",
"delete_domain",
"cancel_task",
"generate_ssl_certificate",
"renew_ssl_certificate",
"send_message",
"delete_domain_expired",
"delete_external_domain",
"create_host",
"update_host",
"delete_host",
"move_project",
"transfer_online_domain",
}
}
func (enum TaskType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TaskType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TaskType(TaskType(tmp).String())
return nil
}
// RecordGeoIPConfigMatch: record geo ip config match.
type RecordGeoIPConfigMatch struct {
Countries []string `json:"countries"`
Continents []string `json:"continents"`
Data string `json:"data"`
}
// RecordViewConfigView: record view config view.
type RecordViewConfigView struct {
Subnet string `json:"subnet"`
Data string `json:"data"`
}
// RecordWeightedConfigWeightedIP: record weighted config weighted ip.
type RecordWeightedConfigWeightedIP struct {
IP net.IP `json:"ip"`
Weight uint32 `json:"weight"`
}
// DSRecordPublicKey: ds record public key.
type DSRecordPublicKey struct {
Key string `json:"key"`
}
// RecordGeoIPConfig: record geo ip config.
type RecordGeoIPConfig struct {
Matches []*RecordGeoIPConfigMatch `json:"matches"`
Default string `json:"default"`
}
// RecordHTTPServiceConfig: record http service config.
type RecordHTTPServiceConfig struct {
IPs []net.IP `json:"ips"`
MustContain *string `json:"must_contain"`
URL string `json:"url"`
UserAgent *string `json:"user_agent"`
// Strategy: default value: random
Strategy RecordHTTPServiceConfigStrategy `json:"strategy"`
}
// RecordViewConfig: record view config.
type RecordViewConfig struct {
Views []*RecordViewConfigView `json:"views"`
}
// RecordWeightedConfig: record weighted config.
type RecordWeightedConfig struct {
WeightedIPs []*RecordWeightedConfigWeightedIP `json:"weighted_ips"`
}
// ContactExtensionFRAssociationInfo: contact extension fr association info.
type ContactExtensionFRAssociationInfo struct {
PublicationJo *time.Time `json:"publication_jo"`
PublicationJoPage uint32 `json:"publication_jo_page"`
}
// ContactExtensionFRCodeAuthAfnicInfo: contact extension fr code auth afnic info.
type ContactExtensionFRCodeAuthAfnicInfo struct {
CodeAuthAfnic string `json:"code_auth_afnic"`
}
// ContactExtensionFRDunsInfo: contact extension fr duns info.
type ContactExtensionFRDunsInfo struct {
DunsID string `json:"duns_id"`
LocalID string `json:"local_id"`
}
// ContactExtensionFRIndividualInfo: contact extension fr individual info.
type ContactExtensionFRIndividualInfo struct {
WhoisOptIn bool `json:"whois_opt_in"`
}
// ContactExtensionFRTrademarkInfo: contact extension fr trademark info.
type ContactExtensionFRTrademarkInfo struct {
TrademarkInpi string `json:"trademark_inpi"`
}
// DSRecordDigest: ds record digest.
type DSRecordDigest struct {
// Type: default value: sha_1
Type DSRecordDigestType `json:"type"`
Digest string `json:"digest"`
PublicKey *DSRecordPublicKey `json:"public_key"`
}
// Record: record.
type Record struct {
Data string `json:"data"`
Name string `json:"name"`
Priority uint32 `json:"priority"`
TTL uint32 `json:"ttl"`
// Type: default value: unknown
Type RecordType `json:"type"`
Comment *string `json:"comment"`
// Precisely one of GeoIPConfig, HTTPServiceConfig, WeightedConfig, ViewConfig must be set.
GeoIPConfig *RecordGeoIPConfig `json:"geo_ip_config,omitempty"`
// Precisely one of GeoIPConfig, HTTPServiceConfig, WeightedConfig, ViewConfig must be set.
HTTPServiceConfig *RecordHTTPServiceConfig `json:"http_service_config,omitempty"`
// Precisely one of GeoIPConfig, HTTPServiceConfig, WeightedConfig, ViewConfig must be set.
WeightedConfig *RecordWeightedConfig `json:"weighted_config,omitempty"`
// Precisely one of GeoIPConfig, HTTPServiceConfig, WeightedConfig, ViewConfig must be set.
ViewConfig *RecordViewConfig `json:"view_config,omitempty"`
ID string `json:"id"`
}
// RecordIdentifier: record identifier.
type RecordIdentifier struct {
Name string `json:"name"`
// Type: default value: unknown
Type RecordType `json:"type"`
Data *string `json:"data"`
TTL *uint32 `json:"ttl"`
}
// ContactExtensionEU: contact extension eu.
type ContactExtensionEU struct {
EuropeanCitizenship string `json:"european_citizenship"`
}
// ContactExtensionFR: contact extension fr.
type ContactExtensionFR struct {
// Mode: default value: mode_unknown
Mode ContactExtensionFRMode `json:"mode"`
// Precisely one of IndividualInfo, DunsInfo, AssociationInfo, TrademarkInfo, CodeAuthAfnicInfo must be set.
IndividualInfo *ContactExtensionFRIndividualInfo `json:"individual_info,omitempty"`
// Precisely one of IndividualInfo, DunsInfo, AssociationInfo, TrademarkInfo, CodeAuthAfnicInfo must be set.
DunsInfo *ContactExtensionFRDunsInfo `json:"duns_info,omitempty"`
// Precisely one of IndividualInfo, DunsInfo, AssociationInfo, TrademarkInfo, CodeAuthAfnicInfo must be set.
AssociationInfo *ContactExtensionFRAssociationInfo `json:"association_info,omitempty"`
// Precisely one of IndividualInfo, DunsInfo, AssociationInfo, TrademarkInfo, CodeAuthAfnicInfo must be set.
TrademarkInfo *ContactExtensionFRTrademarkInfo `json:"trademark_info,omitempty"`
// Precisely one of IndividualInfo, DunsInfo, AssociationInfo, TrademarkInfo, CodeAuthAfnicInfo must be set.
CodeAuthAfnicInfo *ContactExtensionFRCodeAuthAfnicInfo `json:"code_auth_afnic_info,omitempty"`
}
// ContactExtensionNL: contact extension nl.
type ContactExtensionNL struct {
// LegalForm: default value: legal_form_unknown
LegalForm ContactExtensionNLLegalForm `json:"legal_form"`
LegalFormRegistrationNumber string `json:"legal_form_registration_number"`
}
// ContactQuestion: contact question.
type ContactQuestion struct {
Question string `json:"question"`
Answer string `json:"answer"`
}
// TldOffer: tld offer.
type TldOffer struct {
Action string `json:"action"`
OperationPath string `json:"operation_path"`
Price *scw.Money `json:"price"`
}
// DSRecord: ds record.
type DSRecord struct {
KeyID uint32 `json:"key_id"`
// Algorithm: default value: rsamd5
Algorithm DSRecordAlgorithm `json:"algorithm"`
// Precisely one of Digest, PublicKey must be set.
Digest *DSRecordDigest `json:"digest,omitempty"`
// Precisely one of Digest, PublicKey must be set.
PublicKey *DSRecordPublicKey `json:"public_key,omitempty"`
}
// RecordChangeAdd: record change add.
type RecordChangeAdd struct {
Records []*Record `json:"records"`
}
// RecordChangeClear: record change clear.
type RecordChangeClear struct {
}
// RecordChangeDelete: record change delete.
type RecordChangeDelete struct {
// Precisely one of ID, IDFields must be set.
ID *string `json:"id,omitempty"`
// Precisely one of ID, IDFields must be set.
IDFields *RecordIdentifier `json:"id_fields,omitempty"`
}
// RecordChangeSet: record change set.
type RecordChangeSet struct {
// Precisely one of ID, IDFields must be set.
ID *string `json:"id,omitempty"`
// Precisely one of ID, IDFields must be set.
IDFields *RecordIdentifier `json:"id_fields,omitempty"`
Records []*Record `json:"records"`
}
// ImportRawDNSZoneRequestTsigKey: import raw dns zone request tsig key.
type ImportRawDNSZoneRequestTsigKey struct {
Name string `json:"name"`
Key string `json:"key"`
Algorithm string `json:"algorithm"`
}
// Contact: contact.
type Contact struct {
ID string `json:"id"`
// LegalForm: default value: legal_form_unknown
LegalForm ContactLegalForm `json:"legal_form"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
CompanyName string `json:"company_name"`
Email string `json:"email"`
EmailAlt string `json:"email_alt"`
PhoneNumber string `json:"phone_number"`
FaxNumber string `json:"fax_number"`
AddressLine1 string `json:"address_line_1"`
AddressLine2 string `json:"address_line_2"`
Zip string `json:"zip"`
City string `json:"city"`
Country string `json:"country"`
VatIDentificationCode string `json:"vat_identification_code"`
CompanyIDentificationCode string `json:"company_identification_code"`
// Lang: default value: unknown_language_code
Lang std.LanguageCode `json:"lang"`
Resale bool `json:"resale"`
// Deprecated
Questions *[]*ContactQuestion `json:"questions,omitempty"`
ExtensionFr *ContactExtensionFR `json:"extension_fr"`
ExtensionEu *ContactExtensionEU `json:"extension_eu"`
WhoisOptIn bool `json:"whois_opt_in"`
// EmailStatus: default value: email_status_unknown
EmailStatus ContactEmailStatus `json:"email_status"`
State string `json:"state"`
ExtensionNl *ContactExtensionNL `json:"extension_nl"`
// Status: default value: status_unknown
Status ContactStatus `json:"status"`
}
// ContactRolesRoles: contact roles roles.
type ContactRolesRoles struct {
IsOwner bool `json:"is_owner"`
IsAdministrative bool `json:"is_administrative"`
IsTechnical bool `json:"is_technical"`
}
// DomainRegistrationStatusExternalDomain: domain registration status external domain.
type DomainRegistrationStatusExternalDomain struct {
ValidationToken string `json:"validation_token"`
}
// DomainRegistrationStatusTransfer: domain registration status transfer.
type DomainRegistrationStatusTransfer struct {
// Status: default value: status_unknown
Status DomainRegistrationStatusTransferStatus `json:"status"`
VoteCurrentOwner bool `json:"vote_current_owner"`
VoteNewOwner bool `json:"vote_new_owner"`
}
// Tld: tld.
type Tld struct {
Name string `json:"name"`
DnssecSupport bool `json:"dnssec_support"`
DurationInYearsMin uint32 `json:"duration_in_years_min"`
DurationInYearsMax uint32 `json:"duration_in_years_max"`
IDnSupport bool `json:"idn_support"`
Offers map[string]*TldOffer `json:"offers"`
Specifications map[string]string `json:"specifications"`
}
// NewContact: new contact.
type NewContact struct {
// LegalForm: default value: legal_form_unknown
LegalForm ContactLegalForm `json:"legal_form"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
CompanyName *string `json:"company_name"`
Email string `json:"email"`
EmailAlt *string `json:"email_alt"`
PhoneNumber string `json:"phone_number"`
FaxNumber *string `json:"fax_number"`
AddressLine1 string `json:"address_line_1"`
AddressLine2 *string `json:"address_line_2"`
Zip string `json:"zip"`
City string `json:"city"`
Country string `json:"country"`
VatIDentificationCode *string `json:"vat_identification_code"`
CompanyIDentificationCode *string `json:"company_identification_code"`
// Lang: default value: unknown_language_code
Lang std.LanguageCode `json:"lang"`
Resale bool `json:"resale"`
// Deprecated
Questions *[]*ContactQuestion `json:"questions,omitempty"`
ExtensionFr *ContactExtensionFR `json:"extension_fr"`
ExtensionEu *ContactExtensionEU `json:"extension_eu"`
WhoisOptIn bool `json:"whois_opt_in"`
State *string `json:"state"`
ExtensionNl *ContactExtensionNL `json:"extension_nl"`
}
// CheckContactsCompatibilityResponseContactCheckResult: check contacts compatibility response contact check result.
type CheckContactsCompatibilityResponseContactCheckResult struct {
Compatible bool `json:"compatible"`
ErrorMessage *string `json:"error_message"`
}
// DNSZone: dns zone.
type DNSZone struct {
Domain string `json:"domain"`
Subdomain string `json:"subdomain"`
Ns []string `json:"ns"`
NsDefault []string `json:"ns_default"`
NsMaster []string `json:"ns_master"`
// Status: default value: unknown
Status DNSZoneStatus `json:"status"`
Message *string `json:"message"`
UpdatedAt *time.Time `json:"updated_at"`
ProjectID string `json:"project_id"`
LinkedProducts []LinkedProduct `json:"linked_products"`
}
// DomainDNSSEC: domain dnssec.
type DomainDNSSEC struct {
// Status: default value: feature_status_unknown
Status DomainFeatureStatus `json:"status"`
DsRecords []*DSRecord `json:"ds_records"`
}
// RecordChange: record change.
type RecordChange struct {
// Precisely one of Add, Set, Delete, Clear must be set.
Add *RecordChangeAdd `json:"add,omitempty"`
// Precisely one of Add, Set, Delete, Clear must be set.
Set *RecordChangeSet `json:"set,omitempty"`
// Precisely one of Add, Set, Delete, Clear must be set.
Delete *RecordChangeDelete `json:"delete,omitempty"`
// Precisely one of Add, Set, Delete, Clear must be set.
Clear *RecordChangeClear `json:"clear,omitempty"`
}
// ImportProviderDNSZoneRequestOnlineV1: import provider dns zone request online v1.
type ImportProviderDNSZoneRequestOnlineV1 struct {
Token string `json:"token"`
}
// ImportRawDNSZoneRequestAXFRSource: import raw dns zone request axfr source.
type ImportRawDNSZoneRequestAXFRSource struct {
NameServer string `json:"name_server"`
TsigKey *ImportRawDNSZoneRequestTsigKey `json:"tsig_key"`
}
// ImportRawDNSZoneRequestBindSource: import raw dns zone request bind source.
type ImportRawDNSZoneRequestBindSource struct {
Content string `json:"content"`
}
// ContactRoles: contact roles.
type ContactRoles struct {
Contact *Contact `json:"contact"`
Roles map[string]*ContactRolesRoles `json:"roles"`
}
// Nameserver: nameserver.
type Nameserver struct {
Name string `json:"name"`
IP []string `json:"ip"`
}
// DNSZoneVersion: dns zone version.
type DNSZoneVersion struct {
ID string `json:"id"`
CreatedAt *time.Time `json:"created_at"`
}
// Host: host.
type Host struct {
Domain string `json:"domain"`
Name string `json:"name"`
IPs []net.IP `json:"ips"`
// Status: default value: unknown_status
Status HostStatus `json:"status"`
}
// DomainSummary: domain summary.
type DomainSummary struct {
Domain string `json:"domain"`
ProjectID string `json:"project_id"`
// AutoRenewStatus: default value: feature_status_unknown
AutoRenewStatus DomainFeatureStatus `json:"auto_renew_status"`
// DnssecStatus: default value: feature_status_unknown
DnssecStatus DomainFeatureStatus `json:"dnssec_status"`
EppCode []string `json:"epp_code"`
ExpiredAt *time.Time `json:"expired_at"`
UpdatedAt *time.Time `json:"updated_at"`
Registrar string `json:"registrar"`
IsExternal bool `json:"is_external"`
// Status: default value: status_unknown
Status DomainStatus `json:"status"`
// Precisely one of ExternalDomainRegistrationStatus, TransferRegistrationStatus must be set.
ExternalDomainRegistrationStatus *DomainRegistrationStatusExternalDomain `json:"external_domain_registration_status,omitempty"`
// Precisely one of ExternalDomainRegistrationStatus, TransferRegistrationStatus must be set.
TransferRegistrationStatus *DomainRegistrationStatusTransfer `json:"transfer_registration_status,omitempty"`
OrganizationID string `json:"organization_id"`
CreatedAt *time.Time `json:"created_at"`
PendingTrade bool `json:"pending_trade"`
}
// RenewableDomain: renewable domain.
type RenewableDomain struct {
Domain string `json:"domain"`
ProjectID string `json:"project_id"`
OrganizationID string `json:"organization_id"`
// Status: default value: unknown
Status RenewableDomainStatus `json:"status"`
RenewableDurationInYears *int32 `json:"renewable_duration_in_years"`
ExpiredAt *time.Time `json:"expired_at"`
LimitRenewAt *time.Time `json:"limit_renew_at"`
LimitRedemptionAt *time.Time `json:"limit_redemption_at"`
EstimatedDeleteAt *time.Time `json:"estimated_delete_at"`
Tld *Tld `json:"tld"`
}
// SSLCertificate: ssl certificate.
type SSLCertificate struct {
DNSZone string `json:"dns_zone"`
AlternativeDNSZones []string `json:"alternative_dns_zones"`
// Status: default value: unknown
Status SSLCertificateStatus `json:"status"`
PrivateKey string `json:"private_key"`
CertificateChain string `json:"certificate_chain"`
CreatedAt *time.Time `json:"created_at"`
ExpiredAt *time.Time `json:"expired_at"`
}
// Task: task.
type Task struct {
// ID: the unique identifier of the task.
ID string `json:"id"`
// ProjectID: the project ID associated to the task.
ProjectID string `json:"project_id"`
// OrganizationID: the organization ID associated to the task.
OrganizationID string `json:"organization_id"`
// Domain: the domain name associated to the task.
Domain *string `json:"domain"`
// Type: the type of the task.
// Default value: unknown
Type TaskType `json:"type"`
// Status: the status of the task.
// Default value: unavailable
Status TaskStatus `json:"status"`
// StartedAt: start date of the task.
StartedAt *time.Time `json:"started_at"`
// UpdatedAt: last update of the task.
UpdatedAt *time.Time `json:"updated_at"`
// Message: error message associated to the task.
Message *string `json:"message"`
// ContactIDentifier: human-friendly contact identifier used when the task concerns a contact.
ContactIDentifier *string `json:"contact_identifier"`
}
// TransferInDomainRequestTransferRequest: transfer in domain request transfer request.
type TransferInDomainRequestTransferRequest struct {
Domain string `json:"domain"`
AuthCode string `json:"auth_code"`
}
// UpdateContactRequestQuestion: update contact request question.
type UpdateContactRequestQuestion struct {
Question *string `json:"question"`
Answer *string `json:"answer"`
}
// AvailableDomain: available domain.
type AvailableDomain struct {
Domain string `json:"domain"`
Available bool `json:"available"`
Tld *Tld `json:"tld"`
}
// CheckContactsCompatibilityResponse: check contacts compatibility response.
type CheckContactsCompatibilityResponse struct {
Compatible bool `json:"compatible"`
OwnerCheckResult *CheckContactsCompatibilityResponseContactCheckResult `json:"owner_check_result"`
AdministrativeCheckResult *CheckContactsCompatibilityResponseContactCheckResult `json:"administrative_check_result"`
TechnicalCheckResult *CheckContactsCompatibilityResponseContactCheckResult `json:"technical_check_result"`
}
// ClearDNSZoneRecordsRequest: clear dns zone records request.
type ClearDNSZoneRecordsRequest struct {
// DNSZone: DNS zone to clear.
DNSZone string `json:"-"`
}
// ClearDNSZoneRecordsResponse: clear dns zone records response.
type ClearDNSZoneRecordsResponse struct {
}
// CloneDNSZoneRequest: clone dns zone request.
type CloneDNSZoneRequest struct {
// DNSZone: DNS zone to clone.
DNSZone string `json:"-"`
// DestDNSZone: destination DNS zone in which to clone the chosen DNS zone.
DestDNSZone string `json:"dest_dns_zone"`
// Overwrite: specifies whether or not the destination DNS zone will be overwritten.
Overwrite bool `json:"overwrite"`
// ProjectID: project ID of the destination DNS zone.
ProjectID *string `json:"project_id,omitempty"`
}
// CreateDNSZoneRequest: create dns zone request.
type CreateDNSZoneRequest struct {
// Domain: domain in which to crreate the DNS zone.
Domain string `json:"domain"`
// Subdomain: subdomain of the DNS zone to create.
Subdomain string `json:"subdomain"`
// ProjectID: project ID in which to create the DNS zone.
ProjectID string `json:"project_id"`
}
// CreateSSLCertificateRequest: create ssl certificate request.
type CreateSSLCertificateRequest struct {
DNSZone string `json:"dns_zone"`
AlternativeDNSZones []string `json:"alternative_dns_zones"`
}
// DeleteDNSZoneRequest: delete dns zone request.
type DeleteDNSZoneRequest struct {
// DNSZone: DNS zone to delete.
DNSZone string `json:"-"`
// ProjectID: project ID of the DNS zone to delete.
ProjectID string `json:"-"`
}
// DeleteDNSZoneResponse: delete dns zone response.
type DeleteDNSZoneResponse struct {
}
// DeleteDNSZoneTsigKeyRequest: delete dns zone tsig key request.
type DeleteDNSZoneTsigKeyRequest struct {
DNSZone string `json:"-"`
}
// DeleteExternalDomainResponse: delete external domain response.
type DeleteExternalDomainResponse struct {
}
// DeleteSSLCertificateRequest: delete ssl certificate request.
type DeleteSSLCertificateRequest struct {
DNSZone string `json:"-"`
}
// DeleteSSLCertificateResponse: delete ssl certificate response.
type DeleteSSLCertificateResponse struct {
}
// Domain: domain.
type Domain struct {
Domain string `json:"domain"`
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
// AutoRenewStatus: status of the automatic renewal of the domain.
// Default value: feature_status_unknown
AutoRenewStatus DomainFeatureStatus `json:"auto_renew_status"`
// Dnssec: status of the DNSSEC configuration of the domain.
Dnssec *DomainDNSSEC `json:"dnssec"`
// EppCode: list of the domain's EPP codes.
EppCode []string `json:"epp_code"`
// ExpiredAt: date of expiration of the domain.
ExpiredAt *time.Time `json:"expired_at"`
// UpdatedAt: domain's last modification date.
UpdatedAt *time.Time `json:"updated_at"`
Registrar string `json:"registrar"`
// IsExternal: indicates whether Scaleway is the domain's registrar.
IsExternal bool `json:"is_external"`
// Status: status of the domain.
// Default value: status_unknown
Status DomainStatus `json:"status"`
// DNSZones: list of the domain's DNS zones.
DNSZones []*DNSZone `json:"dns_zones"`
// OwnerContact: contact information of the domain's owner.
OwnerContact *Contact `json:"owner_contact"`
// TechnicalContact: contact information of the domain's technical contact.
TechnicalContact *Contact `json:"technical_contact"`
// AdministrativeContact: contact information of the domain's administrative contact.
AdministrativeContact *Contact `json:"administrative_contact"`
// ExternalDomainRegistrationStatus: registration status of an external domain, if available.
// Precisely one of ExternalDomainRegistrationStatus, TransferRegistrationStatus must be set.
ExternalDomainRegistrationStatus *DomainRegistrationStatusExternalDomain `json:"external_domain_registration_status,omitempty"`
// TransferRegistrationStatus: status of a domain, when available for transfer.
// Precisely one of ExternalDomainRegistrationStatus, TransferRegistrationStatus must be set.
TransferRegistrationStatus *DomainRegistrationStatusTransfer `json:"transfer_registration_status,omitempty"`
// Tld: domain's TLD information.
Tld *Tld `json:"tld"`
// LinkedProducts: list of Scaleway resources linked to the domain.
LinkedProducts []LinkedProduct `json:"linked_products"`
// PendingTrade: indicates if a trade is ongoing.
PendingTrade bool `json:"pending_trade"`
}
// ExportRawDNSZoneRequest: export raw dns zone request.
type ExportRawDNSZoneRequest struct {
// DNSZone: DNS zone to export.
DNSZone string `json:"-"`
// Format: DNS zone format.
// Default value: unknown_raw_format
Format RawFormat `json:"-"`
}
// GetDNSZoneTsigKeyRequest: get dns zone tsig key request.
type GetDNSZoneTsigKeyRequest struct {
DNSZone string `json:"-"`
}
// GetDNSZoneTsigKeyResponse: get dns zone tsig key response.
type GetDNSZoneTsigKeyResponse struct {
Name string `json:"name"`
Key string `json:"key"`
Algorithm string `json:"algorithm"`
}
// GetDNSZoneVersionDiffRequest: get dns zone version diff request.
type GetDNSZoneVersionDiffRequest struct {
DNSZoneVersionID string `json:"-"`
}
// GetDNSZoneVersionDiffResponse: get dns zone version diff response.
type GetDNSZoneVersionDiffResponse struct {
Changes []*RecordChange `json:"changes"`
}
// GetDomainAuthCodeResponse: get domain auth code response.
type GetDomainAuthCodeResponse struct {
AuthCode string `json:"auth_code"`
}
// GetSSLCertificateRequest: get ssl certificate request.
type GetSSLCertificateRequest struct {
DNSZone string `json:"-"`
}
// ImportProviderDNSZoneRequest: import provider dns zone request.
type ImportProviderDNSZoneRequest struct {
DNSZone string `json:"-"`
// Precisely one of OnlineV1 must be set.
OnlineV1 *ImportProviderDNSZoneRequestOnlineV1 `json:"online_v1,omitempty"`
}
// ImportProviderDNSZoneResponse: import provider dns zone response.
type ImportProviderDNSZoneResponse struct {
Records []*Record `json:"records"`
}
// ImportRawDNSZoneRequest: import raw dns zone request.
type ImportRawDNSZoneRequest struct {
// DNSZone: DNS zone to import.
DNSZone string `json:"-"`
// Deprecated
Content *string `json:"content,omitempty"`
ProjectID string `json:"project_id"`
// Deprecated: Format: default value: unknown_raw_format
Format *RawFormat `json:"format,omitempty"`
// BindSource: import a bind file format.
// Precisely one of BindSource, AxfrSource must be set.
BindSource *ImportRawDNSZoneRequestBindSource `json:"bind_source,omitempty"`
// AxfrSource: import from the name server given with TSIG, to use or not.
// Precisely one of BindSource, AxfrSource must be set.
AxfrSource *ImportRawDNSZoneRequestAXFRSource `json:"axfr_source,omitempty"`
}
// ImportRawDNSZoneResponse: import raw dns zone response.
type ImportRawDNSZoneResponse struct {
Records []*Record `json:"records"`
}
// ListContactsResponse: list contacts response.
type ListContactsResponse struct {
TotalCount uint32 `json:"total_count"`
Contacts []*ContactRoles `json:"contacts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListContactsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListContactsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListContactsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Contacts = append(r.Contacts, results.Contacts...)
r.TotalCount += uint32(len(results.Contacts))
return uint32(len(results.Contacts)), nil
}
// ListDNSZoneNameserversRequest: list dns zone nameservers request.
type ListDNSZoneNameserversRequest struct {
// DNSZone: DNS zone on which to filter the returned DNS zone name servers.
DNSZone string `json:"-"`
// ProjectID: project ID on which to filter the returned DNS zone name servers.
ProjectID *string `json:"-"`
}
// ListDNSZoneNameserversResponse: list dns zone nameservers response.
type ListDNSZoneNameserversResponse struct {
// Ns: DNS zone name servers returned.
Ns []*Nameserver `json:"ns"`
}
// ListDNSZoneRecordsRequest: list dns zone records request.
type ListDNSZoneRecordsRequest struct {
// DNSZone: DNS zone on which to filter the returned DNS zone records.
DNSZone string `json:"-"`
// ProjectID: project ID on which to filter the returned DNS zone records.
ProjectID *string `json:"-"`
// OrderBy: sort order of the returned DNS zone records.
// Default value: name_asc
OrderBy ListDNSZoneRecordsRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of DNS zone records per page.
PageSize *uint32 `json:"-"`
// Name: name on which to filter the returned DNS zone records.
Name string `json:"-"`
// Type: record type on which to filter the returned DNS zone records.
// Default value: unknown
Type RecordType `json:"-"`
// ID: record ID on which to filter the returned DNS zone records.
ID *string `json:"-"`
}
// ListDNSZoneRecordsResponse: list dns zone records response.
type ListDNSZoneRecordsResponse struct {
// TotalCount: total number of DNS zone records.
TotalCount uint32 `json:"total_count"`
// Records: paginated returned DNS zone records.
Records []*Record `json:"records"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDNSZoneRecordsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDNSZoneRecordsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDNSZoneRecordsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Records = append(r.Records, results.Records...)
r.TotalCount += uint32(len(results.Records))
return uint32(len(results.Records)), nil
}
// ListDNSZoneVersionRecordsRequest: list dns zone version records request.
type ListDNSZoneVersionRecordsRequest struct {
DNSZoneVersionID string `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of DNS zones versions records per page.
PageSize *uint32 `json:"-"`
}
// ListDNSZoneVersionRecordsResponse: list dns zone version records response.
type ListDNSZoneVersionRecordsResponse struct {
// TotalCount: total number of DNS zones versions records.
TotalCount uint32 `json:"total_count"`
Records []*Record `json:"records"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDNSZoneVersionRecordsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDNSZoneVersionRecordsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDNSZoneVersionRecordsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Records = append(r.Records, results.Records...)
r.TotalCount += uint32(len(results.Records))
return uint32(len(results.Records)), nil
}
// ListDNSZoneVersionsRequest: list dns zone versions request.
type ListDNSZoneVersionsRequest struct {
DNSZone string `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of DNS zones versions per page.
PageSize *uint32 `json:"-"`
}
// ListDNSZoneVersionsResponse: list dns zone versions response.
type ListDNSZoneVersionsResponse struct {
// TotalCount: total number of DNS zones versions.
TotalCount uint32 `json:"total_count"`
Versions []*DNSZoneVersion `json:"versions"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDNSZoneVersionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDNSZoneVersionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDNSZoneVersionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Versions = append(r.Versions, results.Versions...)
r.TotalCount += uint32(len(results.Versions))
return uint32(len(results.Versions)), nil
}
// ListDNSZonesRequest: list dns zones request.
type ListDNSZonesRequest struct {
// OrganizationID: organization ID on which to filter the returned DNS zones.
OrganizationID *string `json:"-"`
// ProjectID: project ID on which to filter the returned DNS zones.
ProjectID *string `json:"-"`
// OrderBy: sort order of the returned DNS zones.
// Default value: domain_asc
OrderBy ListDNSZonesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of DNS zones to return per page.
PageSize *uint32 `json:"-"`
// Domain: domain on which to filter the returned DNS zones.
Domain string `json:"-"`
// Deprecated: DNSZone: DNS zone on which to filter the returned DNS zones.
DNSZone *string `json:"-"`
// DNSZones: DNS zones on which to filter the returned DNS zones.
DNSZones []string `json:"-"`
// CreatedAfter: only list DNS zones created after this date.
CreatedAfter *time.Time `json:"-"`
// CreatedBefore: only list DNS zones created before this date.
CreatedBefore *time.Time `json:"-"`
// UpdatedAfter: only list DNS zones updated after this date.
UpdatedAfter *time.Time `json:"-"`
// UpdatedBefore: only list DNS zones updated before this date.
UpdatedBefore *time.Time `json:"-"`
}
// ListDNSZonesResponse: list dns zones response.
type ListDNSZonesResponse struct {
// TotalCount: total number of DNS zones matching the requested criteria.
TotalCount uint32 `json:"total_count"`
// DNSZones: paginated returned DNS zones.
DNSZones []*DNSZone `json:"dns_zones"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDNSZonesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDNSZonesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDNSZonesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.DNSZones = append(r.DNSZones, results.DNSZones...)
r.TotalCount += uint32(len(results.DNSZones))
return uint32(len(results.DNSZones)), nil
}
// ListDomainHostsResponse: list domain hosts response.
type ListDomainHostsResponse struct {
TotalCount uint32 `json:"total_count"`
Hosts []*Host `json:"hosts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDomainHostsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDomainHostsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDomainHostsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Hosts = append(r.Hosts, results.Hosts...)
r.TotalCount += uint32(len(results.Hosts))
return uint32(len(results.Hosts)), nil
}
// ListDomainsResponse: list domains response.
type ListDomainsResponse struct {
TotalCount uint32 `json:"total_count"`
Domains []*DomainSummary `json:"domains"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDomainsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Domains = append(r.Domains, results.Domains...)
r.TotalCount += uint32(len(results.Domains))
return uint32(len(results.Domains)), nil
}
// ListRenewableDomainsResponse: list renewable domains response.
type ListRenewableDomainsResponse struct {
TotalCount uint32 `json:"total_count"`
Domains []*RenewableDomain `json:"domains"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRenewableDomainsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRenewableDomainsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRenewableDomainsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Domains = append(r.Domains, results.Domains...)
r.TotalCount += uint32(len(results.Domains))
return uint32(len(results.Domains)), nil
}
// ListSSLCertificatesRequest: list ssl certificates request.
type ListSSLCertificatesRequest struct {
DNSZone string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
ProjectID *string `json:"-"`
}
// ListSSLCertificatesResponse: list ssl certificates response.
type ListSSLCertificatesResponse struct {
TotalCount uint32 `json:"total_count"`
Certificates []*SSLCertificate `json:"certificates"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSSLCertificatesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSSLCertificatesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSSLCertificatesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Certificates = append(r.Certificates, results.Certificates...)
r.TotalCount += uint32(len(results.Certificates))
return uint32(len(results.Certificates)), nil
}
// ListTasksResponse: list tasks response.
type ListTasksResponse struct {
TotalCount uint32 `json:"total_count"`
Tasks []*Task `json:"tasks"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTasksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTasksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTasksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tasks = append(r.Tasks, results.Tasks...)
r.TotalCount += uint32(len(results.Tasks))
return uint32(len(results.Tasks)), nil
}
// ListTldsResponse: list tlds response.
type ListTldsResponse struct {
// Tlds: array of TLDs.
Tlds []*Tld `json:"tlds"`
// TotalCount: total count of TLDs returned.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTldsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTldsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListTldsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tlds = append(r.Tlds, results.Tlds...)
r.TotalCount += uint64(len(results.Tlds))
return uint64(len(results.Tlds)), nil
}
// OrderResponse: order response.
type OrderResponse struct {
Domains []string `json:"domains"`
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
TaskID string `json:"task_id"`
CreatedAt *time.Time `json:"created_at"`
}
// RefreshDNSZoneRequest: refresh dns zone request.
type RefreshDNSZoneRequest struct {
// DNSZone: DNS zone to refresh.
DNSZone string `json:"-"`
// RecreateDNSZone: specifies whether or not to recreate the DNS zone.
RecreateDNSZone bool `json:"recreate_dns_zone"`
// RecreateSubDNSZone: specifies whether or not to recreate the sub DNS zone.
RecreateSubDNSZone bool `json:"recreate_sub_dns_zone"`
}
// RefreshDNSZoneResponse: refresh dns zone response.
type RefreshDNSZoneResponse struct {
// DNSZones: DNS zones returned.
DNSZones []*DNSZone `json:"dns_zones"`
}
// RegisterExternalDomainResponse: register external domain response.
type RegisterExternalDomainResponse struct {
Domain string `json:"domain"`
OrganizationID string `json:"organization_id"`
ValidationToken string `json:"validation_token"`
CreatedAt *time.Time `json:"created_at"`
ProjectID string `json:"project_id"`
}
// RegistrarAPIBuyDomainsRequest: registrar api buy domains request.
type RegistrarAPIBuyDomainsRequest struct {
Domains []string `json:"domains"`
DurationInYears uint32 `json:"duration_in_years"`
ProjectID string `json:"project_id"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContactID *string `json:"owner_contact_id,omitempty"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContact *NewContact `json:"owner_contact,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContactID *string `json:"administrative_contact_id,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContact *NewContact `json:"administrative_contact,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContactID *string `json:"technical_contact_id,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContact *NewContact `json:"technical_contact,omitempty"`
}
// RegistrarAPICheckContactsCompatibilityRequest: registrar api check contacts compatibility request.
type RegistrarAPICheckContactsCompatibilityRequest struct {
Domains []string `json:"domains"`
Tlds []string `json:"tlds"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContactID *string `json:"owner_contact_id,omitempty"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContact *NewContact `json:"owner_contact,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContactID *string `json:"administrative_contact_id,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContact *NewContact `json:"administrative_contact,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContactID *string `json:"technical_contact_id,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContact *NewContact `json:"technical_contact,omitempty"`
}
// RegistrarAPICreateDomainHostRequest: registrar api create domain host request.
type RegistrarAPICreateDomainHostRequest struct {
Domain string `json:"-"`
Name string `json:"name"`
IPs []net.IP `json:"ips"`
}
// RegistrarAPIDeleteDomainHostRequest: registrar api delete domain host request.
type RegistrarAPIDeleteDomainHostRequest struct {
Domain string `json:"-"`
Name string `json:"-"`
}
// RegistrarAPIDeleteExternalDomainRequest: registrar api delete external domain request.
type RegistrarAPIDeleteExternalDomainRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIDisableDomainAutoRenewRequest: registrar api disable domain auto renew request.
type RegistrarAPIDisableDomainAutoRenewRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIDisableDomainDNSSECRequest: registrar api disable domain dnssec request.
type RegistrarAPIDisableDomainDNSSECRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIEnableDomainAutoRenewRequest: registrar api enable domain auto renew request.
type RegistrarAPIEnableDomainAutoRenewRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIEnableDomainDNSSECRequest: registrar api enable domain dnssec request.
type RegistrarAPIEnableDomainDNSSECRequest struct {
Domain string `json:"-"`
DsRecord *DSRecord `json:"ds_record,omitempty"`
}
// RegistrarAPIGetContactRequest: registrar api get contact request.
type RegistrarAPIGetContactRequest struct {
ContactID string `json:"-"`
}
// RegistrarAPIGetDomainAuthCodeRequest: registrar api get domain auth code request.
type RegistrarAPIGetDomainAuthCodeRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIGetDomainRequest: registrar api get domain request.
type RegistrarAPIGetDomainRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIListContactsRequest: registrar api list contacts request.
type RegistrarAPIListContactsRequest struct {
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
Domain *string `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
// Role: default value: unknown_role
Role ListContactsRequestRole `json:"-"`
// EmailStatus: default value: email_status_unknown
EmailStatus ContactEmailStatus `json:"-"`
}
// RegistrarAPIListDomainHostsRequest: registrar api list domain hosts request.
type RegistrarAPIListDomainHostsRequest struct {
Domain string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// RegistrarAPIListDomainsRequest: registrar api list domains request.
type RegistrarAPIListDomainsRequest struct {
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: domain_asc
OrderBy ListDomainsRequestOrderBy `json:"-"`
Registrar *string `json:"-"`
// Status: default value: status_unknown
Status DomainStatus `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
IsExternal *bool `json:"-"`
Domain *string `json:"-"`
}
// RegistrarAPIListRenewableDomainsRequest: registrar api list renewable domains request.
type RegistrarAPIListRenewableDomainsRequest struct {
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: domain_asc
OrderBy ListRenewableDomainsRequestOrderBy `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
}
// RegistrarAPIListTasksRequest: registrar api list tasks request.
type RegistrarAPIListTasksRequest struct {
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
Domain *string `json:"-"`
Types []TaskType `json:"-"`
Statuses []TaskStatus `json:"-"`
// OrderBy: default value: domain_desc
OrderBy ListTasksRequestOrderBy `json:"-"`
}
// RegistrarAPIListTldsRequest: registrar api list tlds request.
type RegistrarAPIListTldsRequest struct {
// Tlds: array of TLDs to return.
Tlds []string `json:"-"`
// Page: page number for the returned Projects.
Page *int32 `json:"-"`
// PageSize: maximum number of Project per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned TLDs.
// Default value: name_asc
OrderBy ListTldsRequestOrderBy `json:"-"`
}
// RegistrarAPILockDomainTransferRequest: registrar api lock domain transfer request.
type RegistrarAPILockDomainTransferRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIRegisterExternalDomainRequest: registrar api register external domain request.
type RegistrarAPIRegisterExternalDomainRequest struct {
Domain string `json:"domain"`
ProjectID string `json:"project_id"`
}
// RegistrarAPIRenewDomainsRequest: registrar api renew domains request.
type RegistrarAPIRenewDomainsRequest struct {
Domains []string `json:"domains"`
DurationInYears uint32 `json:"duration_in_years"`
ForceLateRenewal *bool `json:"force_late_renewal,omitempty"`
}
// RegistrarAPISearchAvailableDomainsRequest: registrar api search available domains request.
type RegistrarAPISearchAvailableDomainsRequest struct {
// Domains: a list of domain to search, TLD is optional.
Domains []string `json:"-"`
// Tlds: array of tlds to search on.
Tlds []string `json:"-"`
// StrictSearch: search exact match.
StrictSearch bool `json:"-"`
}
// RegistrarAPITradeDomainRequest: registrar api trade domain request.
type RegistrarAPITradeDomainRequest struct {
Domain string `json:"-"`
ProjectID *string `json:"project_id,omitempty"`
// Precisely one of NewOwnerContactID, NewOwnerContact must be set.
NewOwnerContactID *string `json:"new_owner_contact_id,omitempty"`
// Precisely one of NewOwnerContactID, NewOwnerContact must be set.
NewOwnerContact *NewContact `json:"new_owner_contact,omitempty"`
}
// RegistrarAPITransferInDomainRequest: registrar api transfer in domain request.
type RegistrarAPITransferInDomainRequest struct {
Domains []*TransferInDomainRequestTransferRequest `json:"domains"`
ProjectID string `json:"project_id"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContactID *string `json:"owner_contact_id,omitempty"`
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContact *NewContact `json:"owner_contact,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContactID *string `json:"administrative_contact_id,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContact *NewContact `json:"administrative_contact,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContactID *string `json:"technical_contact_id,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContact *NewContact `json:"technical_contact,omitempty"`
}
// RegistrarAPIUnlockDomainTransferRequest: registrar api unlock domain transfer request.
type RegistrarAPIUnlockDomainTransferRequest struct {
Domain string `json:"-"`
}
// RegistrarAPIUpdateContactRequest: registrar api update contact request.
type RegistrarAPIUpdateContactRequest struct {
ContactID string `json:"-"`
Email *string `json:"email,omitempty"`
EmailAlt *string `json:"email_alt,omitempty"`
PhoneNumber *string `json:"phone_number,omitempty"`
FaxNumber *string `json:"fax_number,omitempty"`
AddressLine1 *string `json:"address_line_1,omitempty"`
AddressLine2 *string `json:"address_line_2,omitempty"`
Zip *string `json:"zip,omitempty"`
City *string `json:"city,omitempty"`
Country *string `json:"country,omitempty"`
VatIDentificationCode *string `json:"vat_identification_code,omitempty"`
CompanyIDentificationCode *string `json:"company_identification_code,omitempty"`
// Lang: default value: unknown_language_code
Lang std.LanguageCode `json:"lang"`
Resale *bool `json:"resale,omitempty"`
// Deprecated
Questions *[]*UpdateContactRequestQuestion `json:"questions,omitempty"`
ExtensionFr *ContactExtensionFR `json:"extension_fr,omitempty"`
ExtensionEu *ContactExtensionEU `json:"extension_eu,omitempty"`
WhoisOptIn *bool `json:"whois_opt_in,omitempty"`
State *string `json:"state,omitempty"`
ExtensionNl *ContactExtensionNL `json:"extension_nl,omitempty"`
}
// RegistrarAPIUpdateDomainHostRequest: registrar api update domain host request.
type RegistrarAPIUpdateDomainHostRequest struct {
Domain string `json:"-"`
Name string `json:"-"`
IPs *[]string `json:"ips,omitempty"`
}
// RegistrarAPIUpdateDomainRequest: registrar api update domain request.
type RegistrarAPIUpdateDomainRequest struct {
Domain string `json:"-"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContactID *string `json:"technical_contact_id,omitempty"`
// Precisely one of TechnicalContactID, TechnicalContact must be set.
TechnicalContact *NewContact `json:"technical_contact,omitempty"`
// Deprecated
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContactID *string `json:"owner_contact_id,omitempty"`
// Deprecated
// Precisely one of OwnerContactID, OwnerContact must be set.
OwnerContact *NewContact `json:"owner_contact,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContactID *string `json:"administrative_contact_id,omitempty"`
// Precisely one of AdministrativeContactID, AdministrativeContact must be set.
AdministrativeContact *NewContact `json:"administrative_contact,omitempty"`
}
// RestoreDNSZoneVersionRequest: restore dns zone version request.
type RestoreDNSZoneVersionRequest struct {
DNSZoneVersionID string `json:"-"`
}
// RestoreDNSZoneVersionResponse: restore dns zone version response.
type RestoreDNSZoneVersionResponse struct {
}
// SearchAvailableDomainsResponse: search available domains response.
type SearchAvailableDomainsResponse struct {
// AvailableDomains: array of available domains.
AvailableDomains []*AvailableDomain `json:"available_domains"`
}
// UpdateDNSZoneNameserversRequest: update dns zone nameservers request.
type UpdateDNSZoneNameserversRequest struct {
// DNSZone: DNS zone in which to update the DNS zone name servers.
DNSZone string `json:"-"`
// Ns: new DNS zone name servers.
Ns []*Nameserver `json:"ns"`
}
// UpdateDNSZoneNameserversResponse: update dns zone nameservers response.
type UpdateDNSZoneNameserversResponse struct {
// Ns: DNS zone name servers returned.
Ns []*Nameserver `json:"ns"`
}
// UpdateDNSZoneRecordsRequest: update dns zone records request.
type UpdateDNSZoneRecordsRequest struct {
// DNSZone: DNS zone in which to update the DNS zone records.
DNSZone string `json:"-"`
// Changes: changes made to the records.
Changes []*RecordChange `json:"changes"`
// ReturnAllRecords: specifies whether or not to return all the records.
ReturnAllRecords *bool `json:"return_all_records,omitempty"`
// DisallowNewZoneCreation: disable the creation of the target zone if it does not exist. Target zone creation is disabled by default.
DisallowNewZoneCreation bool `json:"disallow_new_zone_creation"`
// Serial: use the provided serial (0) instead of the auto-increment serial.
Serial *uint64 `json:"serial,omitempty"`
}
// UpdateDNSZoneRecordsResponse: update dns zone records response.
type UpdateDNSZoneRecordsResponse struct {
// Records: DNS zone records returned.
Records []*Record `json:"records"`
}
// UpdateDNSZoneRequest: update dns zone request.
type UpdateDNSZoneRequest struct {
// DNSZone: DNS zone to update.
DNSZone string `json:"-"`
// NewDNSZone: name of the new DNS zone to create.
NewDNSZone *string `json:"new_dns_zone,omitempty"`
// ProjectID: project ID in which to create the new DNS zone.
ProjectID string `json:"project_id"`
}
// This API allows you to manage your domains, DNS zones and records.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// ListDNSZones: Retrieve the list of DNS zones you can manage and filter DNS zones associated with specific domain names.
func (s *API) ListDNSZones(req *ListDNSZonesRequest, opts ...scw.RequestOption) (*ListDNSZonesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "domain", req.Domain)
parameter.AddToQuery(query, "dns_zone", req.DNSZone)
parameter.AddToQuery(query, "dns_zones", req.DNSZones)
parameter.AddToQuery(query, "created_after", req.CreatedAfter)
parameter.AddToQuery(query, "created_before", req.CreatedBefore)
parameter.AddToQuery(query, "updated_after", req.UpdatedAfter)
parameter.AddToQuery(query, "updated_before", req.UpdatedBefore)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones",
Query: query,
}
var resp ListDNSZonesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDNSZone: Create a new DNS zone specified by the domain name, the subdomain and the Project ID.
func (s *API) CreateDNSZone(req *CreateDNSZoneRequest, opts ...scw.RequestOption) (*DNSZone, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSZone
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDNSZone: Update the name and/or the Organizations for a DNS zone.
func (s *API) UpdateDNSZone(req *UpdateDNSZoneRequest, opts ...scw.RequestOption) (*DNSZone, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSZone
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CloneDNSZone: Clone an existing DNS zone with all its records into a new DNS zone.
func (s *API) CloneDNSZone(req *CloneDNSZoneRequest, opts ...scw.RequestOption) (*DNSZone, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/clone",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSZone
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDNSZone: Delete a DNS zone and all its records.
func (s *API) DeleteDNSZone(req *DeleteDNSZoneRequest, opts ...scw.RequestOption) (*DeleteDNSZoneResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "",
Query: query,
}
var resp DeleteDNSZoneResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDNSZoneRecords: Retrieve a list of DNS records within a DNS zone that has default name servers.
// You can filter records by type and name.
func (s *API) ListDNSZoneRecords(req *ListDNSZoneRecordsRequest, opts ...scw.RequestOption) (*ListDNSZoneRecordsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "id", req.ID)
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/records",
Query: query,
}
var resp ListDNSZoneRecordsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDNSZoneRecords: Update records within a DNS zone that has default name servers and perform several actions on your records.
//
// Actions include:
// - add: allows you to add a new record or add a new IP to an existing A record, for example
// - set: allows you to edit a record or edit an IP from an existing A record, for example
// - delete: allows you to delete a record or delete an IP from an existing A record, for example
// - clear: allows you to delete all records from a DNS zone
//
// All edits will be versioned.
func (s *API) UpdateDNSZoneRecords(req *UpdateDNSZoneRecordsRequest, opts ...scw.RequestOption) (*UpdateDNSZoneRecordsResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/records",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateDNSZoneRecordsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDNSZoneNameservers: Retrieve a list of name servers within a DNS zone and their optional glue records.
func (s *API) ListDNSZoneNameservers(req *ListDNSZoneNameserversRequest, opts ...scw.RequestOption) (*ListDNSZoneNameserversResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/nameservers",
Query: query,
}
var resp ListDNSZoneNameserversResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDNSZoneNameservers: Update name servers within a DNS zone and set optional glue records.
func (s *API) UpdateDNSZoneNameservers(req *UpdateDNSZoneNameserversRequest, opts ...scw.RequestOption) (*UpdateDNSZoneNameserversResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/nameservers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateDNSZoneNameserversResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ClearDNSZoneRecords: Delete all records within a DNS zone that has default name servers.
// All edits will be versioned.
func (s *API) ClearDNSZoneRecords(req *ClearDNSZoneRecordsRequest, opts ...scw.RequestOption) (*ClearDNSZoneRecordsResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/records",
}
var resp ClearDNSZoneRecordsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ExportRawDNSZone: Export a DNS zone with default name servers, in a specific format.
func (s *API) ExportRawDNSZone(req *ExportRawDNSZoneRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "format", req.Format)
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/raw",
Query: query,
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ImportRawDNSZone: Import and replace the format of records from a given provider, with default name servers.
func (s *API) ImportRawDNSZone(req *ImportRawDNSZoneRequest, opts ...scw.RequestOption) (*ImportRawDNSZoneResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/raw",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ImportRawDNSZoneResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ImportProviderDNSZone: Import and replace the format of records from a given provider, with default name servers.
func (s *API) ImportProviderDNSZone(req *ImportProviderDNSZoneRequest, opts ...scw.RequestOption) (*ImportProviderDNSZoneResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/import-provider",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ImportProviderDNSZoneResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RefreshDNSZone: Refresh an SOA DNS zone to reload the records in the DNS zone and update the SOA serial.
// You can recreate the given DNS zone and its sub DNS zone if needed.
func (s *API) RefreshDNSZone(req *RefreshDNSZoneRequest, opts ...scw.RequestOption) (*RefreshDNSZoneResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/refresh",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RefreshDNSZoneResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDNSZoneVersions: Retrieve a list of a DNS zone's versions.
// The maximum version count is 100. If the count reaches this limit, the oldest version will be deleted after each new modification.
func (s *API) ListDNSZoneVersions(req *ListDNSZoneVersionsRequest, opts ...scw.RequestOption) (*ListDNSZoneVersionsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/versions",
Query: query,
}
var resp ListDNSZoneVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDNSZoneVersionRecords: Retrieve a list of records from a specific DNS zone version.
func (s *API) ListDNSZoneVersionRecords(req *ListDNSZoneVersionRecordsRequest, opts ...scw.RequestOption) (*ListDNSZoneVersionRecordsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.DNSZoneVersionID) == "" {
return nil, errors.New("field DNSZoneVersionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/version/" + fmt.Sprint(req.DNSZoneVersionID) + "",
Query: query,
}
var resp ListDNSZoneVersionRecordsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDNSZoneVersionDiff: Access a previous DNS zone version to see the differences from another specific version.
func (s *API) GetDNSZoneVersionDiff(req *GetDNSZoneVersionDiffRequest, opts ...scw.RequestOption) (*GetDNSZoneVersionDiffResponse, error) {
var err error
if fmt.Sprint(req.DNSZoneVersionID) == "" {
return nil, errors.New("field DNSZoneVersionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/version/" + fmt.Sprint(req.DNSZoneVersionID) + "/diff",
}
var resp GetDNSZoneVersionDiffResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestoreDNSZoneVersion: Restore and activate a version of a specific DNS zone.
func (s *API) RestoreDNSZoneVersion(req *RestoreDNSZoneVersionRequest, opts ...scw.RequestOption) (*RestoreDNSZoneVersionResponse, error) {
var err error
if fmt.Sprint(req.DNSZoneVersionID) == "" {
return nil, errors.New("field DNSZoneVersionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/dns-zones/version/" + fmt.Sprint(req.DNSZoneVersionID) + "/restore",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RestoreDNSZoneVersionResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSSLCertificate: Get the DNS zone's TLS certificate. If you do not have a certificate, the ouptut returns `no certificate found`.
func (s *API) GetSSLCertificate(req *GetSSLCertificateRequest, opts ...scw.RequestOption) (*SSLCertificate, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/ssl-certificates/" + fmt.Sprint(req.DNSZone) + "",
}
var resp SSLCertificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSSLCertificate: Create a new TLS certificate or retrieve information about an existing TLS certificate.
func (s *API) CreateSSLCertificate(req *CreateSSLCertificateRequest, opts ...scw.RequestOption) (*SSLCertificate, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/ssl-certificates",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SSLCertificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSSLCertificates: List all the TLS certificates a user has created, specified by the user's Project ID and the DNS zone.
func (s *API) ListSSLCertificates(req *ListSSLCertificatesRequest, opts ...scw.RequestOption) (*ListSSLCertificatesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "dns_zone", req.DNSZone)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/ssl-certificates",
Query: query,
}
var resp ListSSLCertificatesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSSLCertificate: Delete an existing TLS certificate specified by its DNS zone. Deleting a TLS certificate is permanent and cannot be undone.
func (s *API) DeleteSSLCertificate(req *DeleteSSLCertificateRequest, opts ...scw.RequestOption) (*DeleteSSLCertificateResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/ssl-certificates/" + fmt.Sprint(req.DNSZone) + "",
}
var resp DeleteSSLCertificateResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDNSZoneTsigKey: Retrieve information about the TSIG key of a given DNS zone to allow AXFR requests.
func (s *API) GetDNSZoneTsigKey(req *GetDNSZoneTsigKeyRequest, opts ...scw.RequestOption) (*GetDNSZoneTsigKeyResponse, error) {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return nil, errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/tsig-key",
}
var resp GetDNSZoneTsigKeyResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDNSZoneTsigKey: Delete an existing TSIG key specified by its DNS zone. Deleting a TSIG key is permanent and cannot be undone.
func (s *API) DeleteDNSZoneTsigKey(req *DeleteDNSZoneTsigKeyRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.DNSZone) == "" {
return errors.New("field DNSZone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/dns-zones/" + fmt.Sprint(req.DNSZone) + "/tsig-key",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Manage your domains and contacts.
type RegistrarAPI struct {
client *scw.Client
}
// NewRegistrarAPI returns a RegistrarAPI object from a Scaleway client.
func NewRegistrarAPI(client *scw.Client) *RegistrarAPI {
return &RegistrarAPI{
client: client,
}
}
// ListTasks: List all operations performed on the account.
// You can filter the list of tasks by domain name.
func (s *RegistrarAPI) ListTasks(req *RegistrarAPIListTasksRequest, opts ...scw.RequestOption) (*ListTasksResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "domain", req.Domain)
parameter.AddToQuery(query, "types", req.Types)
parameter.AddToQuery(query, "statuses", req.Statuses)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/tasks",
Query: query,
}
var resp ListTasksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// BuyDomains: Request the registration of domain names.
// You can provide a domain's already existing contact or a new contact.
func (s *RegistrarAPI) BuyDomains(req *RegistrarAPIBuyDomainsRequest, opts ...scw.RequestOption) (*OrderResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/buy-domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp OrderResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RenewDomains: Request the renewal of one or more domain names.
func (s *RegistrarAPI) RenewDomains(req *RegistrarAPIRenewDomainsRequest, opts ...scw.RequestOption) (*OrderResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/renew-domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp OrderResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// TransferInDomain: Request the transfer of a domain from another registrar to Scaleway Domains and DNS.
func (s *RegistrarAPI) TransferInDomain(req *RegistrarAPITransferInDomainRequest, opts ...scw.RequestOption) (*OrderResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/transfer-domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp OrderResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// TradeDomain: Request to change a domain's contact owner.
// If you specify the `organization_id` of the domain's new owner, the contact will change from the current owner's Scaleway account to the new owner's Scaleway account.
// If the new owner's current contact information is not available, the first ever contact they have created for previous domains is taken into account to operate the change.
// If the new owner has never created a contact to register domains before, an error message displays.
func (s *RegistrarAPI) TradeDomain(req *RegistrarAPITradeDomainRequest, opts ...scw.RequestOption) (*OrderResponse, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/trade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp OrderResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RegisterExternalDomain: Request the registration of an external domain name.
func (s *RegistrarAPI) RegisterExternalDomain(req *RegistrarAPIRegisterExternalDomainRequest, opts ...scw.RequestOption) (*RegisterExternalDomainResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/external-domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RegisterExternalDomainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteExternalDomain: Delete an external domain name.
func (s *RegistrarAPI) DeleteExternalDomain(req *RegistrarAPIDeleteExternalDomainRequest, opts ...scw.RequestOption) (*DeleteExternalDomainResponse, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/external-domains/" + fmt.Sprint(req.Domain) + "",
}
var resp DeleteExternalDomainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckContactsCompatibility: Check whether contacts are compatible with a domain or a TLD.
// If contacts are not compatible with either the domain or the TLD, the information that needs to be corrected is returned.
func (s *RegistrarAPI) CheckContactsCompatibility(req *RegistrarAPICheckContactsCompatibilityRequest, opts ...scw.RequestOption) (*CheckContactsCompatibilityResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/check-contacts-compatibility",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckContactsCompatibilityResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListContacts: Retrieve the list of contacts and their associated domains and roles.
// You can filter the list by domain name.
func (s *RegistrarAPI) ListContacts(req *RegistrarAPIListContactsRequest, opts ...scw.RequestOption) (*ListContactsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "domain", req.Domain)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "role", req.Role)
parameter.AddToQuery(query, "email_status", req.EmailStatus)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/contacts",
Query: query,
}
var resp ListContactsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetContact: Retrieve a contact's details from the registrar using the given contact's ID.
func (s *RegistrarAPI) GetContact(req *RegistrarAPIGetContactRequest, opts ...scw.RequestOption) (*Contact, error) {
var err error
if fmt.Sprint(req.ContactID) == "" {
return nil, errors.New("field ContactID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/contacts/" + fmt.Sprint(req.ContactID) + "",
}
var resp Contact
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateContact: Edit the contact's information.
func (s *RegistrarAPI) UpdateContact(req *RegistrarAPIUpdateContactRequest, opts ...scw.RequestOption) (*Contact, error) {
var err error
if fmt.Sprint(req.ContactID) == "" {
return nil, errors.New("field ContactID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/domain/v2beta1/contacts/" + fmt.Sprint(req.ContactID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Contact
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDomains: Retrieve the list of domains you own.
func (s *RegistrarAPI) ListDomains(req *RegistrarAPIListDomainsRequest, opts ...scw.RequestOption) (*ListDomainsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "registrar", req.Registrar)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "is_external", req.IsExternal)
parameter.AddToQuery(query, "domain", req.Domain)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/domains",
Query: query,
}
var resp ListDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRenewableDomains: Retrieve the list of domains you own that can be renewed. You can also see the maximum renewal duration in years for your domains that are renewable.
func (s *RegistrarAPI) ListRenewableDomains(req *RegistrarAPIListRenewableDomainsRequest, opts ...scw.RequestOption) (*ListRenewableDomainsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/renewable-domains",
Query: query,
}
var resp ListRenewableDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomain: Retrieve a specific domain and display the domain's information.
func (s *RegistrarAPI) GetDomain(req *RegistrarAPIGetDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDomain: Update contacts for a specific domain or create a new contact.
// If you add the same contact for multiple roles (owner, administrative, technical), only one ID will be created and used for all of the roles.
func (s *RegistrarAPI) UpdateDomain(req *RegistrarAPIUpdateDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// LockDomainTransfer: Lock the transfer of a domain. This means that the domain cannot be transferred and the authorization code cannot be requested to your current registrar.
func (s *RegistrarAPI) LockDomainTransfer(req *RegistrarAPILockDomainTransferRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/lock-transfer",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnlockDomainTransfer: Unlock the transfer of a domain. This means that the domain can be transferred and the authorization code can be requested to your current registrar.
func (s *RegistrarAPI) UnlockDomainTransfer(req *RegistrarAPIUnlockDomainTransferRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/unlock-transfer",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableDomainAutoRenew: Enable the `auto renew` feature for a domain. This means the domain will be automatically renewed before its expiry date.
func (s *RegistrarAPI) EnableDomainAutoRenew(req *RegistrarAPIEnableDomainAutoRenewRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/enable-auto-renew",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableDomainAutoRenew: Disable the `auto renew` feature for a domain. This means the domain will not be renewed before its expiry date.
func (s *RegistrarAPI) DisableDomainAutoRenew(req *RegistrarAPIDisableDomainAutoRenewRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/disable-auto-renew",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomainAuthCode: Retrieve the authorization code to tranfer an unlocked domain. The output returns an error if the domain is locked.
// Some TLDs may have a different procedure to retrieve the authorization code. In that case, the information displays in the message field.
func (s *RegistrarAPI) GetDomainAuthCode(req *RegistrarAPIGetDomainAuthCodeRequest, opts ...scw.RequestOption) (*GetDomainAuthCodeResponse, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/auth-code",
}
var resp GetDomainAuthCodeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableDomainDNSSEC: If your domain uses another registrar and has the default Scaleway NS, you have to **update the DS record at your registrar**.
func (s *RegistrarAPI) EnableDomainDNSSEC(req *RegistrarAPIEnableDomainDNSSECRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/enable-dnssec",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableDomainDNSSEC: Disable DNSSEC for a domain.
func (s *RegistrarAPI) DisableDomainDNSSEC(req *RegistrarAPIDisableDomainDNSSECRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/disable-dnssec",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SearchAvailableDomains: Search a domain or a maximum of 10 domains that are available.
//
// If the TLD list is empty or not set, the search returns the results from the most popular TLDs.
func (s *RegistrarAPI) SearchAvailableDomains(req *RegistrarAPISearchAvailableDomainsRequest, opts ...scw.RequestOption) (*SearchAvailableDomainsResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "domains", req.Domains)
parameter.AddToQuery(query, "tlds", req.Tlds)
parameter.AddToQuery(query, "strict_search", req.StrictSearch)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/search-domains",
Query: query,
}
var resp SearchAvailableDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTlds: Retrieve the list of TLDs and offers associated with them.
func (s *RegistrarAPI) ListTlds(req *RegistrarAPIListTldsRequest, opts ...scw.RequestOption) (*ListTldsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "tlds", req.Tlds)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/tlds",
Query: query,
}
var resp ListTldsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDomainHost: Create a hostname for a domain with glue IPs.
func (s *RegistrarAPI) CreateDomainHost(req *RegistrarAPICreateDomainHostRequest, opts ...scw.RequestOption) (*Host, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/hosts",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Host
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDomainHosts: List a domain's hostnames using their glue IPs.
func (s *RegistrarAPI) ListDomainHosts(req *RegistrarAPIListDomainHostsRequest, opts ...scw.RequestOption) (*ListDomainHostsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/hosts",
Query: query,
}
var resp ListDomainHostsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDomainHost: Update a domain's hostname with glue IPs.
func (s *RegistrarAPI) UpdateDomainHost(req *RegistrarAPIUpdateDomainHostRequest, opts ...scw.RequestOption) (*Host, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return nil, errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/hosts/" + fmt.Sprint(req.Name) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Host
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDomainHost: Delete a domain's hostname.
func (s *RegistrarAPI) DeleteDomainHost(req *RegistrarAPIDeleteDomainHostRequest, opts ...scw.RequestOption) (*Host, error) {
var err error
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return nil, errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/domain/v2beta1/domains/" + fmt.Sprint(req.Domain) + "/hosts/" + fmt.Sprint(req.Name) + "",
}
var resp Host
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/domain/v2beta1/domain_utils.go 0000664 0000000 0000000 00000006253 14747113137 0030554 0 ustar 00root root 0000000 0000000 package domain
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 5 * time.Minute
)
const (
// ErrCodeNoSuchDNSZone for service response error code
//
// The specified dns zone does not exist.
ErrCodeNoSuchDNSZone = "NoSuchDNSZone"
ErrCodeNoSuchDNSRecord = "NoSuchDNSRecord"
)
// WaitForDNSZoneRequest is used by WaitForDNSZone method.
type WaitForDNSZoneRequest struct {
DNSZone string
DNSZones []string
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForDNSZone(
req *WaitForDNSZoneRequest,
opts ...scw.RequestOption,
) (*DNSZone, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DNSZoneStatus]struct{}{
DNSZoneStatusActive: {},
DNSZoneStatusLocked: {},
DNSZoneStatusError: {},
}
dnsZone, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
listReq := &ListDNSZonesRequest{
DNSZones: req.DNSZones,
}
if req.DNSZone != "" {
listReq.DNSZone = &req.DNSZone
}
// listing dnsZone zones and take the first one
DNSZones, err := s.ListDNSZones(listReq, opts...)
if err != nil {
return nil, false, err
}
if len(DNSZones.DNSZones) == 0 {
return nil, true, errors.New(ErrCodeNoSuchDNSZone)
}
zone := DNSZones.DNSZones[0]
_, isTerminal := terminalStatus[zone.Status]
return zone, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for DNS failed")
}
return dnsZone.(*DNSZone), nil
}
// WaitForDNSRecordExistRequest is used by WaitForDNSRecordExist method.
type WaitForDNSRecordExistRequest struct {
DNSZone string
RecordName string
RecordType RecordType
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForDNSRecordExist(
req *WaitForDNSRecordExistRequest,
opts ...scw.RequestOption,
) (*Record, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
dns, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
// listing dns zone records and take the first one
DNSRecords, err := s.ListDNSZoneRecords(&ListDNSZoneRecordsRequest{
Name: req.RecordName,
Type: req.RecordType,
DNSZone: req.DNSZone,
}, opts...)
if err != nil {
return nil, false, err
}
if DNSRecords.TotalCount == 0 {
return nil, false, errors.New(ErrCodeNoSuchDNSRecord)
}
record := DNSRecords.Records[0]
return record, true, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "check for DNS Record exist failed")
}
return dns.(*Record), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/ 0000775 0000000 0000000 00000000000 14747113137 0025624 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0027241 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/v1alpha1/edge_services_sdk.go 0000664 0000000 0000000 00000237714 14747113137 0033256 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package edge_services provides methods and message types of the edge_services v1alpha1 API.
package edge_services
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DNSStageType string
const (
// The DNS stage type is unknown by default.
DNSStageTypeUnknownType = DNSStageType("unknown_type")
// The DNS stage is configured with the default FQDN.
DNSStageTypeAuto = DNSStageType("auto")
// Custom FQDN has been provided, managed by Scaleway Domains and DNS.
DNSStageTypeManaged = DNSStageType("managed")
// Custom FQDN has been provided, not managed by Scaleway Domains and DNS.
DNSStageTypeCustom = DNSStageType("custom")
)
func (enum DNSStageType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum DNSStageType) Values() []DNSStageType {
return []DNSStageType{
"unknown_type",
"auto",
"managed",
"custom",
}
}
func (enum DNSStageType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSStageType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSStageType(DNSStageType(tmp).String())
return nil
}
type LBOriginError string
const (
LBOriginErrorUnknown = LBOriginError("unknown")
LBOriginErrorTimeout = LBOriginError("timeout")
LBOriginErrorConnectionRefused = LBOriginError("connection_refused")
LBOriginErrorTLSError = LBOriginError("tls_error")
)
func (enum LBOriginError) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum LBOriginError) Values() []LBOriginError {
return []LBOriginError{
"unknown",
"timeout",
"connection_refused",
"tls_error",
}
}
func (enum LBOriginError) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LBOriginError) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LBOriginError(LBOriginError(tmp).String())
return nil
}
type ListBackendStagesRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListBackendStagesRequestOrderByCreatedAtAsc = ListBackendStagesRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListBackendStagesRequestOrderByCreatedAtDesc = ListBackendStagesRequestOrderBy("created_at_desc")
)
func (enum ListBackendStagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListBackendStagesRequestOrderBy) Values() []ListBackendStagesRequestOrderBy {
return []ListBackendStagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListBackendStagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListBackendStagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListBackendStagesRequestOrderBy(ListBackendStagesRequestOrderBy(tmp).String())
return nil
}
type ListCacheStagesRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListCacheStagesRequestOrderByCreatedAtAsc = ListCacheStagesRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListCacheStagesRequestOrderByCreatedAtDesc = ListCacheStagesRequestOrderBy("created_at_desc")
)
func (enum ListCacheStagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListCacheStagesRequestOrderBy) Values() []ListCacheStagesRequestOrderBy {
return []ListCacheStagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListCacheStagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListCacheStagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListCacheStagesRequestOrderBy(ListCacheStagesRequestOrderBy(tmp).String())
return nil
}
type ListDNSStagesRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListDNSStagesRequestOrderByCreatedAtAsc = ListDNSStagesRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListDNSStagesRequestOrderByCreatedAtDesc = ListDNSStagesRequestOrderBy("created_at_desc")
)
func (enum ListDNSStagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDNSStagesRequestOrderBy) Values() []ListDNSStagesRequestOrderBy {
return []ListDNSStagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListDNSStagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDNSStagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDNSStagesRequestOrderBy(ListDNSStagesRequestOrderBy(tmp).String())
return nil
}
type ListPipelinesRequestOrderBy string
const (
ListPipelinesRequestOrderByCreatedAtAsc = ListPipelinesRequestOrderBy("created_at_asc")
ListPipelinesRequestOrderByCreatedAtDesc = ListPipelinesRequestOrderBy("created_at_desc")
ListPipelinesRequestOrderByNameAsc = ListPipelinesRequestOrderBy("name_asc")
ListPipelinesRequestOrderByNameDesc = ListPipelinesRequestOrderBy("name_desc")
)
func (enum ListPipelinesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPipelinesRequestOrderBy) Values() []ListPipelinesRequestOrderBy {
return []ListPipelinesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListPipelinesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPipelinesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPipelinesRequestOrderBy(ListPipelinesRequestOrderBy(tmp).String())
return nil
}
type ListPipelinesWithStagesRequestOrderBy string
const (
ListPipelinesWithStagesRequestOrderByCreatedAtAsc = ListPipelinesWithStagesRequestOrderBy("created_at_asc")
ListPipelinesWithStagesRequestOrderByCreatedAtDesc = ListPipelinesWithStagesRequestOrderBy("created_at_desc")
ListPipelinesWithStagesRequestOrderByNameAsc = ListPipelinesWithStagesRequestOrderBy("name_asc")
ListPipelinesWithStagesRequestOrderByNameDesc = ListPipelinesWithStagesRequestOrderBy("name_desc")
)
func (enum ListPipelinesWithStagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPipelinesWithStagesRequestOrderBy) Values() []ListPipelinesWithStagesRequestOrderBy {
return []ListPipelinesWithStagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListPipelinesWithStagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPipelinesWithStagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPipelinesWithStagesRequestOrderBy(ListPipelinesWithStagesRequestOrderBy(tmp).String())
return nil
}
type ListPurgeRequestsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListPurgeRequestsRequestOrderByCreatedAtAsc = ListPurgeRequestsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListPurgeRequestsRequestOrderByCreatedAtDesc = ListPurgeRequestsRequestOrderBy("created_at_desc")
)
func (enum ListPurgeRequestsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPurgeRequestsRequestOrderBy) Values() []ListPurgeRequestsRequestOrderBy {
return []ListPurgeRequestsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListPurgeRequestsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPurgeRequestsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPurgeRequestsRequestOrderBy(ListPurgeRequestsRequestOrderBy(tmp).String())
return nil
}
type ListTLSStagesRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListTLSStagesRequestOrderByCreatedAtAsc = ListTLSStagesRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListTLSStagesRequestOrderByCreatedAtDesc = ListTLSStagesRequestOrderBy("created_at_desc")
)
func (enum ListTLSStagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTLSStagesRequestOrderBy) Values() []ListTLSStagesRequestOrderBy {
return []ListTLSStagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListTLSStagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTLSStagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTLSStagesRequestOrderBy(ListTLSStagesRequestOrderBy(tmp).String())
return nil
}
type PipelineErrorCode string
const (
PipelineErrorCodeUnknownCode = PipelineErrorCode("unknown_code")
PipelineErrorCodeDNSInvalidFormat = PipelineErrorCode("dns_invalid_format")
PipelineErrorCodeDNSInvalidTld = PipelineErrorCode("dns_invalid_tld")
PipelineErrorCodeDNSForbiddenRootDomain = PipelineErrorCode("dns_forbidden_root_domain")
PipelineErrorCodeDNSForbiddenScwCloud = PipelineErrorCode("dns_forbidden_scw_cloud")
PipelineErrorCodeDNSDomainDontExist = PipelineErrorCode("dns_domain_dont_exist")
PipelineErrorCodeDNSCnameDontExist = PipelineErrorCode("dns_cname_dont_exist")
PipelineErrorCodeDNSCnameResolve = PipelineErrorCode("dns_cname_resolve")
PipelineErrorCodeDNSFqdnAlreadyExists = PipelineErrorCode("dns_fqdn_already_exists")
PipelineErrorCodeDNSFqdnAlreadyInUse = PipelineErrorCode("dns_fqdn_already_in_use")
PipelineErrorCodeTLSCertDeleted = PipelineErrorCode("tls_cert_deleted")
PipelineErrorCodeTLSCertDisabled = PipelineErrorCode("tls_cert_disabled")
PipelineErrorCodeTLSCertExpired = PipelineErrorCode("tls_cert_expired")
PipelineErrorCodeTLSCertInvalidFormat = PipelineErrorCode("tls_cert_invalid_format")
PipelineErrorCodeTLSCertMissing = PipelineErrorCode("tls_cert_missing")
PipelineErrorCodeTLSChainOrder = PipelineErrorCode("tls_chain_order")
PipelineErrorCodeTLSKeyInvalidFormat = PipelineErrorCode("tls_key_invalid_format")
PipelineErrorCodeTLSKeyMissing = PipelineErrorCode("tls_key_missing")
PipelineErrorCodeTLSKeyTooMany = PipelineErrorCode("tls_key_too_many")
PipelineErrorCodeTLSManagedDomainRateLimit = PipelineErrorCode("tls_managed_domain_rate_limit")
PipelineErrorCodeTLSManagedInternal = PipelineErrorCode("tls_managed_internal")
PipelineErrorCodeTLSPairMismatch = PipelineErrorCode("tls_pair_mismatch")
PipelineErrorCodeTLSRootInconsistent = PipelineErrorCode("tls_root_inconsistent")
PipelineErrorCodeTLSRootIncorrect = PipelineErrorCode("tls_root_incorrect")
PipelineErrorCodeTLSRootMissing = PipelineErrorCode("tls_root_missing")
PipelineErrorCodeTLSSanMismatch = PipelineErrorCode("tls_san_mismatch")
PipelineErrorCodeTLSSelfSigned = PipelineErrorCode("tls_self_signed")
)
func (enum PipelineErrorCode) String() string {
if enum == "" {
// return default value if empty
return "unknown_code"
}
return string(enum)
}
func (enum PipelineErrorCode) Values() []PipelineErrorCode {
return []PipelineErrorCode{
"unknown_code",
"dns_invalid_format",
"dns_invalid_tld",
"dns_forbidden_root_domain",
"dns_forbidden_scw_cloud",
"dns_domain_dont_exist",
"dns_cname_dont_exist",
"dns_cname_resolve",
"dns_fqdn_already_exists",
"dns_fqdn_already_in_use",
"tls_cert_deleted",
"tls_cert_disabled",
"tls_cert_expired",
"tls_cert_invalid_format",
"tls_cert_missing",
"tls_chain_order",
"tls_key_invalid_format",
"tls_key_missing",
"tls_key_too_many",
"tls_managed_domain_rate_limit",
"tls_managed_internal",
"tls_pair_mismatch",
"tls_root_inconsistent",
"tls_root_incorrect",
"tls_root_missing",
"tls_san_mismatch",
"tls_self_signed",
}
}
func (enum PipelineErrorCode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PipelineErrorCode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PipelineErrorCode(PipelineErrorCode(tmp).String())
return nil
}
type PipelineErrorSeverity string
const (
PipelineErrorSeverityUnknownSeverity = PipelineErrorSeverity("unknown_severity")
PipelineErrorSeverityWarning = PipelineErrorSeverity("warning")
PipelineErrorSeverityCritical = PipelineErrorSeverity("critical")
)
func (enum PipelineErrorSeverity) String() string {
if enum == "" {
// return default value if empty
return "unknown_severity"
}
return string(enum)
}
func (enum PipelineErrorSeverity) Values() []PipelineErrorSeverity {
return []PipelineErrorSeverity{
"unknown_severity",
"warning",
"critical",
}
}
func (enum PipelineErrorSeverity) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PipelineErrorSeverity) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PipelineErrorSeverity(PipelineErrorSeverity(tmp).String())
return nil
}
type PipelineErrorStage string
const (
PipelineErrorStageUnknownStage = PipelineErrorStage("unknown_stage")
PipelineErrorStageDNS = PipelineErrorStage("dns")
PipelineErrorStageTLS = PipelineErrorStage("tls")
PipelineErrorStageCache = PipelineErrorStage("cache")
PipelineErrorStageBackend = PipelineErrorStage("backend")
)
func (enum PipelineErrorStage) String() string {
if enum == "" {
// return default value if empty
return "unknown_stage"
}
return string(enum)
}
func (enum PipelineErrorStage) Values() []PipelineErrorStage {
return []PipelineErrorStage{
"unknown_stage",
"dns",
"tls",
"cache",
"backend",
}
}
func (enum PipelineErrorStage) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PipelineErrorStage) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PipelineErrorStage(PipelineErrorStage(tmp).String())
return nil
}
type PipelineErrorType string
const (
PipelineErrorTypeUnknownType = PipelineErrorType("unknown_type")
PipelineErrorTypeRuntime = PipelineErrorType("runtime")
PipelineErrorTypeConfig = PipelineErrorType("config")
)
func (enum PipelineErrorType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum PipelineErrorType) Values() []PipelineErrorType {
return []PipelineErrorType{
"unknown_type",
"runtime",
"config",
}
}
func (enum PipelineErrorType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PipelineErrorType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PipelineErrorType(PipelineErrorType(tmp).String())
return nil
}
type PipelineStatus string
const (
PipelineStatusUnknownStatus = PipelineStatus("unknown_status")
PipelineStatusReady = PipelineStatus("ready")
PipelineStatusError = PipelineStatus("error")
PipelineStatusPending = PipelineStatus("pending")
PipelineStatusWarning = PipelineStatus("warning")
)
func (enum PipelineStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum PipelineStatus) Values() []PipelineStatus {
return []PipelineStatus{
"unknown_status",
"ready",
"error",
"pending",
"warning",
}
}
func (enum PipelineStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PipelineStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PipelineStatus(PipelineStatus(tmp).String())
return nil
}
type PlanName string
const (
PlanNameUnknownName = PlanName("unknown_name")
PlanNameStarter = PlanName("starter")
PlanNameProfessional = PlanName("professional")
PlanNameAdvanced = PlanName("advanced")
)
func (enum PlanName) String() string {
if enum == "" {
// return default value if empty
return "unknown_name"
}
return string(enum)
}
func (enum PlanName) Values() []PlanName {
return []PlanName{
"unknown_name",
"starter",
"professional",
"advanced",
}
}
func (enum PlanName) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlanName) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlanName(PlanName(tmp).String())
return nil
}
type PurgeRequestStatus string
const (
// The purge request status is unknown by default.
PurgeRequestStatusUnknownStatus = PurgeRequestStatus("unknown_status")
// The purge request has been processed sucessfully.
PurgeRequestStatusDone = PurgeRequestStatus("done")
// An error occurred during the purge request.
PurgeRequestStatusError = PurgeRequestStatus("error")
// The purge request status is pending.
PurgeRequestStatusPending = PurgeRequestStatus("pending")
)
func (enum PurgeRequestStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum PurgeRequestStatus) Values() []PurgeRequestStatus {
return []PurgeRequestStatus{
"unknown_status",
"done",
"error",
"pending",
}
}
func (enum PurgeRequestStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PurgeRequestStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PurgeRequestStatus(PurgeRequestStatus(tmp).String())
return nil
}
// ScalewayLB: scaleway lb.
type ScalewayLB struct {
// ID: ID of the Load Balancer.
ID string `json:"id"`
// Zone: zone of the Load Balancer.
Zone scw.Zone `json:"zone"`
// FrontendID: ID of the frontend linked to the Load Balancer.
FrontendID string `json:"frontend_id"`
// IsSsl: defines whether the Load Balancer's frontend handles SSL connections.
IsSsl *bool `json:"is_ssl"`
// DomainName: fully Qualified Domain Name (in the format subdomain.example.com) to use in HTTP requests sent towards your Load Balancer.
DomainName *string `json:"domain_name"`
}
// ScalewayLBBackendConfig: scaleway lb backend config.
type ScalewayLBBackendConfig struct {
// LBs: load Balancer information.
LBs []*ScalewayLB `json:"lbs"`
}
// ScalewayS3BackendConfig: scaleway s3 backend config.
type ScalewayS3BackendConfig struct {
// BucketName: name of the Bucket.
BucketName *string `json:"bucket_name"`
// BucketRegion: region of the Bucket.
BucketRegion *string `json:"bucket_region"`
// IsWebsite: defines whether the bucket website feature is enabled.
IsWebsite *bool `json:"is_website"`
}
// PipelineError: pipeline error.
type PipelineError struct {
// Stage: default value: unknown_stage
Stage PipelineErrorStage `json:"stage"`
// Code: default value: unknown_code
Code PipelineErrorCode `json:"code"`
// Severity: default value: unknown_severity
Severity PipelineErrorSeverity `json:"severity"`
Message string `json:"message"`
// Type: default value: unknown_type
Type PipelineErrorType `json:"type"`
}
// TLSSecret: tls secret.
type TLSSecret struct {
// SecretID: ID of the Secret.
SecretID string `json:"secret_id"`
// Region: region of the Secret.
Region scw.Region `json:"region"`
}
// BackendStage: backend stage.
type BackendStage struct {
// ID: ID of the backend stage.
ID string `json:"id"`
// PipelineID: pipeline ID the backend stage belongs to.
PipelineID *string `json:"pipeline_id"`
// ProjectID: project ID of the backend stage.
ProjectID string `json:"project_id"`
// CreatedAt: date the backend stage was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the backend stage was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// ScalewayS3: scaleway Object Storage origin bucket (S3) linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayS3 *ScalewayS3BackendConfig `json:"scaleway_s3,omitempty"`
// ScalewayLB: scaleway Load Balancer origin linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayLB *ScalewayLBBackendConfig `json:"scaleway_lb,omitempty"`
}
// CacheStage: cache stage.
type CacheStage struct {
// ID: ID of the cache stage.
ID string `json:"id"`
// PipelineID: pipeline ID the cache stage belongs to.
PipelineID *string `json:"pipeline_id"`
// ProjectID: project ID of the cache stage.
ProjectID string `json:"project_id"`
// FallbackTTL: time To Live (TTL) in seconds. Defines how long content is cached.
FallbackTTL *scw.Duration `json:"fallback_ttl"`
// CreatedAt: date the cache stage was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the cache stage was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// BackendStageID: backend stage ID the cache stage is linked to.
// Precisely one of BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// DNSStage: dns stage.
type DNSStage struct {
// ID: ID of the DNS stage.
ID string `json:"id"`
// Fqdns: list of Fully Qualified Domain Names attached to the stage.
Fqdns []string `json:"fqdns"`
// Type: type of the stage.
// Default value: unknown_type
Type DNSStageType `json:"type"`
// PipelineID: pipeline ID the DNS stage belongs to.
PipelineID *string `json:"pipeline_id"`
// ProjectID: project ID of the DNS stage.
ProjectID string `json:"project_id"`
// CreatedAt: date the DNS stage was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the DNS stage was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// TLSStageID: TLS stage ID the DNS stage is linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
TLSStageID *string `json:"tls_stage_id,omitempty"`
// CacheStageID: cache stage ID the DNS stage is linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the DNS stage is linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// Pipeline: pipeline.
type Pipeline struct {
// ID: ID of the pipeline.
ID string `json:"id"`
// Name: name of the pipeline.
Name string `json:"name"`
// Description: description of the pipeline.
Description string `json:"description"`
// Status: status of the pipeline.
// Default value: unknown_status
Status PipelineStatus `json:"status"`
// Errors: errors of the pipeline.
Errors []*PipelineError `json:"errors"`
// ProjectID: project ID of the pipeline.
ProjectID string `json:"project_id"`
// OrganizationID: organization ID of the pipeline.
OrganizationID string `json:"organization_id"`
// CreatedAt: date the pipeline was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the pipeline was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// DNSStageID: DNS stage ID the pipeline is attached to.
// Precisely one of DNSStageID must be set.
DNSStageID *string `json:"dns_stage_id,omitempty"`
}
// TLSStage: tls stage.
type TLSStage struct {
// ID: ID of the TLS stage.
ID string `json:"id"`
// Secrets: secret (from Scaleway Secret Manager) containing your custom certificate.
Secrets []*TLSSecret `json:"secrets"`
// ManagedCertificate: true when Scaleway generates and manages a Let's Encrypt certificate for the TLS stage/custom endpoint.
ManagedCertificate bool `json:"managed_certificate"`
// PipelineID: pipeline ID the TLS stage belongs to.
PipelineID *string `json:"pipeline_id"`
// ProjectID: project ID of the TLS stage.
ProjectID string `json:"project_id"`
// CertificateExpiresAt: expiration date of the certificate.
CertificateExpiresAt *time.Time `json:"certificate_expires_at"`
// CreatedAt: date the TLS stage was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the TLS stage was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// CacheStageID: cache stage ID the TLS stage is linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the TLS stage is linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// CheckPEMChainRequestSecretChain: check pem chain request secret chain.
type CheckPEMChainRequestSecretChain struct {
SecretID string `json:"secret_id"`
SecretRegion string `json:"secret_region"`
}
// PlanDetails: plan details.
type PlanDetails struct {
// PlanName: subscription plan name.
// Default value: unknown_name
PlanName PlanName `json:"plan_name"`
// PackageGb: amount of egress data from cache included in subscription plan.
PackageGb uint64 `json:"package_gb"`
// PipelineLimit: number of pipelines included in subscription plan.
PipelineLimit uint32 `json:"pipeline_limit"`
}
// PipelineStages: pipeline stages.
type PipelineStages struct {
Pipeline *Pipeline `json:"pipeline"`
DNSStages []*DNSStage `json:"dns_stages"`
TLSStages []*TLSStage `json:"tls_stages"`
CacheStages []*CacheStage `json:"cache_stages"`
BackendStages []*BackendStage `json:"backend_stages"`
}
// PurgeRequest: purge request.
type PurgeRequest struct {
// ID: ID of the purge request.
ID string `json:"id"`
// PipelineID: pipeline ID the purge request belongs to.
PipelineID string `json:"pipeline_id"`
// Status: status of the purge request.
// Default value: unknown_status
Status PurgeRequestStatus `json:"status"`
// Assets: list of asserts to purge.
// Precisely one of Assets, All must be set.
Assets *[]string `json:"assets,omitempty"`
// All: defines whether to purge all content.
// Precisely one of Assets, All must be set.
All *bool `json:"all,omitempty"`
// CreatedAt: date the purge request was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the purge request was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// TLSSecretsConfig: tls secrets config.
type TLSSecretsConfig struct {
// TLSSecrets: secret information (from Secret Manager).
TLSSecrets []*TLSSecret `json:"tls_secrets"`
}
// CheckDomainRequest: check domain request.
type CheckDomainRequest struct {
ProjectID string `json:"project_id"`
Fqdn string `json:"fqdn"`
Cname string `json:"cname"`
}
// CheckDomainResponse: check domain response.
type CheckDomainResponse struct {
IsValid bool `json:"is_valid"`
}
// CheckLBOriginRequest: check lb origin request.
type CheckLBOriginRequest struct {
LB *ScalewayLB `json:"lb,omitempty"`
}
// CheckLBOriginResponse: check lb origin response.
type CheckLBOriginResponse struct {
IsValid bool `json:"is_valid"`
// ErrorType: default value: unknown
ErrorType LBOriginError `json:"error_type"`
}
// CheckPEMChainRequest: check pem chain request.
type CheckPEMChainRequest struct {
ProjectID string `json:"project_id"`
Fqdn string `json:"fqdn"`
// Precisely one of Secret, Raw must be set.
Secret *CheckPEMChainRequestSecretChain `json:"secret,omitempty"`
// Precisely one of Secret, Raw must be set.
Raw *string `json:"raw,omitempty"`
}
// CheckPEMChainResponse: check pem chain response.
type CheckPEMChainResponse struct {
IsValid bool `json:"is_valid"`
}
// CreateBackendStageRequest: create backend stage request.
type CreateBackendStageRequest struct {
// ProjectID: project ID in which the backend stage will be created.
ProjectID string `json:"project_id"`
// ScalewayS3: scaleway Object Storage origin bucket (S3) linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayS3 *ScalewayS3BackendConfig `json:"scaleway_s3,omitempty"`
// ScalewayLB: scaleway Load Balancer origin linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayLB *ScalewayLBBackendConfig `json:"scaleway_lb,omitempty"`
}
// CreateCacheStageRequest: create cache stage request.
type CreateCacheStageRequest struct {
// ProjectID: project ID in which the cache stage will be created.
ProjectID string `json:"project_id"`
// FallbackTTL: time To Live (TTL) in seconds. Defines how long content is cached.
FallbackTTL *scw.Duration `json:"fallback_ttl,omitempty"`
// BackendStageID: backend stage ID the cache stage will be linked to.
// Precisely one of BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// CreateDNSStageRequest: create dns stage request.
type CreateDNSStageRequest struct {
// ProjectID: project ID in which the DNS stage will be created.
ProjectID string `json:"project_id"`
// Fqdns: fully Qualified Domain Name (in the format subdomain.example.com) to attach to the stage.
Fqdns *[]string `json:"fqdns,omitempty"`
// TLSStageID: TLS stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
TLSStageID *string `json:"tls_stage_id,omitempty"`
// CacheStageID: cache stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// CreatePipelineRequest: create pipeline request.
type CreatePipelineRequest struct {
// ProjectID: project ID in which the pipeline will be created.
ProjectID string `json:"project_id"`
// Name: name of the pipeline.
Name string `json:"name"`
// Description: description of the pipeline.
Description string `json:"description"`
// DNSStageID: DNS stage ID the pipeline will be attached to.
// Precisely one of DNSStageID must be set.
DNSStageID *string `json:"dns_stage_id,omitempty"`
}
// CreatePurgeRequestRequest: create purge request request.
type CreatePurgeRequestRequest struct {
// PipelineID: pipeline ID in which the purge request will be created.
PipelineID string `json:"pipeline_id"`
// Assets: list of asserts to purge.
// Precisely one of Assets, All must be set.
Assets *[]string `json:"assets,omitempty"`
// All: defines whether to purge all content.
// Precisely one of Assets, All must be set.
All *bool `json:"all,omitempty"`
}
// CreateTLSStageRequest: create tls stage request.
type CreateTLSStageRequest struct {
// ProjectID: project ID in which the TLS stage will be created.
ProjectID string `json:"project_id"`
// Secrets: secret (from Scaleway Secret Manager) containing your custom certificate.
Secrets []*TLSSecret `json:"secrets"`
// ManagedCertificate: true when Scaleway generates and manages a Let's Encrypt certificate for the TLS stage/custom endpoint.
ManagedCertificate *bool `json:"managed_certificate,omitempty"`
// CacheStageID: cache stage ID the TLS stage will be linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the TLS stage will be linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// DeleteBackendStageRequest: delete backend stage request.
type DeleteBackendStageRequest struct {
// BackendStageID: ID of the backend stage to delete.
BackendStageID string `json:"-"`
}
// DeleteCacheStageRequest: delete cache stage request.
type DeleteCacheStageRequest struct {
// CacheStageID: ID of the cache stage to delete.
CacheStageID string `json:"-"`
}
// DeleteCurrentPlanRequest: delete current plan request.
type DeleteCurrentPlanRequest struct {
ProjectID string `json:"-"`
}
// DeleteDNSStageRequest: delete dns stage request.
type DeleteDNSStageRequest struct {
// DNSStageID: ID of the DNS stage to delete.
DNSStageID string `json:"-"`
}
// DeletePipelineRequest: delete pipeline request.
type DeletePipelineRequest struct {
// PipelineID: ID of the pipeline to delete.
PipelineID string `json:"-"`
}
// DeleteTLSStageRequest: delete tls stage request.
type DeleteTLSStageRequest struct {
// TLSStageID: ID of the TLS stage to delete.
TLSStageID string `json:"-"`
}
// GetBackendStageRequest: get backend stage request.
type GetBackendStageRequest struct {
// BackendStageID: ID of the requested backend stage.
BackendStageID string `json:"-"`
}
// GetBillingRequest: get billing request.
type GetBillingRequest struct {
ProjectID string `json:"-"`
}
// GetBillingResponse: get billing response.
type GetBillingResponse struct {
// CurrentPlan: information on the currently-selected, active Edge Services subscription plan.
CurrentPlan *PlanDetails `json:"current_plan"`
// PlanCost: cost to date (this month) for Edge Service subscription plans. This comprises the pro-rata cost of the current subscription plan, and any previous subscription plans that were active earlier in the month.
PlanCost *scw.Money `json:"plan_cost"`
// PipelineNumber: total number of pipelines currently configured.
PipelineNumber uint32 `json:"pipeline_number"`
// ExtraPipelinesCost: cost to date (this month) of pipelines not included in the subscription plans.
ExtraPipelinesCost *scw.Money `json:"extra_pipelines_cost"`
// CurrentPlanCacheUsage: total amount of data egressed from the cache in gigabytes from the beginning of the month, for the active subscription plan.
CurrentPlanCacheUsage uint64 `json:"current_plan_cache_usage"`
// ExtraCacheUsage: total amount of extra data egressed from cache in gigabytes from the beginning of the month, not included in the subscription plans.
ExtraCacheUsage uint64 `json:"extra_cache_usage"`
// ExtraCacheCost: cost to date (this month) of the data egressed from the cache that is not included in the subscription plans.
ExtraCacheCost *scw.Money `json:"extra_cache_cost"`
// TotalCost: total cost to date (this month) of all Edge Services resources including active subscription plan, previously active plans, extra pipelines and extra egress cache data.
TotalCost *scw.Money `json:"total_cost"`
}
// GetCacheStageRequest: get cache stage request.
type GetCacheStageRequest struct {
// CacheStageID: ID of the requested cache stage.
CacheStageID string `json:"-"`
}
// GetCurrentPlanRequest: get current plan request.
type GetCurrentPlanRequest struct {
ProjectID string `json:"-"`
}
// GetDNSStageRequest: get dns stage request.
type GetDNSStageRequest struct {
// DNSStageID: ID of the requested DNS stage.
DNSStageID string `json:"-"`
}
// GetPipelineRequest: get pipeline request.
type GetPipelineRequest struct {
// PipelineID: ID of the requested pipeline.
PipelineID string `json:"-"`
}
// GetPurgeRequestRequest: get purge request request.
type GetPurgeRequestRequest struct {
// PurgeRequestID: ID of the requested purge request.
PurgeRequestID string `json:"-"`
}
// GetTLSStageRequest: get tls stage request.
type GetTLSStageRequest struct {
// TLSStageID: ID of the requested TLS stage.
TLSStageID string `json:"-"`
}
// ListBackendStagesRequest: list backend stages request.
type ListBackendStagesRequest struct {
// OrderBy: sort order of backend stages in the response.
// Default value: created_at_asc
OrderBy ListBackendStagesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of backend stages to return per page.
PageSize *uint32 `json:"-"`
// PipelineID: pipeline ID to filter for, only backend stages from this pipeline will be returned.
PipelineID *string `json:"-"`
// ProjectID: project ID to filter for, only backend stages from this Project will be returned.
ProjectID *string `json:"-"`
// BucketName: bucket name to filter for, only backend stages from this Bucket will be returned.
BucketName *string `json:"-"`
// BucketRegion: bucket region to filter for, only backend stages with buckets in this region will be returned.
BucketRegion *string `json:"-"`
// LBID: load Balancer ID to filter for, only backend stages with this Load Balancer will be returned.
LBID *string `json:"-"`
}
// ListBackendStagesResponse: list backend stages response.
type ListBackendStagesResponse struct {
// Stages: paginated list of backend stages.
Stages []*BackendStage `json:"stages"`
// TotalCount: count of all backend stages matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListBackendStagesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListBackendStagesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListBackendStagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Stages = append(r.Stages, results.Stages...)
r.TotalCount += uint64(len(results.Stages))
return uint64(len(results.Stages)), nil
}
// ListCacheStagesRequest: list cache stages request.
type ListCacheStagesRequest struct {
// OrderBy: sort order of cache stages in the response.
// Default value: created_at_asc
OrderBy ListCacheStagesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of cache stages to return per page.
PageSize *uint32 `json:"-"`
// PipelineID: pipeline ID to filter for, only cache stages from this pipeline will be returned.
PipelineID *string `json:"-"`
// ProjectID: project ID to filter for, only cache stages from this Project will be returned.
ProjectID *string `json:"-"`
}
// ListCacheStagesResponse: list cache stages response.
type ListCacheStagesResponse struct {
// Stages: paginated list of cache stages.
Stages []*CacheStage `json:"stages"`
// TotalCount: count of all cache stages matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListCacheStagesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListCacheStagesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListCacheStagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Stages = append(r.Stages, results.Stages...)
r.TotalCount += uint64(len(results.Stages))
return uint64(len(results.Stages)), nil
}
// ListDNSStagesRequest: list dns stages request.
type ListDNSStagesRequest struct {
// OrderBy: sort order of DNS stages in the response.
// Default value: created_at_asc
OrderBy ListDNSStagesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of DNS stages to return per page.
PageSize *uint32 `json:"-"`
// PipelineID: pipeline ID to filter for, only DNS stages from this pipeline will be returned.
PipelineID *string `json:"-"`
// ProjectID: project ID to filter for, only DNS stages from this Project will be returned.
ProjectID *string `json:"-"`
// Fqdn: fully Qualified Domain Name to filter for (in the format subdomain.example.com), only DNS stages with this FQDN will be returned.
Fqdn *string `json:"-"`
}
// ListDNSStagesResponse: list dns stages response.
type ListDNSStagesResponse struct {
// Stages: paginated list of DNS stages.
Stages []*DNSStage `json:"stages"`
// TotalCount: count of all DNS stages matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDNSStagesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDNSStagesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDNSStagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Stages = append(r.Stages, results.Stages...)
r.TotalCount += uint64(len(results.Stages))
return uint64(len(results.Stages)), nil
}
// ListPipelinesRequest: list pipelines request.
type ListPipelinesRequest struct {
// OrderBy: sort order of pipelines in the response.
// Default value: created_at_asc
OrderBy ListPipelinesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of pipelines to return per page.
PageSize *uint32 `json:"-"`
// Name: pipeline name to filter for, only pipelines with this string within their name will be returned.
Name *string `json:"-"`
// OrganizationID: organization ID to filter for, only pipelines from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only pipelines from this Project will be returned.
ProjectID *string `json:"-"`
// HasBackendStageLB: filter on backend stage, only pipelines with a Load Balancer origin will be returned.
HasBackendStageLB *bool `json:"-"`
}
// ListPipelinesResponse: list pipelines response.
type ListPipelinesResponse struct {
// Pipelines: paginated list of pipelines.
Pipelines []*Pipeline `json:"pipelines"`
// TotalCount: count of all pipelines matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPipelinesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPipelinesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPipelinesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Pipelines = append(r.Pipelines, results.Pipelines...)
r.TotalCount += uint64(len(results.Pipelines))
return uint64(len(results.Pipelines)), nil
}
// ListPipelinesWithStagesRequest: list pipelines with stages request.
type ListPipelinesWithStagesRequest struct {
// OrderBy: default value: created_at_asc
OrderBy ListPipelinesWithStagesRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
Name *string `json:"-"`
OrganizationID *string `json:"-"`
ProjectID *string `json:"-"`
}
// ListPipelinesWithStagesResponse: list pipelines with stages response.
type ListPipelinesWithStagesResponse struct {
Pipelines []*PipelineStages `json:"pipelines"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPipelinesWithStagesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPipelinesWithStagesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPipelinesWithStagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Pipelines = append(r.Pipelines, results.Pipelines...)
r.TotalCount += uint64(len(results.Pipelines))
return uint64(len(results.Pipelines)), nil
}
// ListPlansResponse: list plans response.
type ListPlansResponse struct {
TotalCount uint64 `json:"total_count"`
Plans []*PlanDetails `json:"plans"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPlansResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPlansResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPlansResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Plans = append(r.Plans, results.Plans...)
r.TotalCount += uint64(len(results.Plans))
return uint64(len(results.Plans)), nil
}
// ListPurgeRequestsRequest: list purge requests request.
type ListPurgeRequestsRequest struct {
// OrderBy: sort order of purge requests in the response.
// Default value: created_at_asc
OrderBy ListPurgeRequestsRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of purge requests to return per page.
PageSize *uint32 `json:"-"`
// OrganizationID: organization ID to filter for, only purge requests from this Project will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only purge requests from this Project will be returned.
ProjectID *string `json:"-"`
// PipelineID: pipeline ID to filter for, only purge requests from this pipeline will be returned.
PipelineID *string `json:"-"`
}
// ListPurgeRequestsResponse: list purge requests response.
type ListPurgeRequestsResponse struct {
// PurgeRequests: paginated list of purge requests.
PurgeRequests []*PurgeRequest `json:"purge_requests"`
// TotalCount: count of all purge requests matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPurgeRequestsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPurgeRequestsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPurgeRequestsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PurgeRequests = append(r.PurgeRequests, results.PurgeRequests...)
r.TotalCount += uint64(len(results.PurgeRequests))
return uint64(len(results.PurgeRequests)), nil
}
// ListTLSStagesRequest: list tls stages request.
type ListTLSStagesRequest struct {
// OrderBy: sort order of TLS stages in the response.
// Default value: created_at_asc
OrderBy ListTLSStagesRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of TLS stages to return per page.
PageSize *uint32 `json:"-"`
// PipelineID: pipeline ID to filter for, only TLS stages from this pipeline will be returned.
PipelineID *string `json:"-"`
// ProjectID: project ID to filter for, only TLS stages from this Project will be returned.
ProjectID *string `json:"-"`
// SecretID: secret ID to filter for, only TLS stages with this Secret ID will be returned.
SecretID *string `json:"-"`
// SecretRegion: secret region to filter for, only TLS stages with a Secret in this region will be returned.
SecretRegion *string `json:"-"`
}
// ListTLSStagesResponse: list tls stages response.
type ListTLSStagesResponse struct {
// Stages: paginated list of TLS stages.
Stages []*TLSStage `json:"stages"`
// TotalCount: count of all TLS stages matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTLSStagesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTLSStagesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListTLSStagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Stages = append(r.Stages, results.Stages...)
r.TotalCount += uint64(len(results.Stages))
return uint64(len(results.Stages)), nil
}
// Plan: plan.
type Plan struct {
// PlanName: default value: unknown_name
PlanName PlanName `json:"plan_name"`
}
// SelectPlanRequest: select plan request.
type SelectPlanRequest struct {
ProjectID string `json:"project_id"`
// PlanName: default value: unknown_name
PlanName PlanName `json:"plan_name"`
}
// UpdateBackendStageRequest: update backend stage request.
type UpdateBackendStageRequest struct {
// BackendStageID: ID of the backend stage to update.
BackendStageID string `json:"-"`
// ScalewayS3: scaleway Object Storage origin bucket (S3) linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayS3 *ScalewayS3BackendConfig `json:"scaleway_s3,omitempty"`
// ScalewayLB: scaleway Load Balancer origin linked to the backend stage.
// Precisely one of ScalewayS3, ScalewayLB must be set.
ScalewayLB *ScalewayLBBackendConfig `json:"scaleway_lb,omitempty"`
}
// UpdateCacheStageRequest: update cache stage request.
type UpdateCacheStageRequest struct {
// CacheStageID: ID of the cache stage to update.
CacheStageID string `json:"-"`
// FallbackTTL: time To Live (TTL) in seconds. Defines how long content is cached.
FallbackTTL *scw.Duration `json:"fallback_ttl,omitempty"`
// BackendStageID: backend stage ID the cache stage will be linked to.
// Precisely one of BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// UpdateDNSStageRequest: update dns stage request.
type UpdateDNSStageRequest struct {
// DNSStageID: ID of the DNS stage to update.
DNSStageID string `json:"-"`
// Fqdns: fully Qualified Domain Name (in the format subdomain.example.com) attached to the stage.
Fqdns *[]string `json:"fqdns,omitempty"`
// TLSStageID: TLS stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
TLSStageID *string `json:"tls_stage_id,omitempty"`
// CacheStageID: cache stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the DNS stage will be linked to.
// Precisely one of TLSStageID, CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
// UpdatePipelineRequest: update pipeline request.
type UpdatePipelineRequest struct {
// PipelineID: ID of the pipeline to update.
PipelineID string `json:"-"`
// Name: name of the pipeline.
Name *string `json:"name,omitempty"`
// Description: description of the pipeline.
Description *string `json:"description,omitempty"`
// DNSStageID: DNS stage ID the pipeline will be attached to.
// Precisely one of DNSStageID must be set.
DNSStageID *string `json:"dns_stage_id,omitempty"`
}
// UpdateTLSStageRequest: update tls stage request.
type UpdateTLSStageRequest struct {
// TLSStageID: ID of the TLS stage to update.
TLSStageID string `json:"-"`
// TLSSecretsConfig: secret (from Scaleway Secret-Manager) containing your custom certificate.
TLSSecretsConfig *TLSSecretsConfig `json:"tls_secrets_config,omitempty"`
// ManagedCertificate: true when Scaleway generates and manages a Let's Encrypt certificate for the TLS stage/custom endpoint.
ManagedCertificate *bool `json:"managed_certificate,omitempty"`
// CacheStageID: cache stage ID the TLS stage will be linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
CacheStageID *string `json:"cache_stage_id,omitempty"`
// BackendStageID: backend stage ID the TLS stage will be linked to.
// Precisely one of CacheStageID, BackendStageID must be set.
BackendStageID *string `json:"backend_stage_id,omitempty"`
}
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// ListPipelines: List all pipelines, for a Scaleway Organization or Scaleway Project. By default, the pipelines returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListPipelines(req *ListPipelinesRequest, opts ...scw.RequestOption) (*ListPipelinesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "has_backend_stage_lb", req.HasBackendStageLB)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/pipelines",
Query: query,
}
var resp ListPipelinesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePipeline: Create a new pipeline. You must specify a `dns_stage_id` to form a stage-chain that goes all the way to the backend stage (origin), so the HTTP request will be processed according to the stages you created.
func (s *API) CreatePipeline(req *CreatePipelineRequest, opts ...scw.RequestOption) (*Pipeline, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/pipelines",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Pipeline
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPipeline: Retrieve information about an existing pipeline, specified by its `pipeline_id`. Its full details, including errors, are returned in the response object.
func (s *API) GetPipeline(req *GetPipelineRequest, opts ...scw.RequestOption) (*Pipeline, error) {
var err error
if fmt.Sprint(req.PipelineID) == "" {
return nil, errors.New("field PipelineID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/pipelines/" + fmt.Sprint(req.PipelineID) + "",
}
var resp Pipeline
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPipelinesWithStages:
func (s *API) ListPipelinesWithStages(req *ListPipelinesWithStagesRequest, opts ...scw.RequestOption) (*ListPipelinesWithStagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/pipelines-stages",
Query: query,
}
var resp ListPipelinesWithStagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePipeline: Update the parameters of an existing pipeline, specified by its `pipeline_id`. Parameters which can be updated include the `name`, `description` and `dns_stage_id`.
func (s *API) UpdatePipeline(req *UpdatePipelineRequest, opts ...scw.RequestOption) (*Pipeline, error) {
var err error
if fmt.Sprint(req.PipelineID) == "" {
return nil, errors.New("field PipelineID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/pipelines/" + fmt.Sprint(req.PipelineID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Pipeline
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePipeline: Delete an existing pipeline, specified by its `pipeline_id`. Deleting a pipeline is permanent, and cannot be undone. Note that all stages linked to the pipeline are also deleted.
func (s *API) DeletePipeline(req *DeletePipelineRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.PipelineID) == "" {
return errors.New("field PipelineID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/pipelines/" + fmt.Sprint(req.PipelineID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDNSStages: List all DNS stages, for a Scaleway Organization or Scaleway Project. By default, the DNS stages returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListDNSStages(req *ListDNSStagesRequest, opts ...scw.RequestOption) (*ListDNSStagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "pipeline_id", req.PipelineID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "fqdn", req.Fqdn)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/dns-stages",
Query: query,
}
var resp ListDNSStagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDNSStage: Create a new DNS stage. You must specify the `fqdns` field to customize the domain endpoint, using a domain you already own.
func (s *API) CreateDNSStage(req *CreateDNSStageRequest, opts ...scw.RequestOption) (*DNSStage, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/dns-stages",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDNSStage: Retrieve information about an existing DNS stage, specified by its `dns_stage_id`. Its full details, including FQDNs, are returned in the response object.
func (s *API) GetDNSStage(req *GetDNSStageRequest, opts ...scw.RequestOption) (*DNSStage, error) {
var err error
if fmt.Sprint(req.DNSStageID) == "" {
return nil, errors.New("field DNSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/dns-stages/" + fmt.Sprint(req.DNSStageID) + "",
}
var resp DNSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDNSStage: Update the parameters of an existing DNS stage, specified by its `dns_stage_id`.
func (s *API) UpdateDNSStage(req *UpdateDNSStageRequest, opts ...scw.RequestOption) (*DNSStage, error) {
var err error
if fmt.Sprint(req.DNSStageID) == "" {
return nil, errors.New("field DNSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/dns-stages/" + fmt.Sprint(req.DNSStageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDNSStage: Delete an existing DNS stage, specified by its `dns_stage_id`. Deleting a DNS stage is permanent, and cannot be undone.
func (s *API) DeleteDNSStage(req *DeleteDNSStageRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.DNSStageID) == "" {
return errors.New("field DNSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/dns-stages/" + fmt.Sprint(req.DNSStageID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListTLSStages: List all TLS stages, for a Scaleway Organization or Scaleway Project. By default, the TLS stages returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListTLSStages(req *ListTLSStagesRequest, opts ...scw.RequestOption) (*ListTLSStagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "pipeline_id", req.PipelineID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "secret_id", req.SecretID)
parameter.AddToQuery(query, "secret_region", req.SecretRegion)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/tls-stages",
Query: query,
}
var resp ListTLSStagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateTLSStage: Create a new TLS stage. You must specify either the `secrets` or `managed_certificate` fields to customize the SSL/TLS certificate of your endpoint. Choose `secrets` if you are using a pre-existing certificate held in Scaleway Secret Manager, or `managed_certificate` to let Scaleway generate and manage a Let's Encrypt certificate for your customized endpoint.
func (s *API) CreateTLSStage(req *CreateTLSStageRequest, opts ...scw.RequestOption) (*TLSStage, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/tls-stages",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp TLSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetTLSStage: Retrieve information about an existing TLS stage, specified by its `tls_stage_id`. Its full details, including secrets and certificate expiration date are returned in the response object.
func (s *API) GetTLSStage(req *GetTLSStageRequest, opts ...scw.RequestOption) (*TLSStage, error) {
var err error
if fmt.Sprint(req.TLSStageID) == "" {
return nil, errors.New("field TLSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/tls-stages/" + fmt.Sprint(req.TLSStageID) + "",
}
var resp TLSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateTLSStage: Update the parameters of an existing TLS stage, specified by its `tls_stage_id`. Both `tls_secrets_config` and `managed_certificate` parameters can be updated.
func (s *API) UpdateTLSStage(req *UpdateTLSStageRequest, opts ...scw.RequestOption) (*TLSStage, error) {
var err error
if fmt.Sprint(req.TLSStageID) == "" {
return nil, errors.New("field TLSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/tls-stages/" + fmt.Sprint(req.TLSStageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp TLSStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTLSStage: Delete an existing TLS stage, specified by its `tls_stage_id`. Deleting a TLS stage is permanent, and cannot be undone.
func (s *API) DeleteTLSStage(req *DeleteTLSStageRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.TLSStageID) == "" {
return errors.New("field TLSStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/tls-stages/" + fmt.Sprint(req.TLSStageID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListCacheStages: List all cache stages, for a Scaleway Organization or Scaleway Project. By default, the cache stages returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListCacheStages(req *ListCacheStagesRequest, opts ...scw.RequestOption) (*ListCacheStagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "pipeline_id", req.PipelineID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/cache-stages",
Query: query,
}
var resp ListCacheStagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateCacheStage: Create a new cache stage. You must specify the `fallback_ttl` field to customize the TTL of the cache.
func (s *API) CreateCacheStage(req *CreateCacheStageRequest, opts ...scw.RequestOption) (*CacheStage, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/cache-stages",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CacheStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCacheStage: Retrieve information about an existing cache stage, specified by its `cache_stage_id`. Its full details, including Time To Live (TTL), are returned in the response object.
func (s *API) GetCacheStage(req *GetCacheStageRequest, opts ...scw.RequestOption) (*CacheStage, error) {
var err error
if fmt.Sprint(req.CacheStageID) == "" {
return nil, errors.New("field CacheStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/cache-stages/" + fmt.Sprint(req.CacheStageID) + "",
}
var resp CacheStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCacheStage: Update the parameters of an existing cache stage, specified by its `cache_stage_id`. Parameters which can be updated include the `fallback_ttl` and `backend_stage_id`.
func (s *API) UpdateCacheStage(req *UpdateCacheStageRequest, opts ...scw.RequestOption) (*CacheStage, error) {
var err error
if fmt.Sprint(req.CacheStageID) == "" {
return nil, errors.New("field CacheStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/cache-stages/" + fmt.Sprint(req.CacheStageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CacheStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCacheStage: Delete an existing cache stage, specified by its `cache_stage_id`. Deleting a cache stage is permanent, and cannot be undone.
func (s *API) DeleteCacheStage(req *DeleteCacheStageRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.CacheStageID) == "" {
return errors.New("field CacheStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/cache-stages/" + fmt.Sprint(req.CacheStageID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListBackendStages: List all backend stages, for a Scaleway Organization or Scaleway Project. By default, the backend stages returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListBackendStages(req *ListBackendStagesRequest, opts ...scw.RequestOption) (*ListBackendStagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "pipeline_id", req.PipelineID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "bucket_name", req.BucketName)
parameter.AddToQuery(query, "bucket_region", req.BucketRegion)
parameter.AddToQuery(query, "lb_id", req.LBID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/backend-stages",
Query: query,
}
var resp ListBackendStagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateBackendStage: Create a new backend stage. You must specify either a `scaleway_s3` (for a Scaleway Object Storage bucket) or `scaleway_lb` (for a Scaleway Load Balancer) field to configure the origin.
func (s *API) CreateBackendStage(req *CreateBackendStageRequest, opts ...scw.RequestOption) (*BackendStage, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/backend-stages",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp BackendStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetBackendStage: Retrieve information about an existing backend stage, specified by its `backend_stage_id`. Its full details, including `scaleway_s3` or `scaleway_lb`, are returned in the response object.
func (s *API) GetBackendStage(req *GetBackendStageRequest, opts ...scw.RequestOption) (*BackendStage, error) {
var err error
if fmt.Sprint(req.BackendStageID) == "" {
return nil, errors.New("field BackendStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/backend-stages/" + fmt.Sprint(req.BackendStageID) + "",
}
var resp BackendStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateBackendStage: Update the parameters of an existing backend stage, specified by its `backend_stage_id`.
func (s *API) UpdateBackendStage(req *UpdateBackendStageRequest, opts ...scw.RequestOption) (*BackendStage, error) {
var err error
if fmt.Sprint(req.BackendStageID) == "" {
return nil, errors.New("field BackendStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/backend-stages/" + fmt.Sprint(req.BackendStageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp BackendStage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteBackendStage: Delete an existing backend stage, specified by its `backend_stage_id`. Deleting a backend stage is permanent, and cannot be undone.
func (s *API) DeleteBackendStage(req *DeleteBackendStageRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.BackendStageID) == "" {
return errors.New("field BackendStageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/backend-stages/" + fmt.Sprint(req.BackendStageID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CheckDomain:
func (s *API) CheckDomain(req *CheckDomainRequest, opts ...scw.RequestOption) (*CheckDomainResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/check-domain",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckDomainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckPEMChain:
func (s *API) CheckPEMChain(req *CheckPEMChainRequest, opts ...scw.RequestOption) (*CheckPEMChainResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/check-pem-chain",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckPEMChainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPurgeRequests: List all purge requests, for a Scaleway Organization or Scaleway Project. This enables you to retrieve a history of all previously-made purge requests. By default, the purge requests returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListPurgeRequests(req *ListPurgeRequestsRequest, opts ...scw.RequestOption) (*ListPurgeRequestsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "pipeline_id", req.PipelineID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/purge-requests",
Query: query,
}
var resp ListPurgeRequestsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePurgeRequest: Create a new purge request. You must specify either the `all` field (to purge all content) or a list of `assets` (to define the precise assets to purge).
func (s *API) CreatePurgeRequest(req *CreatePurgeRequestRequest, opts ...scw.RequestOption) (*PurgeRequest, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/purge-requests",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PurgeRequest
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPurgeRequest: Retrieve information about a purge request, specified by its `purge_request_id`. Its full details, including `status` and `target`, are returned in the response object.
func (s *API) GetPurgeRequest(req *GetPurgeRequestRequest, opts ...scw.RequestOption) (*PurgeRequest, error) {
var err error
if fmt.Sprint(req.PurgeRequestID) == "" {
return nil, errors.New("field PurgeRequestID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/purge-requests/" + fmt.Sprint(req.PurgeRequestID) + "",
}
var resp PurgeRequest
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckLBOrigin:
func (s *API) CheckLBOrigin(req *CheckLBOriginRequest, opts ...scw.RequestOption) (*CheckLBOriginResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/edge-services/v1alpha1/check-lb-origin",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckLBOriginResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPlans:
func (s *API) ListPlans(opts ...scw.RequestOption) (*ListPlansResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/plans",
}
var resp ListPlansResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SelectPlan:
func (s *API) SelectPlan(req *SelectPlanRequest, opts ...scw.RequestOption) (*Plan, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/edge-services/v1alpha1/current-plan",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Plan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCurrentPlan:
func (s *API) GetCurrentPlan(req *GetCurrentPlanRequest, opts ...scw.RequestOption) (*Plan, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/current-plan/" + fmt.Sprint(req.ProjectID) + "",
}
var resp Plan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCurrentPlan:
func (s *API) DeleteCurrentPlan(req *DeleteCurrentPlanRequest, opts ...scw.RequestOption) error {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/edge-services/v1alpha1/current-plan/" + fmt.Sprint(req.ProjectID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetBilling: Gives information on the currently selected Edge Services subscription plan, resource usage and associated billing information for this calendar month (including whether consumption falls within or exceeds the currently selected subscription plan.).
func (s *API) GetBilling(req *GetBillingRequest, opts ...scw.RequestOption) (*GetBillingResponse, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/edge-services/v1alpha1/billing/" + fmt.Sprint(req.ProjectID) + "",
}
var resp GetBillingResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
edge_services_utils.go 0000664 0000000 0000000 00000005633 14747113137 0033547 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/v1alpha1 package edge_services //nolint:revive
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 5 * time.Second
defaultTimeout = 5 * time.Minute
)
// WaitForPipelineRequest is used by WaitForPipeline method.
type WaitForPipelineRequest struct {
PipelineID string
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForPipeline wait for a pipeline to be in a "terminal state" before returning.
func (s *API) WaitForPipeline(req *WaitForPipelineRequest, opts ...scw.RequestOption) (*Pipeline, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[PipelineStatus]struct{}{
PipelineStatusReady: {},
PipelineStatusError: {},
PipelineStatusUnknownStatus: {},
PipelineStatusWarning: {},
}
res, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
pipeline, err := s.GetPipeline(&GetPipelineRequest{
PipelineID: req.PipelineID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[pipeline.Status]
return pipeline, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for pipeline failed")
}
return res.(*Pipeline), nil
}
// WaitForPurgeRequestRequest is used by WaitForPurgeRequest method.
type WaitForPurgeRequestRequest struct {
PurgeRequestID string
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForPurgeRequest wait for a purge request to be in a "terminal state" before returning.
func (s *API) WaitForPurgeRequest(req *WaitForPurgeRequestRequest, opts ...scw.RequestOption) (*PurgeRequest, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[PurgeRequestStatus]struct{}{
PurgeRequestStatusDone: {},
PurgeRequestStatusError: {},
PurgeRequestStatusUnknownStatus: {},
}
res, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
purgeRequest, err := s.GetPurgeRequest(&GetPurgeRequestRequest{
PurgeRequestID: req.PurgeRequestID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[purgeRequest.Status]
return purgeRequest, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for purge request failed")
}
return res.(*PurgeRequest), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0031076 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/edge_services/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000000021 14747113137 0033253 0 ustar 00root root 0000000 0000000 package sweepers
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/ 0000775 0000000 0000000 00000000000 14747113137 0025140 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0026555 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/v1alpha1/flexibleip_helpers.go 0000664 0000000 0000000 00000004033 14747113137 0032751 0 ustar 00root root 0000000 0000000 package flexibleip
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
waitForFlexibleIPDefaultTimeout = 15 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForFlexibleIPRequest is used by WaitForFlexibleIP method.
type WaitForFlexibleIPRequest struct {
FipID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForFlexibleIP waits for the FlexibleIP to be in a ready state before returning.
func (s *API) WaitForFlexibleIP(req *WaitForFlexibleIPRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
timeout := waitForFlexibleIPDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
fipTerminalStatus := map[FlexibleIPStatus]struct{}{
FlexibleIPStatusError: {},
FlexibleIPStatusReady: {},
FlexibleIPStatusAttached: {},
FlexibleIPStatusLocked: {},
}
macAddressTerminalStatus := map[MACAddressStatus]struct{}{
MACAddressStatusUnknown: {},
MACAddressStatusReady: {},
MACAddressStatusUsed: {},
MACAddressStatusError: {},
}
fip, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
fip, err := s.GetFlexibleIP(&GetFlexibleIPRequest{
FipID: req.FipID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
// Check if the MACAddress is in a terminal state
isMacAddressTerminal := true
if fip.MacAddress != nil {
_, isMacAddressTerminal = macAddressTerminalStatus[fip.MacAddress.Status]
}
_, isTerminal := fipTerminalStatus[fip.Status]
return fip, isTerminal && isMacAddressTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for FlexibleIP failed")
}
return fip.(*FlexibleIP), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/v1alpha1/flexibleip_sdk.go 0000664 0000000 0000000 00000061534 14747113137 0032101 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package flexibleip provides methods and message types of the flexibleip v1alpha1 API.
package flexibleip
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type FlexibleIPStatus string
const (
FlexibleIPStatusUnknown = FlexibleIPStatus("unknown")
FlexibleIPStatusReady = FlexibleIPStatus("ready")
FlexibleIPStatusUpdating = FlexibleIPStatus("updating")
FlexibleIPStatusAttached = FlexibleIPStatus("attached")
FlexibleIPStatusError = FlexibleIPStatus("error")
FlexibleIPStatusDetaching = FlexibleIPStatus("detaching")
FlexibleIPStatusLocked = FlexibleIPStatus("locked")
)
func (enum FlexibleIPStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum FlexibleIPStatus) Values() []FlexibleIPStatus {
return []FlexibleIPStatus{
"unknown",
"ready",
"updating",
"attached",
"error",
"detaching",
"locked",
}
}
func (enum FlexibleIPStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FlexibleIPStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FlexibleIPStatus(FlexibleIPStatus(tmp).String())
return nil
}
type ListFlexibleIPsRequestOrderBy string
const (
ListFlexibleIPsRequestOrderByCreatedAtAsc = ListFlexibleIPsRequestOrderBy("created_at_asc")
ListFlexibleIPsRequestOrderByCreatedAtDesc = ListFlexibleIPsRequestOrderBy("created_at_desc")
)
func (enum ListFlexibleIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListFlexibleIPsRequestOrderBy) Values() []ListFlexibleIPsRequestOrderBy {
return []ListFlexibleIPsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListFlexibleIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListFlexibleIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListFlexibleIPsRequestOrderBy(ListFlexibleIPsRequestOrderBy(tmp).String())
return nil
}
type MACAddressStatus string
const (
MACAddressStatusUnknown = MACAddressStatus("unknown")
MACAddressStatusReady = MACAddressStatus("ready")
MACAddressStatusUpdating = MACAddressStatus("updating")
MACAddressStatusUsed = MACAddressStatus("used")
MACAddressStatusError = MACAddressStatus("error")
MACAddressStatusDeleting = MACAddressStatus("deleting")
)
func (enum MACAddressStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum MACAddressStatus) Values() []MACAddressStatus {
return []MACAddressStatus{
"unknown",
"ready",
"updating",
"used",
"error",
"deleting",
}
}
func (enum MACAddressStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MACAddressStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MACAddressStatus(MACAddressStatus(tmp).String())
return nil
}
type MACAddressType string
const (
MACAddressTypeUnknownType = MACAddressType("unknown_type")
MACAddressTypeVmware = MACAddressType("vmware")
MACAddressTypeXen = MACAddressType("xen")
MACAddressTypeKvm = MACAddressType("kvm")
)
func (enum MACAddressType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum MACAddressType) Values() []MACAddressType {
return []MACAddressType{
"unknown_type",
"vmware",
"xen",
"kvm",
}
}
func (enum MACAddressType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MACAddressType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MACAddressType(MACAddressType(tmp).String())
return nil
}
// MACAddress: mac address.
type MACAddress struct {
// ID: ID of the flexible IP.
ID string `json:"id"`
// MacAddress: mAC address of the Virtual MAC.
MacAddress string `json:"mac_address"`
// MacType: type of virtual MAC.
// Default value: unknown_type
MacType MACAddressType `json:"mac_type"`
// Status: status of virtual MAC.
// Default value: unknown
Status MACAddressStatus `json:"status"`
// UpdatedAt: date on which the virtual MAC was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: date on which the virtual MAC was created.
CreatedAt *time.Time `json:"created_at"`
// Zone: mAC address IP Availability Zone.
Zone scw.Zone `json:"zone"`
}
// FlexibleIP: flexible ip.
type FlexibleIP struct {
// ID: ID of the flexible IP.
ID string `json:"id"`
// OrganizationID: ID of the Organization the flexible IP is attached to.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the Project the flexible IP is attached to.
ProjectID string `json:"project_id"`
// Description: flexible IP description.
Description string `json:"description"`
// Tags: flexible IP tags.
Tags []string `json:"tags"`
// UpdatedAt: date on which the flexible IP was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: date on which the flexible IP was created.
CreatedAt *time.Time `json:"created_at"`
// Status: - ready : flexible IP is created and ready to be attached to a server or to be associated with a virtual MAC.
// - updating: flexible IP is being attached to a server or a virtual MAC operation is ongoing
// - attached: flexible IP is attached to a server
// - error: a flexible IP operation resulted in an error
// - detaching: flexible IP is being detached from a server
// - locked: the resource of the flexible IP is locked.
// Default value: unknown
Status FlexibleIPStatus `json:"status"`
// IPAddress: IP of the flexible IP.
IPAddress scw.IPNet `json:"ip_address"`
// MacAddress: mAC address of the flexible IP.
MacAddress *MACAddress `json:"mac_address"`
// ServerID: ID of the server linked to the flexible IP.
ServerID *string `json:"server_id"`
// Reverse: reverse DNS value.
Reverse string `json:"reverse"`
// Zone: availability Zone of the flexible IP.
Zone scw.Zone `json:"zone"`
}
// AttachFlexibleIPRequest: attach flexible ip request.
type AttachFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipsIDs: multiple IDs can be provided, but note that flexible IPs must belong to the same MAC group (see details about MAC groups).
FipsIDs []string `json:"fips_ids"`
// ServerID: ID of the server on which to attach the flexible IPs.
ServerID string `json:"server_id"`
}
// AttachFlexibleIPsResponse: attach flexible i ps response.
type AttachFlexibleIPsResponse struct {
// TotalCount: total count of flexible IPs that are being updated.
TotalCount uint32 `json:"total_count"`
// FlexibleIPs: list of flexible IPs in an updating state.
FlexibleIPs []*FlexibleIP `json:"flexible_ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *AttachFlexibleIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *AttachFlexibleIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*AttachFlexibleIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.FlexibleIPs = append(r.FlexibleIPs, results.FlexibleIPs...)
r.TotalCount += uint32(len(results.FlexibleIPs))
return uint32(len(results.FlexibleIPs)), nil
}
// CreateFlexibleIPRequest: create flexible ip request.
type CreateFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: ID of the project to associate with the Flexible IP.
ProjectID string `json:"project_id"`
// Description: flexible IP description (max. of 255 characters).
Description string `json:"description"`
// Tags: tags to associate to the flexible IP.
Tags []string `json:"tags"`
// ServerID: ID of the server to which the newly created flexible IP will be attached.
ServerID *string `json:"server_id,omitempty"`
// Reverse: value of the reverse DNS.
Reverse *string `json:"reverse,omitempty"`
// IsIPv6: defines whether the flexible IP has an IPv6 address.
IsIPv6 bool `json:"is_ipv6"`
}
// DeleteFlexibleIPRequest: delete flexible ip request.
type DeleteFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: ID of the flexible IP to delete.
FipID string `json:"-"`
}
// DeleteMACAddrRequest: delete mac addr request.
type DeleteMACAddrRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: if the flexible IP belongs to a MAC group, the MAC will be removed from both the MAC group and flexible IP.
FipID string `json:"-"`
}
// DetachFlexibleIPRequest: detach flexible ip request.
type DetachFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipsIDs: list of flexible IP IDs to detach from a server. Multiple IDs can be provided. Note that flexible IPs must belong to the same MAC group.
FipsIDs []string `json:"fips_ids"`
}
// DetachFlexibleIPsResponse: detach flexible i ps response.
type DetachFlexibleIPsResponse struct {
// TotalCount: total count of flexible IPs that are being detached.
TotalCount uint32 `json:"total_count"`
// FlexibleIPs: list of flexible IPs in a detaching state.
FlexibleIPs []*FlexibleIP `json:"flexible_ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *DetachFlexibleIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *DetachFlexibleIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*DetachFlexibleIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.FlexibleIPs = append(r.FlexibleIPs, results.FlexibleIPs...)
r.TotalCount += uint32(len(results.FlexibleIPs))
return uint32(len(results.FlexibleIPs)), nil
}
// DuplicateMACAddrRequest: duplicate mac addr request.
type DuplicateMACAddrRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: note that the flexible IPs need to be attached to the same server.
FipID string `json:"-"`
// DuplicateFromFipID: note that flexible IPs need to be attached to the same server.
DuplicateFromFipID string `json:"duplicate_from_fip_id"`
}
// GenerateMACAddrRequest: generate mac addr request.
type GenerateMACAddrRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: ID of the flexible IP for which to generate a virtual MAC.
FipID string `json:"-"`
// MacType: tODO.
// Default value: unknown_type
MacType MACAddressType `json:"mac_type"`
}
// GetFlexibleIPRequest: get flexible ip request.
type GetFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: ID of the flexible IP.
FipID string `json:"-"`
}
// ListFlexibleIPsRequest: list flexible i ps request.
type ListFlexibleIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order of the returned flexible IPs.
// Default value: created_at_asc
OrderBy ListFlexibleIPsRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of flexible IPs per page.
PageSize *uint32 `json:"-"`
// Tags: filter by tag, only flexible IPs with one or more matching tags will be returned.
Tags []string `json:"-"`
// Status: filter by status, only flexible IPs with this status will be returned.
Status []FlexibleIPStatus `json:"-"`
// ServerIDs: filter by server IDs, only flexible IPs with these server IDs will be returned.
ServerIDs []string `json:"-"`
// OrganizationID: filter by Organization ID, only flexible IPs from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: filter by Project ID, only flexible IPs from this Project will be returned.
ProjectID *string `json:"-"`
}
// ListFlexibleIPsResponse: list flexible i ps response.
type ListFlexibleIPsResponse struct {
// TotalCount: total count of matching flexible IPs.
TotalCount uint32 `json:"total_count"`
// FlexibleIPs: list of all flexible IPs.
FlexibleIPs []*FlexibleIP `json:"flexible_ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFlexibleIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFlexibleIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListFlexibleIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.FlexibleIPs = append(r.FlexibleIPs, results.FlexibleIPs...)
r.TotalCount += uint32(len(results.FlexibleIPs))
return uint32(len(results.FlexibleIPs)), nil
}
// MoveMACAddrRequest: move mac addr request.
type MoveMACAddrRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
FipID string `json:"-"`
DstFipID string `json:"dst_fip_id"`
}
// UpdateFlexibleIPRequest: update flexible ip request.
type UpdateFlexibleIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FipID: ID of the flexible IP to update.
FipID string `json:"-"`
// Description: flexible IP description (max. 255 characters).
Description *string `json:"description,omitempty"`
// Tags: tags associated with the flexible IP.
Tags *[]string `json:"tags,omitempty"`
// Reverse: value of the reverse DNS.
Reverse *string `json:"reverse,omitempty"`
}
// This API allows you to manage your Elastic Metal servers' flexible public IP addresses.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// CreateFlexibleIP: Generate a new flexible IP within a given zone, specifying its configuration including Project ID and description.
func (s *API) CreateFlexibleIP(req *CreateFlexibleIPRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFlexibleIP: Retrieve information about an existing flexible IP, specified by its ID and zone. Its full details, including Project ID, description and status, are returned in the response object.
func (s *API) GetFlexibleIP(req *GetFlexibleIPRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return nil, errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "",
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFlexibleIPs: List all flexible IPs within a given zone.
func (s *API) ListFlexibleIPs(req *ListFlexibleIPsRequest, opts ...scw.RequestOption) (*ListFlexibleIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "server_ids", req.ServerIDs)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips",
Query: query,
}
var resp ListFlexibleIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateFlexibleIP: Update the parameters of an existing flexible IP, specified by its ID and zone. These parameters include tags and description.
func (s *API) UpdateFlexibleIP(req *UpdateFlexibleIPRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return nil, errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteFlexibleIP: Delete an existing flexible IP, specified by its ID and zone. Note that deleting a flexible IP is permanent and cannot be undone.
func (s *API) DeleteFlexibleIP(req *DeleteFlexibleIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AttachFlexibleIP: Attach an existing flexible IP to a specified Elastic Metal server.
func (s *API) AttachFlexibleIP(req *AttachFlexibleIPRequest, opts ...scw.RequestOption) (*AttachFlexibleIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/attach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AttachFlexibleIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachFlexibleIP: Detach an existing flexible IP from a specified Elastic Metal server.
func (s *API) DetachFlexibleIP(req *DetachFlexibleIPRequest, opts ...scw.RequestOption) (*DetachFlexibleIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/detach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DetachFlexibleIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GenerateMACAddr: Generate a virtual MAC (Media Access Control) address on an existing flexible IP.
func (s *API) GenerateMACAddr(req *GenerateMACAddrRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return nil, errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "/mac",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DuplicateMACAddr: Duplicate a virtual MAC address from a given flexible IP to another flexible IP attached to the same server.
func (s *API) DuplicateMACAddr(req *DuplicateMACAddrRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return nil, errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "/mac/duplicate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// MoveMACAddr: Relocate a virtual MAC (Media Access Control) address from an existing flexible IP to a different flexible IP.
func (s *API) MoveMACAddr(req *MoveMACAddrRequest, opts ...scw.RequestOption) (*FlexibleIP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return nil, errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "/mac/move",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FlexibleIP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteMACAddr: Detach a given MAC (Media Access Control) address from an existing flexible IP.
func (s *API) DeleteMACAddr(req *DeleteMACAddrRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FipID) == "" {
return errors.New("field FipID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/flexible-ip/v1alpha1/zones/" + fmt.Sprint(req.Zone) + "/fips/" + fmt.Sprint(req.FipID) + "/mac",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0030412 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/flexibleip/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000001724 14747113137 0032602 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
flexibleip "github.com/scaleway/scaleway-sdk-go/api/flexibleip/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepFlexibleIP(scwClient *scw.Client, zone scw.Zone) error {
fipAPI := flexibleip.NewAPI(scwClient)
listIPs, err := fipAPI.ListFlexibleIPs(&flexibleip.ListFlexibleIPsRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
logger.Warningf("error listing ips in (%s) in sweeper: %s", zone, err)
return nil
}
for _, ip := range listIPs.FlexibleIPs {
err := fipAPI.DeleteFlexibleIP(&flexibleip.DeleteFlexibleIPRequest{
FipID: ip.ID,
Zone: zone,
})
if err != nil {
return fmt.Errorf("error deleting ip in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&flexibleip.API{}).Zones() {
err := SweepFlexibleIP(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/ 0000775 0000000 0000000 00000000000 14747113137 0024642 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0026105 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/v1beta1/function_helpers.go 0000664 0000000 0000000 00000015613 14747113137 0032011 0 ustar 00root root 0000000 0000000 package function
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
waitForNamespaceDefaultTimeout = 15 * time.Minute
waitForCronDefaultTimeout = 15 * time.Minute
waitForDomainDefaultTimeout = 15 * time.Minute
waitForFunctionDefaultTimeout = 15 * time.Minute
waitForTriggerDefaultTimeout = 15 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForNamespaceRequest is used by WaitForNamespace method.
type WaitForNamespaceRequest struct {
NamespaceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForNamespace waits for the Namespace to be in a ready state before returning.
func (s *API) WaitForNamespace(req *WaitForNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
timeout := waitForNamespaceDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[NamespaceStatus]struct{}{
NamespaceStatusError: {},
NamespaceStatusReady: {},
NamespaceStatusLocked: {},
}
namespace, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
namespace, err := s.GetNamespace(&GetNamespaceRequest{
NamespaceID: req.NamespaceID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[namespace.Status]
return namespace, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Namespace failed")
}
return namespace.(*Namespace), nil
}
// WaitForFunctionRequest is used by WaitForNamespace method.
type WaitForFunctionRequest struct {
FunctionID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForFunction waits for the Function to be in a ready state before returning.
func (s *API) WaitForFunction(req *WaitForFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
timeout := waitForFunctionDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[FunctionStatus]struct{}{
FunctionStatusCreated: {},
FunctionStatusError: {},
FunctionStatusLocked: {},
FunctionStatusReady: {},
}
function, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
function, err := s.GetFunction(&GetFunctionRequest{
FunctionID: req.FunctionID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[function.Status]
return function, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for function failed")
}
return function.(*Function), nil
}
// WaitForCronRequest is used by WaitForNamespace method.
type WaitForCronRequest struct {
CronID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForCron waits for the Cron to be in a ready state before returning.
func (s *API) WaitForCron(req *WaitForCronRequest, opts ...scw.RequestOption) (*Cron, error) {
timeout := waitForCronDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[CronStatus]struct{}{
CronStatusError: {},
CronStatusReady: {},
CronStatusLocked: {},
}
cron, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
cron, err := s.GetCron(&GetCronRequest{
CronID: req.CronID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[cron.Status]
return cron, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Cron failed")
}
return cron.(*Cron), nil
}
// WaitForDomainRequest waits for the Domain to be in a ready state before returning.
type WaitForDomainRequest struct {
DomainID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDomain waits for the Domain to be in a ready state before returning.
func (s *API) WaitForDomain(req *WaitForDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
timeout := waitForDomainDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DomainStatus]struct{}{
DomainStatusError: {},
DomainStatusReady: {},
}
domain, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
domain, err := s.GetDomain(&GetDomainRequest{
DomainID: req.DomainID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[domain.Status]
return domain, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Domain failed")
}
return domain.(*Domain), nil
}
// WaitForTriggerRequest waits for the Trigger to be in a ready state before returning.
type WaitForTriggerRequest struct {
TriggerID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForTrigger waits for the Trigger to be in a ready state before returning.
func (s *API) WaitForTrigger(req *WaitForTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
timeout := waitForTriggerDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[TriggerStatus]struct{}{
TriggerStatusError: {},
TriggerStatusReady: {},
}
trigger, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
trigger, err := s.GetTrigger(&GetTriggerRequest{
TriggerID: req.TriggerID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[trigger.Status]
return trigger, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for Trigger failed")
}
return trigger.(*Trigger), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/v1beta1/function_sdk.go 0000664 0000000 0000000 00000245523 14747113137 0031135 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package function provides methods and message types of the function v1beta1 API.
package function
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type CronStatus string
const (
CronStatusUnknown = CronStatus("unknown")
CronStatusReady = CronStatus("ready")
CronStatusDeleting = CronStatus("deleting")
CronStatusError = CronStatus("error")
CronStatusLocked = CronStatus("locked")
CronStatusCreating = CronStatus("creating")
CronStatusPending = CronStatus("pending")
)
func (enum CronStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum CronStatus) Values() []CronStatus {
return []CronStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
}
}
func (enum CronStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *CronStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = CronStatus(CronStatus(tmp).String())
return nil
}
type DomainStatus string
const (
DomainStatusUnknown = DomainStatus("unknown")
DomainStatusReady = DomainStatus("ready")
DomainStatusDeleting = DomainStatus("deleting")
DomainStatusError = DomainStatus("error")
DomainStatusCreating = DomainStatus("creating")
DomainStatusPending = DomainStatus("pending")
)
func (enum DomainStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DomainStatus) Values() []DomainStatus {
return []DomainStatus{
"unknown",
"ready",
"deleting",
"error",
"creating",
"pending",
}
}
func (enum DomainStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainStatus(DomainStatus(tmp).String())
return nil
}
type FunctionHTTPOption string
const (
FunctionHTTPOptionUnknownHTTPOption = FunctionHTTPOption("unknown_http_option")
FunctionHTTPOptionEnabled = FunctionHTTPOption("enabled")
FunctionHTTPOptionRedirected = FunctionHTTPOption("redirected")
)
func (enum FunctionHTTPOption) String() string {
if enum == "" {
// return default value if empty
return "unknown_http_option"
}
return string(enum)
}
func (enum FunctionHTTPOption) Values() []FunctionHTTPOption {
return []FunctionHTTPOption{
"unknown_http_option",
"enabled",
"redirected",
}
}
func (enum FunctionHTTPOption) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FunctionHTTPOption) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FunctionHTTPOption(FunctionHTTPOption(tmp).String())
return nil
}
type FunctionPrivacy string
const (
FunctionPrivacyUnknownPrivacy = FunctionPrivacy("unknown_privacy")
FunctionPrivacyPublic = FunctionPrivacy("public")
FunctionPrivacyPrivate = FunctionPrivacy("private")
)
func (enum FunctionPrivacy) String() string {
if enum == "" {
// return default value if empty
return "unknown_privacy"
}
return string(enum)
}
func (enum FunctionPrivacy) Values() []FunctionPrivacy {
return []FunctionPrivacy{
"unknown_privacy",
"public",
"private",
}
}
func (enum FunctionPrivacy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FunctionPrivacy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FunctionPrivacy(FunctionPrivacy(tmp).String())
return nil
}
type FunctionRuntime string
const (
FunctionRuntimeUnknownRuntime = FunctionRuntime("unknown_runtime")
FunctionRuntimeGolang = FunctionRuntime("golang")
FunctionRuntimePython = FunctionRuntime("python")
FunctionRuntimePython3 = FunctionRuntime("python3")
FunctionRuntimeNode8 = FunctionRuntime("node8")
FunctionRuntimeNode10 = FunctionRuntime("node10")
FunctionRuntimeNode14 = FunctionRuntime("node14")
FunctionRuntimeNode16 = FunctionRuntime("node16")
FunctionRuntimeNode17 = FunctionRuntime("node17")
FunctionRuntimePython37 = FunctionRuntime("python37")
FunctionRuntimePython38 = FunctionRuntime("python38")
FunctionRuntimePython39 = FunctionRuntime("python39")
FunctionRuntimePython310 = FunctionRuntime("python310")
FunctionRuntimeGo113 = FunctionRuntime("go113")
FunctionRuntimeGo117 = FunctionRuntime("go117")
FunctionRuntimeGo118 = FunctionRuntime("go118")
FunctionRuntimeNode18 = FunctionRuntime("node18")
FunctionRuntimeRust165 = FunctionRuntime("rust165")
FunctionRuntimeGo119 = FunctionRuntime("go119")
FunctionRuntimePython311 = FunctionRuntime("python311")
FunctionRuntimePhp82 = FunctionRuntime("php82")
FunctionRuntimeNode19 = FunctionRuntime("node19")
FunctionRuntimeGo120 = FunctionRuntime("go120")
FunctionRuntimeNode20 = FunctionRuntime("node20")
FunctionRuntimeGo121 = FunctionRuntime("go121")
FunctionRuntimeNode22 = FunctionRuntime("node22")
FunctionRuntimePython312 = FunctionRuntime("python312")
FunctionRuntimePhp83 = FunctionRuntime("php83")
FunctionRuntimeGo122 = FunctionRuntime("go122")
FunctionRuntimeRust179 = FunctionRuntime("rust179")
)
func (enum FunctionRuntime) String() string {
if enum == "" {
// return default value if empty
return "unknown_runtime"
}
return string(enum)
}
func (enum FunctionRuntime) Values() []FunctionRuntime {
return []FunctionRuntime{
"unknown_runtime",
"golang",
"python",
"python3",
"node8",
"node10",
"node14",
"node16",
"node17",
"python37",
"python38",
"python39",
"python310",
"go113",
"go117",
"go118",
"node18",
"rust165",
"go119",
"python311",
"php82",
"node19",
"go120",
"node20",
"go121",
"node22",
"python312",
"php83",
"go122",
"rust179",
}
}
func (enum FunctionRuntime) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FunctionRuntime) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FunctionRuntime(FunctionRuntime(tmp).String())
return nil
}
type FunctionSandbox string
const (
// Unknown sandbox.
FunctionSandboxUnknownSandbox = FunctionSandbox("unknown_sandbox")
// Legacy sandboxing with slower cold starts. Fully supports the Linux system call interface.
FunctionSandboxV1 = FunctionSandbox("v1")
// Recommended sandboxing with faster cold starts.
FunctionSandboxV2 = FunctionSandbox("v2")
)
func (enum FunctionSandbox) String() string {
if enum == "" {
// return default value if empty
return "unknown_sandbox"
}
return string(enum)
}
func (enum FunctionSandbox) Values() []FunctionSandbox {
return []FunctionSandbox{
"unknown_sandbox",
"v1",
"v2",
}
}
func (enum FunctionSandbox) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FunctionSandbox) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FunctionSandbox(FunctionSandbox(tmp).String())
return nil
}
type FunctionStatus string
const (
FunctionStatusUnknown = FunctionStatus("unknown")
FunctionStatusReady = FunctionStatus("ready")
FunctionStatusDeleting = FunctionStatus("deleting")
FunctionStatusError = FunctionStatus("error")
FunctionStatusLocked = FunctionStatus("locked")
FunctionStatusCreating = FunctionStatus("creating")
FunctionStatusPending = FunctionStatus("pending")
FunctionStatusCreated = FunctionStatus("created")
)
func (enum FunctionStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum FunctionStatus) Values() []FunctionStatus {
return []FunctionStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
"created",
}
}
func (enum FunctionStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *FunctionStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = FunctionStatus(FunctionStatus(tmp).String())
return nil
}
type ListCronsRequestOrderBy string
const (
ListCronsRequestOrderByCreatedAtAsc = ListCronsRequestOrderBy("created_at_asc")
ListCronsRequestOrderByCreatedAtDesc = ListCronsRequestOrderBy("created_at_desc")
)
func (enum ListCronsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListCronsRequestOrderBy) Values() []ListCronsRequestOrderBy {
return []ListCronsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListCronsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListCronsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListCronsRequestOrderBy(ListCronsRequestOrderBy(tmp).String())
return nil
}
type ListDomainsRequestOrderBy string
const (
ListDomainsRequestOrderByCreatedAtAsc = ListDomainsRequestOrderBy("created_at_asc")
ListDomainsRequestOrderByCreatedAtDesc = ListDomainsRequestOrderBy("created_at_desc")
ListDomainsRequestOrderByHostnameAsc = ListDomainsRequestOrderBy("hostname_asc")
ListDomainsRequestOrderByHostnameDesc = ListDomainsRequestOrderBy("hostname_desc")
)
func (enum ListDomainsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDomainsRequestOrderBy) Values() []ListDomainsRequestOrderBy {
return []ListDomainsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"hostname_asc",
"hostname_desc",
}
}
func (enum ListDomainsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDomainsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDomainsRequestOrderBy(ListDomainsRequestOrderBy(tmp).String())
return nil
}
type ListFunctionsRequestOrderBy string
const (
ListFunctionsRequestOrderByCreatedAtAsc = ListFunctionsRequestOrderBy("created_at_asc")
ListFunctionsRequestOrderByCreatedAtDesc = ListFunctionsRequestOrderBy("created_at_desc")
ListFunctionsRequestOrderByNameAsc = ListFunctionsRequestOrderBy("name_asc")
ListFunctionsRequestOrderByNameDesc = ListFunctionsRequestOrderBy("name_desc")
)
func (enum ListFunctionsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListFunctionsRequestOrderBy) Values() []ListFunctionsRequestOrderBy {
return []ListFunctionsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListFunctionsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListFunctionsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListFunctionsRequestOrderBy(ListFunctionsRequestOrderBy(tmp).String())
return nil
}
type ListNamespacesRequestOrderBy string
const (
ListNamespacesRequestOrderByCreatedAtAsc = ListNamespacesRequestOrderBy("created_at_asc")
ListNamespacesRequestOrderByCreatedAtDesc = ListNamespacesRequestOrderBy("created_at_desc")
ListNamespacesRequestOrderByNameAsc = ListNamespacesRequestOrderBy("name_asc")
ListNamespacesRequestOrderByNameDesc = ListNamespacesRequestOrderBy("name_desc")
)
func (enum ListNamespacesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNamespacesRequestOrderBy) Values() []ListNamespacesRequestOrderBy {
return []ListNamespacesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListNamespacesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNamespacesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNamespacesRequestOrderBy(ListNamespacesRequestOrderBy(tmp).String())
return nil
}
type ListTokensRequestOrderBy string
const (
ListTokensRequestOrderByCreatedAtAsc = ListTokensRequestOrderBy("created_at_asc")
ListTokensRequestOrderByCreatedAtDesc = ListTokensRequestOrderBy("created_at_desc")
)
func (enum ListTokensRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTokensRequestOrderBy) Values() []ListTokensRequestOrderBy {
return []ListTokensRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListTokensRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTokensRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTokensRequestOrderBy(ListTokensRequestOrderBy(tmp).String())
return nil
}
type ListTriggersRequestOrderBy string
const (
// Order by creation date ascending.
ListTriggersRequestOrderByCreatedAtAsc = ListTriggersRequestOrderBy("created_at_asc")
// Order by creation date descending.
ListTriggersRequestOrderByCreatedAtDesc = ListTriggersRequestOrderBy("created_at_desc")
)
func (enum ListTriggersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTriggersRequestOrderBy) Values() []ListTriggersRequestOrderBy {
return []ListTriggersRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListTriggersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTriggersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTriggersRequestOrderBy(ListTriggersRequestOrderBy(tmp).String())
return nil
}
type NamespaceStatus string
const (
NamespaceStatusUnknown = NamespaceStatus("unknown")
NamespaceStatusReady = NamespaceStatus("ready")
NamespaceStatusDeleting = NamespaceStatus("deleting")
NamespaceStatusError = NamespaceStatus("error")
NamespaceStatusLocked = NamespaceStatus("locked")
NamespaceStatusCreating = NamespaceStatus("creating")
NamespaceStatusPending = NamespaceStatus("pending")
)
func (enum NamespaceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NamespaceStatus) Values() []NamespaceStatus {
return []NamespaceStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
"creating",
"pending",
}
}
func (enum NamespaceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NamespaceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NamespaceStatus(NamespaceStatus(tmp).String())
return nil
}
type RuntimeStatus string
const (
RuntimeStatusUnknownStatus = RuntimeStatus("unknown_status")
RuntimeStatusBeta = RuntimeStatus("beta")
RuntimeStatusAvailable = RuntimeStatus("available")
RuntimeStatusDeprecated = RuntimeStatus("deprecated")
RuntimeStatusEndOfSupport = RuntimeStatus("end_of_support")
RuntimeStatusEndOfLife = RuntimeStatus("end_of_life")
)
func (enum RuntimeStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum RuntimeStatus) Values() []RuntimeStatus {
return []RuntimeStatus{
"unknown_status",
"beta",
"available",
"deprecated",
"end_of_support",
"end_of_life",
}
}
func (enum RuntimeStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RuntimeStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RuntimeStatus(RuntimeStatus(tmp).String())
return nil
}
type TokenStatus string
const (
TokenStatusUnknown = TokenStatus("unknown")
TokenStatusReady = TokenStatus("ready")
TokenStatusDeleting = TokenStatus("deleting")
TokenStatusError = TokenStatus("error")
TokenStatusCreating = TokenStatus("creating")
)
func (enum TokenStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum TokenStatus) Values() []TokenStatus {
return []TokenStatus{
"unknown",
"ready",
"deleting",
"error",
"creating",
}
}
func (enum TokenStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TokenStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TokenStatus(TokenStatus(tmp).String())
return nil
}
type TriggerInputType string
const (
// Unknown input type.
TriggerInputTypeUnknownInputType = TriggerInputType("unknown_input_type")
TriggerInputTypeSqs = TriggerInputType("sqs")
// Scaleway Messaging and Queuing SQS queue.
TriggerInputTypeScwSqs = TriggerInputType("scw_sqs")
TriggerInputTypeNats = TriggerInputType("nats")
// Scaleway Messaging and Queuing NATS subject.
TriggerInputTypeScwNats = TriggerInputType("scw_nats")
)
func (enum TriggerInputType) String() string {
if enum == "" {
// return default value if empty
return "unknown_input_type"
}
return string(enum)
}
func (enum TriggerInputType) Values() []TriggerInputType {
return []TriggerInputType{
"unknown_input_type",
"sqs",
"scw_sqs",
"nats",
"scw_nats",
}
}
func (enum TriggerInputType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TriggerInputType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TriggerInputType(TriggerInputType(tmp).String())
return nil
}
type TriggerStatus string
const (
// Unknown status.
TriggerStatusUnknownStatus = TriggerStatus("unknown_status")
// Ready status.
TriggerStatusReady = TriggerStatus("ready")
// Deleting status.
TriggerStatusDeleting = TriggerStatus("deleting")
// Error status.
TriggerStatusError = TriggerStatus("error")
// Creating status.
TriggerStatusCreating = TriggerStatus("creating")
// Pending status.
TriggerStatusPending = TriggerStatus("pending")
)
func (enum TriggerStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum TriggerStatus) Values() []TriggerStatus {
return []TriggerStatus{
"unknown_status",
"ready",
"deleting",
"error",
"creating",
"pending",
}
}
func (enum TriggerStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TriggerStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TriggerStatus(TriggerStatus(tmp).String())
return nil
}
// SecretHashedValue: secret hashed value.
type SecretHashedValue struct {
Key string `json:"key"`
HashedValue string `json:"hashed_value"`
}
// TriggerMnqNatsClientConfig: trigger mnq nats client config.
type TriggerMnqNatsClientConfig struct {
// Subject: name of the NATS subject the trigger listens to.
Subject string `json:"subject"`
// MnqNatsAccountID: ID of the Messaging and Queuing NATS account.
MnqNatsAccountID string `json:"mnq_nats_account_id"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
// MnqCredentialID: ID of the Messaging and Queuing credentials used to subscribe to the NATS subject.
MnqCredentialID *string `json:"mnq_credential_id"`
}
// TriggerMnqSqsClientConfig: trigger mnq sqs client config.
type TriggerMnqSqsClientConfig struct {
// Queue: name of the SQS queue the trigger listens to.
Queue string `json:"queue"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
// MnqCredentialID: ID of the Messaging and Queuing credentials used to read from the SQS queue.
MnqCredentialID *string `json:"mnq_credential_id"`
}
// TriggerSqsClientConfig: trigger sqs client config.
type TriggerSqsClientConfig struct {
Endpoint string `json:"endpoint"`
QueueURL string `json:"queue_url"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
}
// Secret: secret.
type Secret struct {
Key string `json:"key"`
Value *string `json:"value"`
}
// CreateTriggerRequestMnqNatsClientConfig: create trigger request mnq nats client config.
type CreateTriggerRequestMnqNatsClientConfig struct {
// Subject: name of the NATS subject the trigger should listen to.
Subject string `json:"subject"`
// MnqNatsAccountID: ID of the Messaging and Queuing NATS account.
MnqNatsAccountID string `json:"mnq_nats_account_id"`
// MnqProjectID: ID of the Messaging and Queuing project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
}
// CreateTriggerRequestMnqSqsClientConfig: create trigger request mnq sqs client config.
type CreateTriggerRequestMnqSqsClientConfig struct {
// Queue: name of the SQS queue the trigger should listen to.
Queue string `json:"queue"`
// MnqProjectID: you must have activated SQS on this project.
MnqProjectID string `json:"mnq_project_id"`
// MnqRegion: currently, only the `fr-par` and `nl-ams` regions are available.
MnqRegion string `json:"mnq_region"`
}
// CreateTriggerRequestSqsClientConfig: create trigger request sqs client config.
type CreateTriggerRequestSqsClientConfig struct {
Endpoint string `json:"endpoint"`
QueueURL string `json:"queue_url"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
}
// Cron: cron.
type Cron struct {
// ID: UUID of the cron.
ID string `json:"id"`
// FunctionID: UUID of the function the cron applies to.
FunctionID string `json:"function_id"`
// Schedule: schedule of the cron.
Schedule string `json:"schedule"`
// Args: arguments to pass with the cron.
Args *scw.JSONObject `json:"args"`
// Status: status of the cron.
// Default value: unknown
Status CronStatus `json:"status"`
// Name: name of the cron.
Name string `json:"name"`
}
// Domain: domain.
type Domain struct {
// ID: UUID of the domain.
ID string `json:"id"`
// Hostname: hostname associated with the function.
Hostname string `json:"hostname"`
// FunctionID: UUID of the function the domain is associated with.
FunctionID string `json:"function_id"`
// URL: URL of the function.
URL string `json:"url"`
// Status: state of the doamin.
// Default value: unknown
Status DomainStatus `json:"status"`
// ErrorMessage: error message if the domain is in "error" state.
ErrorMessage *string `json:"error_message"`
}
// Runtime: runtime.
type Runtime struct {
Name string `json:"name"`
Language string `json:"language"`
Version string `json:"version"`
DefaultHandler string `json:"default_handler"`
CodeSample string `json:"code_sample"`
// Status: default value: unknown_status
Status RuntimeStatus `json:"status"`
StatusMessage string `json:"status_message"`
Extension string `json:"extension"`
Implementation string `json:"implementation"`
LogoURL string `json:"logo_url"`
}
// Function: function.
type Function struct {
// ID: UUID of the function.
ID string `json:"id"`
// Name: name of the function.
Name string `json:"name"`
// NamespaceID: UUID of the namespace the function belongs to.
NamespaceID string `json:"namespace_id"`
// Status: status of the function.
// Default value: unknown
Status FunctionStatus `json:"status"`
// EnvironmentVariables: environment variables of the function.
EnvironmentVariables map[string]string `json:"environment_variables"`
// MinScale: minimum number of instances to scale the function to.
MinScale uint32 `json:"min_scale"`
// MaxScale: maximum number of instances to scale the function to.
MaxScale uint32 `json:"max_scale"`
// Runtime: runtime of the function.
// Default value: unknown_runtime
Runtime FunctionRuntime `json:"runtime"`
// MemoryLimit: memory limit of the function in MB.
MemoryLimit uint32 `json:"memory_limit"`
// CPULimit: CPU limit of the function.
CPULimit uint32 `json:"cpu_limit"`
// Timeout: request processing time limit for the function.
Timeout *scw.Duration `json:"timeout"`
// Handler: handler to use for the function.
Handler string `json:"handler"`
// ErrorMessage: error message if the function is in "error" state.
ErrorMessage *string `json:"error_message"`
// BuildMessage: description of the current build step.
BuildMessage *string `json:"build_message"`
// Privacy: privacy setting of the function.
// Default value: unknown_privacy
Privacy FunctionPrivacy `json:"privacy"`
// Description: description of the function.
Description *string `json:"description"`
// DomainName: domain name associated with the function.
DomainName string `json:"domain_name"`
// SecretEnvironmentVariables: secret environment variables of the function.
SecretEnvironmentVariables []*SecretHashedValue `json:"secret_environment_variables"`
// Region: region in which the function is deployed.
Region scw.Region `json:"region"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption FunctionHTTPOption `json:"http_option"`
RuntimeMessage string `json:"runtime_message"`
// Sandbox: execution environment of the function.
// Default value: unknown_sandbox
Sandbox FunctionSandbox `json:"sandbox"`
// CreatedAt: creation date of the function.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of the function.
UpdatedAt *time.Time `json:"updated_at"`
// ReadyAt: last date when the function was successfully deployed and set to ready.
ReadyAt *time.Time `json:"ready_at"`
}
// Namespace: namespace.
type Namespace struct {
// ID: UUID of the namespace.
ID string `json:"id"`
// Name: name of the namespace.
Name string `json:"name"`
// EnvironmentVariables: environment variables of the namespace.
EnvironmentVariables map[string]string `json:"environment_variables"`
// OrganizationID: UUID of the Organization the namespace belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: UUID of the Project the namespace belongs to.
ProjectID string `json:"project_id"`
// Status: status of the namespace.
// Default value: unknown
Status NamespaceStatus `json:"status"`
// RegistryNamespaceID: UUID of the registry namespace.
RegistryNamespaceID string `json:"registry_namespace_id"`
// ErrorMessage: error message if the namespace is in "error" state.
ErrorMessage *string `json:"error_message"`
// RegistryEndpoint: registry endpoint of the namespace.
RegistryEndpoint string `json:"registry_endpoint"`
// Description: description of the namespace.
Description *string `json:"description"`
// SecretEnvironmentVariables: secret environment variables of the namespace.
SecretEnvironmentVariables []*SecretHashedValue `json:"secret_environment_variables"`
// Region: region in which the namespace is located.
Region scw.Region `json:"region"`
// Tags: [ALPHA] List of tags applied to the Serverless Function Namespace.
Tags []string `json:"tags"`
// CreatedAt: creation date of the namespace.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of the namespace.
UpdatedAt *time.Time `json:"updated_at"`
}
// Token: token.
type Token struct {
// ID: UUID of the token.
ID string `json:"id"`
// Token: string of the token.
Token string `json:"token"`
// FunctionID: UUID of the function the token is associated with.
// Precisely one of FunctionID, NamespaceID must be set.
FunctionID *string `json:"function_id,omitempty"`
// NamespaceID: UUID of the namespace the token is assoicated with.
// Precisely one of FunctionID, NamespaceID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// Deprecated: PublicKey: public key of the token.
PublicKey *string `json:"public_key,omitempty"`
// Status: status of the token.
// Default value: unknown
Status TokenStatus `json:"status"`
// Description: description of the token.
Description *string `json:"description"`
// ExpiresAt: date on which the token expires.
ExpiresAt *time.Time `json:"expires_at"`
}
// Trigger: trigger.
type Trigger struct {
// ID: ID of the trigger.
ID string `json:"id"`
// Name: name of the trigger.
Name string `json:"name"`
// Description: description of the trigger.
Description string `json:"description"`
// FunctionID: ID of the function to trigger.
FunctionID string `json:"function_id"`
// InputType: type of the input.
// Default value: unknown_input_type
InputType TriggerInputType `json:"input_type"`
// Status: status of the trigger.
// Default value: unknown_status
Status TriggerStatus `json:"status"`
// ErrorMessage: error message of the trigger.
ErrorMessage *string `json:"error_message"`
// ScwSqsConfig: configuration for a Scaleway Messaging and Queuing SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwSqsConfig *TriggerMnqSqsClientConfig `json:"scw_sqs_config,omitempty"`
// ScwNatsConfig: configuration for a Scaleway Messaging and Queuing NATS subject.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwNatsConfig *TriggerMnqNatsClientConfig `json:"scw_nats_config,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
SqsConfig *TriggerSqsClientConfig `json:"sqs_config,omitempty"`
}
// UpdateTriggerRequestSqsClientConfig: update trigger request sqs client config.
type UpdateTriggerRequestSqsClientConfig struct {
AccessKey *string `json:"access_key"`
SecretKey *string `json:"secret_key"`
}
// CreateCronRequest: create cron request.
type CreateCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to use the cron with.
FunctionID string `json:"function_id"`
// Schedule: schedule of the cron in UNIX cron format.
Schedule string `json:"schedule"`
// Args: arguments to use with the cron.
Args *scw.JSONObject `json:"args,omitempty"`
// Name: name of the cron.
Name *string `json:"name,omitempty"`
}
// CreateDomainRequest: create domain request.
type CreateDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Hostname: hostame to create.
Hostname string `json:"hostname"`
// FunctionID: UUID of the function to associate the domain with.
FunctionID string `json:"function_id"`
}
// CreateFunctionRequest: create function request.
type CreateFunctionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the function to create.
Name string `json:"name"`
// NamespaceID: UUID of the namespace the function will be created in.
NamespaceID string `json:"namespace_id"`
// EnvironmentVariables: environment variables of the function.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// MinScale: minumum number of instances to scale the function to.
MinScale *uint32 `json:"min_scale,omitempty"`
// MaxScale: maximum number of instances to scale the function to.
MaxScale *uint32 `json:"max_scale,omitempty"`
// Runtime: runtime to use with the function.
// Default value: unknown_runtime
Runtime FunctionRuntime `json:"runtime"`
// MemoryLimit: memory limit of the function in MB.
MemoryLimit *uint32 `json:"memory_limit,omitempty"`
// Timeout: request processing time limit for the function.
Timeout *scw.Duration `json:"timeout,omitempty"`
// Handler: handler to use with the function.
Handler *string `json:"handler,omitempty"`
// Privacy: privacy setting of the function.
// Default value: unknown_privacy
Privacy FunctionPrivacy `json:"privacy"`
// Description: description of the function.
Description *string `json:"description,omitempty"`
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption FunctionHTTPOption `json:"http_option"`
// Sandbox: execution environment of the function.
// Default value: unknown_sandbox
Sandbox FunctionSandbox `json:"sandbox"`
}
// CreateNamespaceRequest: create namespace request.
type CreateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Name string `json:"name"`
// EnvironmentVariables: environment variables of the namespace.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// ProjectID: UUID of the project in which the namespace will be created.
ProjectID string `json:"project_id"`
// Description: description of the namespace.
Description *string `json:"description,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the namespace.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// Tags: [ALPHA] Tags of the Serverless Function Namespace.
Tags []string `json:"tags"`
}
// CreateTokenRequest: create token request.
type CreateTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to associate the token with.
// Precisely one of FunctionID, NamespaceID must be set.
FunctionID *string `json:"function_id,omitempty"`
// NamespaceID: UUID of the namespace to associate the token with.
// Precisely one of FunctionID, NamespaceID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// Description: description of the token.
Description *string `json:"description,omitempty"`
// ExpiresAt: date on which the token expires.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateTriggerRequest: create trigger request.
type CreateTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the trigger.
Name string `json:"name"`
// FunctionID: ID of the function to trigger.
FunctionID string `json:"function_id"`
// Description: description of the trigger.
Description *string `json:"description,omitempty"`
// ScwSqsConfig: configuration for a Scaleway Messaging and Queuing SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwSqsConfig *CreateTriggerRequestMnqSqsClientConfig `json:"scw_sqs_config,omitempty"`
// ScwNatsConfig: configuration for a Scaleway Messaging and Queuing NATS subject.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
ScwNatsConfig *CreateTriggerRequestMnqNatsClientConfig `json:"scw_nats_config,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of ScwSqsConfig, ScwNatsConfig, SqsConfig must be set.
SqsConfig *CreateTriggerRequestSqsClientConfig `json:"sqs_config,omitempty"`
}
// DeleteCronRequest: delete cron request.
type DeleteCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to delete.
CronID string `json:"-"`
}
// DeleteDomainRequest: delete domain request.
type DeleteDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: UUID of the domain to delete.
DomainID string `json:"-"`
}
// DeleteFunctionRequest: delete function request.
type DeleteFunctionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to delete.
FunctionID string `json:"-"`
}
// DeleteNamespaceRequest: delete namespace request.
type DeleteNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace.
NamespaceID string `json:"-"`
}
// DeleteTokenRequest: delete token request.
type DeleteTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: UUID of the token to delete.
TokenID string `json:"-"`
}
// DeleteTriggerRequest: delete trigger request.
type DeleteTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to delete.
TriggerID string `json:"-"`
}
// DeployFunctionRequest: deploy function request.
type DeployFunctionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to deploy.
FunctionID string `json:"-"`
}
// DownloadURL: download url.
type DownloadURL struct {
URL string `json:"url"`
Headers map[string]*[]string `json:"headers"`
}
// GetCronRequest: get cron request.
type GetCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to get.
CronID string `json:"-"`
}
// GetDomainRequest: get domain request.
type GetDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: UUID of the domain to get.
DomainID string `json:"-"`
}
// GetFunctionDownloadURLRequest: get function download url request.
type GetFunctionDownloadURLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to get the the download URL for.
FunctionID string `json:"-"`
}
// GetFunctionRequest: get function request.
type GetFunctionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function.
FunctionID string `json:"-"`
}
// GetFunctionUploadURLRequest: get function upload url request.
type GetFunctionUploadURLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to get the upload URL for.
FunctionID string `json:"-"`
// ContentLength: size of the archive to upload in bytes.
ContentLength uint64 `json:"content_length"`
}
// GetNamespaceRequest: get namespace request.
type GetNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace.
NamespaceID string `json:"-"`
}
// GetTokenRequest: get token request.
type GetTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TokenID: UUID of the token to get.
TokenID string `json:"-"`
}
// GetTriggerRequest: get trigger request.
type GetTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to get.
TriggerID string `json:"-"`
}
// ListCronsRequest: list crons request.
type ListCronsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of crons per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the crons.
// Default value: created_at_asc
OrderBy ListCronsRequestOrderBy `json:"-"`
// FunctionID: UUID of the function.
FunctionID string `json:"-"`
}
// ListCronsResponse: list crons response.
type ListCronsResponse struct {
// Crons: array of crons.
Crons []*Cron `json:"crons"`
// TotalCount: total number of crons.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListCronsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListCronsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListCronsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Crons = append(r.Crons, results.Crons...)
r.TotalCount += uint32(len(results.Crons))
return uint32(len(results.Crons)), nil
}
// ListDomainsRequest: list domains request.
type ListDomainsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of domains per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the domains.
// Default value: created_at_asc
OrderBy ListDomainsRequestOrderBy `json:"-"`
// FunctionID: UUID of the function the domain is assoicated with.
FunctionID string `json:"-"`
}
// ListDomainsResponse: list domains response.
type ListDomainsResponse struct {
// Domains: array of domains.
Domains []*Domain `json:"domains"`
// TotalCount: total number of domains.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDomainsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Domains = append(r.Domains, results.Domains...)
r.TotalCount += uint32(len(results.Domains))
return uint32(len(results.Domains)), nil
}
// ListFunctionRuntimesRequest: list function runtimes request.
type ListFunctionRuntimesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// ListFunctionRuntimesResponse: list function runtimes response.
type ListFunctionRuntimesResponse struct {
// Runtimes: array of runtimes available.
Runtimes []*Runtime `json:"runtimes"`
// TotalCount: total number of runtimes.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFunctionRuntimesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFunctionRuntimesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListFunctionRuntimesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Runtimes = append(r.Runtimes, results.Runtimes...)
r.TotalCount += uint32(len(results.Runtimes))
return uint32(len(results.Runtimes)), nil
}
// ListFunctionsRequest: list functions request.
type ListFunctionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of functions per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the functions.
// Default value: created_at_asc
OrderBy ListFunctionsRequestOrderBy `json:"-"`
// NamespaceID: UUID of the namespace the function belongs to.
NamespaceID string `json:"-"`
// Name: name of the function.
Name *string `json:"-"`
// OrganizationID: UUID of the Organziation the function belongs to.
OrganizationID *string `json:"-"`
// ProjectID: UUID of the Project the function belongs to.
ProjectID *string `json:"-"`
}
// ListFunctionsResponse: list functions response.
type ListFunctionsResponse struct {
// Functions: array of functions.
Functions []*Function `json:"functions"`
// TotalCount: total number of functions.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFunctionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFunctionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListFunctionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Functions = append(r.Functions, results.Functions...)
r.TotalCount += uint32(len(results.Functions))
return uint32(len(results.Functions)), nil
}
// ListNamespacesRequest: list namespaces request.
type ListNamespacesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of namespaces per page.
PageSize *uint32 `json:"-"`
// OrderBy: order of the namespaces.
// Default value: created_at_asc
OrderBy ListNamespacesRequestOrderBy `json:"-"`
// Name: name of the namespace.
Name *string `json:"-"`
// OrganizationID: UUID of the Organization the namespace belongs to.
OrganizationID *string `json:"-"`
// ProjectID: UUID of the Project the namespace belongs to.
ProjectID *string `json:"-"`
}
// ListNamespacesResponse: list namespaces response.
type ListNamespacesResponse struct {
Namespaces []*Namespace `json:"namespaces"`
// TotalCount: total number of namespaces.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNamespacesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Namespaces = append(r.Namespaces, results.Namespaces...)
r.TotalCount += uint32(len(results.Namespaces))
return uint32(len(results.Namespaces)), nil
}
// ListTokensRequest: list tokens request.
type ListTokensRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: number of tokens per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order for the tokens.
// Default value: created_at_asc
OrderBy ListTokensRequestOrderBy `json:"-"`
// FunctionID: UUID of the function the token is assoicated with.
FunctionID *string `json:"-"`
// NamespaceID: UUID of the namespace the token is associated with.
NamespaceID *string `json:"-"`
}
// ListTokensResponse: list tokens response.
type ListTokensResponse struct {
Tokens []*Token `json:"tokens"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTokensResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTokensResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tokens = append(r.Tokens, results.Tokens...)
r.TotalCount += uint32(len(results.Tokens))
return uint32(len(results.Tokens)), nil
}
// ListTriggersRequest: list triggers request.
type ListTriggersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of triggers to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListTriggersRequestOrderBy `json:"-"`
// FunctionID: ID of the function the triggers belongs to.
// Precisely one of FunctionID, NamespaceID, ProjectID must be set.
FunctionID *string `json:"function_id,omitempty"`
// NamespaceID: ID of the namespace the triggers belongs to.
// Precisely one of FunctionID, NamespaceID, ProjectID must be set.
NamespaceID *string `json:"namespace_id,omitempty"`
// ProjectID: ID of the project the triggers belongs to.
// Precisely one of FunctionID, NamespaceID, ProjectID must be set.
ProjectID *string `json:"project_id,omitempty"`
}
// ListTriggersResponse: list triggers response.
type ListTriggersResponse struct {
// TotalCount: total count of existing triggers (matching any filters specified).
TotalCount uint32 `json:"total_count"`
// Triggers: triggers on this page.
Triggers []*Trigger `json:"triggers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTriggersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTriggersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTriggersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Triggers = append(r.Triggers, results.Triggers...)
r.TotalCount += uint32(len(results.Triggers))
return uint32(len(results.Triggers)), nil
}
// UpdateCronRequest: update cron request.
type UpdateCronRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CronID: UUID of the cron to update.
CronID string `json:"-"`
// FunctionID: UUID of the function to use the cron with.
FunctionID *string `json:"function_id,omitempty"`
// Schedule: schedule of the cron in UNIX cron format.
Schedule *string `json:"schedule,omitempty"`
// Args: arguments to use with the cron.
Args *scw.JSONObject `json:"args,omitempty"`
// Name: name of the cron.
Name *string `json:"name,omitempty"`
}
// UpdateFunctionRequest: update function request.
type UpdateFunctionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FunctionID: UUID of the function to update.
FunctionID string `json:"-"`
// EnvironmentVariables: environment variables of the function to update.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// MinScale: minumum number of instances to scale the function to.
MinScale *uint32 `json:"min_scale,omitempty"`
// MaxScale: maximum number of instances to scale the function to.
MaxScale *uint32 `json:"max_scale,omitempty"`
// Runtime: runtime to use with the function.
// Default value: unknown_runtime
Runtime FunctionRuntime `json:"runtime"`
// MemoryLimit: memory limit of the function in MB.
MemoryLimit *uint32 `json:"memory_limit,omitempty"`
// Timeout: processing time limit for the function.
Timeout *scw.Duration `json:"timeout,omitempty"`
// Redeploy: redeploy failed function.
Redeploy *bool `json:"redeploy,omitempty"`
// Handler: handler to use with the function.
Handler *string `json:"handler,omitempty"`
// Privacy: privacy setting of the function.
// Default value: unknown_privacy
Privacy FunctionPrivacy `json:"privacy"`
// Description: description of the function.
Description *string `json:"description,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the function.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// HTTPOption: possible values:
// - redirected: Responds to HTTP request with a 301 redirect to ask the clients to use HTTPS.
// - enabled: Serve both HTTP and HTTPS traffic.
// Default value: unknown_http_option
HTTPOption FunctionHTTPOption `json:"http_option"`
// Sandbox: execution environment of the function.
// Default value: unknown_sandbox
Sandbox FunctionSandbox `json:"sandbox"`
}
// UpdateNamespaceRequest: update namespace request.
type UpdateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespapce.
NamespaceID string `json:"-"`
// EnvironmentVariables: environment variables of the namespace.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// Description: description of the namespace.
Description *string `json:"description,omitempty"`
// SecretEnvironmentVariables: secret environment variables of the namespace.
SecretEnvironmentVariables []*Secret `json:"secret_environment_variables"`
// Tags: [ALPHA] Tags of the Serverless Function Namespace.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateTriggerRequest: update trigger request.
type UpdateTriggerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TriggerID: ID of the trigger to update.
TriggerID string `json:"-"`
// Name: name of the trigger.
Name *string `json:"name,omitempty"`
// Description: description of the trigger.
Description *string `json:"description,omitempty"`
// SqsConfig: configuration for an AWS SQS queue.
// Precisely one of SqsConfig must be set.
SqsConfig *UpdateTriggerRequestSqsClientConfig `json:"sqs_config,omitempty"`
}
// UploadURL: upload url.
type UploadURL struct {
// URL: upload URL to upload the function to.
URL string `json:"url"`
// Headers: HTTP headers.
Headers map[string]*[]string `json:"headers"`
}
// This API allows you to manage your Serverless Functions.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListNamespaces: List all existing namespaces in the specified region.
func (s *API) ListNamespaces(req *ListNamespacesRequest, opts ...scw.RequestOption) (*ListNamespacesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
Query: query,
}
var resp ListNamespacesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNamespace: Get the namespace associated with the specified ID.
func (s *API) GetNamespace(req *GetNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateNamespace: Create a new namespace in a specified Organization or Project.
func (s *API) CreateNamespace(req *CreateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("ns")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateNamespace: Update the namespace associated with the specified ID.
func (s *API) UpdateNamespace(req *UpdateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNamespace: Delete the namespace associated with the specified ID.
func (s *API) DeleteNamespace(req *DeleteNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFunctions: List all your functions.
func (s *API) ListFunctions(req *ListFunctionsRequest, opts ...scw.RequestOption) (*ListFunctionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions",
Query: query,
}
var resp ListFunctionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFunction: Get the function associated with the specified ID.
func (s *API) GetFunction(req *GetFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "",
}
var resp Function
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateFunction: Create a new function in the specified region for a specified Organization or Project.
func (s *API) CreateFunction(req *CreateFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("fn")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Function
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateFunction: Update the function associated with the specified ID.
func (s *API) UpdateFunction(req *UpdateFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Function
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteFunction: Delete the function associated with the specified ID.
func (s *API) DeleteFunction(req *DeleteFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "",
}
var resp Function
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeployFunction: Deploy a function associated with the specified ID.
func (s *API) DeployFunction(req *DeployFunctionRequest, opts ...scw.RequestOption) (*Function, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "/deploy",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Function
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFunctionRuntimes: List available function runtimes.
func (s *API) ListFunctionRuntimes(req *ListFunctionRuntimesRequest, opts ...scw.RequestOption) (*ListFunctionRuntimesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/runtimes",
}
var resp ListFunctionRuntimesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFunctionUploadURL: Get an upload URL of a function associated with the specified ID.
func (s *API) GetFunctionUploadURL(req *GetFunctionUploadURLRequest, opts ...scw.RequestOption) (*UploadURL, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "content_length", req.ContentLength)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "/upload-url",
Query: query,
}
var resp UploadURL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFunctionDownloadURL: Get a download URL for a function associated with the specified ID.
func (s *API) GetFunctionDownloadURL(req *GetFunctionDownloadURLRequest, opts ...scw.RequestOption) (*DownloadURL, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FunctionID) == "" {
return nil, errors.New("field FunctionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/functions/" + fmt.Sprint(req.FunctionID) + "/download-url",
}
var resp DownloadURL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListCrons: List all the cronjobs in a specified region.
func (s *API) ListCrons(req *ListCronsRequest, opts ...scw.RequestOption) (*ListCronsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "function_id", req.FunctionID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons",
Query: query,
}
var resp ListCronsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCron: Get the cron associated with the specified ID.
func (s *API) GetCron(req *GetCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateCron: Create a new cronjob for a function with the specified ID.
func (s *API) CreateCron(req *CreateCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCron: Update the cron associated with the specified ID.
func (s *API) UpdateCron(req *UpdateCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCron: Delete the cron associated with the specified ID.
func (s *API) DeleteCron(req *DeleteCronRequest, opts ...scw.RequestOption) (*Cron, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CronID) == "" {
return nil, errors.New("field CronID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/crons/" + fmt.Sprint(req.CronID) + "",
}
var resp Cron
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDomains: List all domain name bindings in a specified region.
func (s *API) ListDomains(req *ListDomainsRequest, opts ...scw.RequestOption) (*ListDomainsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "function_id", req.FunctionID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains",
Query: query,
}
var resp ListDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomain: Get a domain name binding for the function with the specified ID.
func (s *API) GetDomain(req *GetDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDomain: Create a domain name binding for the function with the specified ID.
func (s *API) CreateDomain(req *CreateDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDomain: Delete a domain name binding for the function with the specified ID.
func (s *API) DeleteDomain(req *DeleteDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateToken: Create a new revocable token.
func (s *API) CreateToken(req *CreateTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetToken: Get a token.
func (s *API) GetToken(req *GetTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return nil, errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTokens: List all tokens.
func (s *API) ListTokens(req *ListTokensRequest, opts ...scw.RequestOption) (*ListTokensResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "function_id", req.FunctionID)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens",
Query: query,
}
var resp ListTokensResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteToken: Delete a token.
func (s *API) DeleteToken(req *DeleteTokenRequest, opts ...scw.RequestOption) (*Token, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TokenID) == "" {
return nil, errors.New("field TokenID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tokens/" + fmt.Sprint(req.TokenID) + "",
}
var resp Token
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateTrigger: Create a new trigger for a specified function.
func (s *API) CreateTrigger(req *CreateTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetTrigger: Get a trigger with a specified ID.
func (s *API) GetTrigger(req *GetTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTriggers: List all triggers belonging to a specified Organization or Project.
func (s *API) ListTriggers(req *ListTriggersRequest, opts ...scw.RequestOption) (*ListTriggersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.FunctionID == nil && req.NamespaceID == nil && req.ProjectID == nil {
req.ProjectID = &defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "function_id", req.FunctionID)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers",
Query: query,
}
var resp ListTriggersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateTrigger: Update a trigger with a specified ID.
func (s *API) UpdateTrigger(req *UpdateTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTrigger: Delete a trigger with a specified ID.
func (s *API) DeleteTrigger(req *DeleteTriggerRequest, opts ...scw.RequestOption) (*Trigger, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TriggerID) == "" {
return nil, errors.New("field TriggerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/functions/v1beta1/regions/" + fmt.Sprint(req.Region) + "/triggers/" + fmt.Sprint(req.TriggerID) + "",
}
var resp Trigger
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/v1beta1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027742 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/function/v1beta1/sweepers/sweepers.go 0000664 0000000 0000000 00000006614 14747113137 0032135 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
functionSDK "github.com/scaleway/scaleway-sdk-go/api/function/v1beta1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepTriggers(scwClient *scw.Client, region scw.Region) error {
functionAPI := functionSDK.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the function triggers in (%s)", region)
listTriggers, err := functionAPI.ListTriggers(
&functionSDK.ListTriggersRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing trigger in (%s) in sweeper: %s", region, err)
}
for _, trigger := range listTriggers.Triggers {
_, err := functionAPI.DeleteTrigger(&functionSDK.DeleteTriggerRequest{
TriggerID: trigger.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting trigger in sweeper: %s", err)
}
}
return nil
}
func SweepNamespaces(scwClient *scw.Client, region scw.Region) error {
functionAPI := functionSDK.NewAPI(scwClient)
logger.Debugf("sweeper: destroying the function namespaces in (%s)", region)
listNamespaces, err := functionAPI.ListNamespaces(
&functionSDK.ListNamespacesRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing namespaces in (%s) in sweeper: %s", region, err)
}
for _, ns := range listNamespaces.Namespaces {
_, err := functionAPI.DeleteNamespace(&functionSDK.DeleteNamespaceRequest{
NamespaceID: ns.ID,
Region: region,
})
if err != nil {
logger.Debugf("sweeper: error (%s)", err)
return fmt.Errorf("error deleting namespace in sweeper: %s", err)
}
}
return nil
}
func SweepFunctions(scwClient *scw.Client, region scw.Region) error {
functionAPI := functionSDK.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the function in (%s)", region)
listFunctions, err := functionAPI.ListFunctions(
&functionSDK.ListFunctionsRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing functions in (%s) in sweeper: %s", region, err)
}
for _, f := range listFunctions.Functions {
_, err := functionAPI.DeleteFunction(&functionSDK.DeleteFunctionRequest{
FunctionID: f.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting functions in sweeper: %s", err)
}
}
return nil
}
func SweepCrons(scwClient *scw.Client, region scw.Region) error {
functionAPI := functionSDK.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the function cron in (%s)", region)
listCron, err := functionAPI.ListCrons(
&functionSDK.ListCronsRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing cron in (%s) in sweeper: %s", region, err)
}
for _, cron := range listCron.Crons {
_, err := functionAPI.DeleteCron(&functionSDK.DeleteCronRequest{
CronID: cron.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting cron in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&functionSDK.API{}).Regions() {
err := SweepTriggers(scwClient, region)
if err != nil {
return err
}
err = SweepNamespaces(scwClient, region)
if err != nil {
return err
}
err = SweepFunctions(scwClient, region)
if err != nil {
return err
}
err = SweepCrons(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iam/ 0000775 0000000 0000000 00000000000 14747113137 0023563 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iam/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025200 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iam/v1alpha1/iam_sdk.go 0000664 0000000 0000000 00000337021 14747113137 0027144 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package iam provides methods and message types of the iam v1alpha1 API.
package iam
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type BearerType string
const (
// Unknown bearer type.
BearerTypeUnknownBearerType = BearerType("unknown_bearer_type")
// User.
BearerTypeUser = BearerType("user")
// Application.
BearerTypeApplication = BearerType("application")
)
func (enum BearerType) String() string {
if enum == "" {
// return default value if empty
return "unknown_bearer_type"
}
return string(enum)
}
func (enum BearerType) Values() []BearerType {
return []BearerType{
"unknown_bearer_type",
"user",
"application",
}
}
func (enum BearerType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BearerType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BearerType(BearerType(tmp).String())
return nil
}
type GracePeriodType string
const (
// Unknown grace period type.
GracePeriodTypeUnknownGracePeriodType = GracePeriodType("unknown_grace_period_type")
// Password should be updated.
GracePeriodTypeUpdatePassword = GracePeriodType("update_password")
// MFA should be configured.
GracePeriodTypeSetMfa = GracePeriodType("set_mfa")
)
func (enum GracePeriodType) String() string {
if enum == "" {
// return default value if empty
return "unknown_grace_period_type"
}
return string(enum)
}
func (enum GracePeriodType) Values() []GracePeriodType {
return []GracePeriodType{
"unknown_grace_period_type",
"update_password",
"set_mfa",
}
}
func (enum GracePeriodType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GracePeriodType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GracePeriodType(GracePeriodType(tmp).String())
return nil
}
type ListAPIKeysRequestOrderBy string
const (
// Creation date ascending.
ListAPIKeysRequestOrderByCreatedAtAsc = ListAPIKeysRequestOrderBy("created_at_asc")
// Creation date descending.
ListAPIKeysRequestOrderByCreatedAtDesc = ListAPIKeysRequestOrderBy("created_at_desc")
// Update date ascending.
ListAPIKeysRequestOrderByUpdatedAtAsc = ListAPIKeysRequestOrderBy("updated_at_asc")
// Update date descending.
ListAPIKeysRequestOrderByUpdatedAtDesc = ListAPIKeysRequestOrderBy("updated_at_desc")
// Expiration date ascending.
ListAPIKeysRequestOrderByExpiresAtAsc = ListAPIKeysRequestOrderBy("expires_at_asc")
// Expiration date descending.
ListAPIKeysRequestOrderByExpiresAtDesc = ListAPIKeysRequestOrderBy("expires_at_desc")
// Access key ascending.
ListAPIKeysRequestOrderByAccessKeyAsc = ListAPIKeysRequestOrderBy("access_key_asc")
// Access key descending.
ListAPIKeysRequestOrderByAccessKeyDesc = ListAPIKeysRequestOrderBy("access_key_desc")
)
func (enum ListAPIKeysRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListAPIKeysRequestOrderBy) Values() []ListAPIKeysRequestOrderBy {
return []ListAPIKeysRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"expires_at_asc",
"expires_at_desc",
"access_key_asc",
"access_key_desc",
}
}
func (enum ListAPIKeysRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListAPIKeysRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListAPIKeysRequestOrderBy(ListAPIKeysRequestOrderBy(tmp).String())
return nil
}
type ListApplicationsRequestOrderBy string
const (
// Creation date ascending.
ListApplicationsRequestOrderByCreatedAtAsc = ListApplicationsRequestOrderBy("created_at_asc")
// Creation date descending.
ListApplicationsRequestOrderByCreatedAtDesc = ListApplicationsRequestOrderBy("created_at_desc")
// Update date ascending.
ListApplicationsRequestOrderByUpdatedAtAsc = ListApplicationsRequestOrderBy("updated_at_asc")
// Update date descending.
ListApplicationsRequestOrderByUpdatedAtDesc = ListApplicationsRequestOrderBy("updated_at_desc")
// Name ascending.
ListApplicationsRequestOrderByNameAsc = ListApplicationsRequestOrderBy("name_asc")
// Name descending.
ListApplicationsRequestOrderByNameDesc = ListApplicationsRequestOrderBy("name_desc")
)
func (enum ListApplicationsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListApplicationsRequestOrderBy) Values() []ListApplicationsRequestOrderBy {
return []ListApplicationsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListApplicationsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListApplicationsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListApplicationsRequestOrderBy(ListApplicationsRequestOrderBy(tmp).String())
return nil
}
type ListGroupsRequestOrderBy string
const (
// Creation date ascending.
ListGroupsRequestOrderByCreatedAtAsc = ListGroupsRequestOrderBy("created_at_asc")
// Creation date descending.
ListGroupsRequestOrderByCreatedAtDesc = ListGroupsRequestOrderBy("created_at_desc")
// Update date ascending.
ListGroupsRequestOrderByUpdatedAtAsc = ListGroupsRequestOrderBy("updated_at_asc")
// Update date descending.
ListGroupsRequestOrderByUpdatedAtDesc = ListGroupsRequestOrderBy("updated_at_desc")
// Name ascending.
ListGroupsRequestOrderByNameAsc = ListGroupsRequestOrderBy("name_asc")
// Name descending.
ListGroupsRequestOrderByNameDesc = ListGroupsRequestOrderBy("name_desc")
)
func (enum ListGroupsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListGroupsRequestOrderBy) Values() []ListGroupsRequestOrderBy {
return []ListGroupsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListGroupsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGroupsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGroupsRequestOrderBy(ListGroupsRequestOrderBy(tmp).String())
return nil
}
type ListJWTsRequestOrderBy string
const (
// Creation date ascending.
ListJWTsRequestOrderByCreatedAtAsc = ListJWTsRequestOrderBy("created_at_asc")
// Creation date descending.
ListJWTsRequestOrderByCreatedAtDesc = ListJWTsRequestOrderBy("created_at_desc")
// Update date ascending.
ListJWTsRequestOrderByUpdatedAtAsc = ListJWTsRequestOrderBy("updated_at_asc")
// Update date descending.
ListJWTsRequestOrderByUpdatedAtDesc = ListJWTsRequestOrderBy("updated_at_desc")
)
func (enum ListJWTsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListJWTsRequestOrderBy) Values() []ListJWTsRequestOrderBy {
return []ListJWTsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListJWTsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListJWTsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListJWTsRequestOrderBy(ListJWTsRequestOrderBy(tmp).String())
return nil
}
type ListLogsRequestOrderBy string
const (
// Creation date ascending.
ListLogsRequestOrderByCreatedAtAsc = ListLogsRequestOrderBy("created_at_asc")
// Creation date descending.
ListLogsRequestOrderByCreatedAtDesc = ListLogsRequestOrderBy("created_at_desc")
)
func (enum ListLogsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListLogsRequestOrderBy) Values() []ListLogsRequestOrderBy {
return []ListLogsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListLogsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListLogsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListLogsRequestOrderBy(ListLogsRequestOrderBy(tmp).String())
return nil
}
type ListPermissionSetsRequestOrderBy string
const (
// Name ascending.
ListPermissionSetsRequestOrderByNameAsc = ListPermissionSetsRequestOrderBy("name_asc")
// Name descending.
ListPermissionSetsRequestOrderByNameDesc = ListPermissionSetsRequestOrderBy("name_desc")
// Creation date ascending.
ListPermissionSetsRequestOrderByCreatedAtAsc = ListPermissionSetsRequestOrderBy("created_at_asc")
// Creation date descending.
ListPermissionSetsRequestOrderByCreatedAtDesc = ListPermissionSetsRequestOrderBy("created_at_desc")
)
func (enum ListPermissionSetsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListPermissionSetsRequestOrderBy) Values() []ListPermissionSetsRequestOrderBy {
return []ListPermissionSetsRequestOrderBy{
"name_asc",
"name_desc",
"created_at_asc",
"created_at_desc",
}
}
func (enum ListPermissionSetsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPermissionSetsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPermissionSetsRequestOrderBy(ListPermissionSetsRequestOrderBy(tmp).String())
return nil
}
type ListPoliciesRequestOrderBy string
const (
// Policy name ascending.
ListPoliciesRequestOrderByPolicyNameAsc = ListPoliciesRequestOrderBy("policy_name_asc")
// Policy name descending.
ListPoliciesRequestOrderByPolicyNameDesc = ListPoliciesRequestOrderBy("policy_name_desc")
// Creation date ascending.
ListPoliciesRequestOrderByCreatedAtAsc = ListPoliciesRequestOrderBy("created_at_asc")
// Creation date descending.
ListPoliciesRequestOrderByCreatedAtDesc = ListPoliciesRequestOrderBy("created_at_desc")
)
func (enum ListPoliciesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "policy_name_asc"
}
return string(enum)
}
func (enum ListPoliciesRequestOrderBy) Values() []ListPoliciesRequestOrderBy {
return []ListPoliciesRequestOrderBy{
"policy_name_asc",
"policy_name_desc",
"created_at_asc",
"created_at_desc",
}
}
func (enum ListPoliciesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPoliciesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPoliciesRequestOrderBy(ListPoliciesRequestOrderBy(tmp).String())
return nil
}
type ListQuotaRequestOrderBy string
const (
// Name ascending.
ListQuotaRequestOrderByNameAsc = ListQuotaRequestOrderBy("name_asc")
// Name descending.
ListQuotaRequestOrderByNameDesc = ListQuotaRequestOrderBy("name_desc")
)
func (enum ListQuotaRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListQuotaRequestOrderBy) Values() []ListQuotaRequestOrderBy {
return []ListQuotaRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListQuotaRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListQuotaRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListQuotaRequestOrderBy(ListQuotaRequestOrderBy(tmp).String())
return nil
}
type ListSSHKeysRequestOrderBy string
const (
// Creation date ascending.
ListSSHKeysRequestOrderByCreatedAtAsc = ListSSHKeysRequestOrderBy("created_at_asc")
// Creation date descending.
ListSSHKeysRequestOrderByCreatedAtDesc = ListSSHKeysRequestOrderBy("created_at_desc")
// Update date ascending.
ListSSHKeysRequestOrderByUpdatedAtAsc = ListSSHKeysRequestOrderBy("updated_at_asc")
// Update date descending.
ListSSHKeysRequestOrderByUpdatedAtDesc = ListSSHKeysRequestOrderBy("updated_at_desc")
// Name ascending.
ListSSHKeysRequestOrderByNameAsc = ListSSHKeysRequestOrderBy("name_asc")
// Name descending.
ListSSHKeysRequestOrderByNameDesc = ListSSHKeysRequestOrderBy("name_desc")
)
func (enum ListSSHKeysRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSSHKeysRequestOrderBy) Values() []ListSSHKeysRequestOrderBy {
return []ListSSHKeysRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListSSHKeysRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSSHKeysRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSSHKeysRequestOrderBy(ListSSHKeysRequestOrderBy(tmp).String())
return nil
}
type ListUsersRequestOrderBy string
const (
// Creation date ascending.
ListUsersRequestOrderByCreatedAtAsc = ListUsersRequestOrderBy("created_at_asc")
// Creation date descending.
ListUsersRequestOrderByCreatedAtDesc = ListUsersRequestOrderBy("created_at_desc")
// Update date ascending.
ListUsersRequestOrderByUpdatedAtAsc = ListUsersRequestOrderBy("updated_at_asc")
// Update date descending.
ListUsersRequestOrderByUpdatedAtDesc = ListUsersRequestOrderBy("updated_at_desc")
// Email ascending.
ListUsersRequestOrderByEmailAsc = ListUsersRequestOrderBy("email_asc")
// Email descending.
ListUsersRequestOrderByEmailDesc = ListUsersRequestOrderBy("email_desc")
// Last login ascending.
ListUsersRequestOrderByLastLoginAsc = ListUsersRequestOrderBy("last_login_asc")
// Last login descending.
ListUsersRequestOrderByLastLoginDesc = ListUsersRequestOrderBy("last_login_desc")
// Username ascending.
ListUsersRequestOrderByUsernameAsc = ListUsersRequestOrderBy("username_asc")
// Username descending.
ListUsersRequestOrderByUsernameDesc = ListUsersRequestOrderBy("username_desc")
)
func (enum ListUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListUsersRequestOrderBy) Values() []ListUsersRequestOrderBy {
return []ListUsersRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"email_asc",
"email_desc",
"last_login_asc",
"last_login_desc",
"username_asc",
"username_desc",
}
}
func (enum ListUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListUsersRequestOrderBy(ListUsersRequestOrderBy(tmp).String())
return nil
}
type LocalityType string
const (
LocalityTypeGlobal = LocalityType("global")
LocalityTypeRegion = LocalityType("region")
LocalityTypeZone = LocalityType("zone")
)
func (enum LocalityType) String() string {
if enum == "" {
// return default value if empty
return "global"
}
return string(enum)
}
func (enum LocalityType) Values() []LocalityType {
return []LocalityType{
"global",
"region",
"zone",
}
}
func (enum LocalityType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LocalityType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LocalityType(LocalityType(tmp).String())
return nil
}
type LogAction string
const (
// Unknown action.
LogActionUnknownAction = LogAction("unknown_action")
// Created.
LogActionCreated = LogAction("created")
// Updated.
LogActionUpdated = LogAction("updated")
// Deleted.
LogActionDeleted = LogAction("deleted")
)
func (enum LogAction) String() string {
if enum == "" {
// return default value if empty
return "unknown_action"
}
return string(enum)
}
func (enum LogAction) Values() []LogAction {
return []LogAction{
"unknown_action",
"created",
"updated",
"deleted",
}
}
func (enum LogAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LogAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LogAction(LogAction(tmp).String())
return nil
}
type LogResourceType string
const (
// Unknown resource type.
LogResourceTypeUnknownResourceType = LogResourceType("unknown_resource_type")
// API Key.
LogResourceTypeAPIKey = LogResourceType("api_key")
// User.
LogResourceTypeUser = LogResourceType("user")
// Application.
LogResourceTypeApplication = LogResourceType("application")
// Group.
LogResourceTypeGroup = LogResourceType("group")
// Policy.
LogResourceTypePolicy = LogResourceType("policy")
)
func (enum LogResourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_resource_type"
}
return string(enum)
}
func (enum LogResourceType) Values() []LogResourceType {
return []LogResourceType{
"unknown_resource_type",
"api_key",
"user",
"application",
"group",
"policy",
}
}
func (enum LogResourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LogResourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LogResourceType(LogResourceType(tmp).String())
return nil
}
type PermissionSetScopeType string
const (
// Unknown scope type.
PermissionSetScopeTypeUnknownScopeType = PermissionSetScopeType("unknown_scope_type")
// Projects.
PermissionSetScopeTypeProjects = PermissionSetScopeType("projects")
// Organization.
PermissionSetScopeTypeOrganization = PermissionSetScopeType("organization")
// Account root user.
PermissionSetScopeTypeAccountRootUser = PermissionSetScopeType("account_root_user")
)
func (enum PermissionSetScopeType) String() string {
if enum == "" {
// return default value if empty
return "unknown_scope_type"
}
return string(enum)
}
func (enum PermissionSetScopeType) Values() []PermissionSetScopeType {
return []PermissionSetScopeType{
"unknown_scope_type",
"projects",
"organization",
"account_root_user",
}
}
func (enum PermissionSetScopeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PermissionSetScopeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PermissionSetScopeType(PermissionSetScopeType(tmp).String())
return nil
}
type UserStatus string
const (
// Unknown status.
UserStatusUnknownStatus = UserStatus("unknown_status")
// Invitation pending.
UserStatusInvitationPending = UserStatus("invitation_pending")
// Activated.
UserStatusActivated = UserStatus("activated")
)
func (enum UserStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum UserStatus) Values() []UserStatus {
return []UserStatus{
"unknown_status",
"invitation_pending",
"activated",
}
}
func (enum UserStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *UserStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = UserStatus(UserStatus(tmp).String())
return nil
}
type UserType string
const (
// Unknown type.
UserTypeUnknownType = UserType("unknown_type")
// Guest.
UserTypeGuest = UserType("guest")
// Owner.
UserTypeOwner = UserType("owner")
UserTypeMember = UserType("member")
)
func (enum UserType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum UserType) Values() []UserType {
return []UserType{
"unknown_type",
"guest",
"owner",
"member",
}
}
func (enum UserType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *UserType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = UserType(UserType(tmp).String())
return nil
}
// QuotumLimit: quotum limit.
type QuotumLimit struct {
// Global: whether or not the limit is applied globally.
// Precisely one of Global, Region, Zone must be set.
Global *bool `json:"global,omitempty"`
// Region: the region on which the limit is applied.
// Precisely one of Global, Region, Zone must be set.
Region *scw.Region `json:"region,omitempty"`
// Zone: the zone on which the limit is applied.
// Precisely one of Global, Region, Zone must be set.
Zone *scw.Zone `json:"zone,omitempty"`
// Limit: maximum locality limit.
// Precisely one of Limit, Unlimited must be set.
Limit *uint64 `json:"limit,omitempty"`
// Unlimited: whether or not the quota per locality is unlimited.
// Precisely one of Limit, Unlimited must be set.
Unlimited *bool `json:"unlimited,omitempty"`
}
// JWT: jwt.
type JWT struct {
// Jti: jWT ID.
Jti string `json:"jti"`
// IssuerID: ID of the user who issued the JWT.
IssuerID string `json:"issuer_id"`
// AudienceID: ID of the user targeted by the JWT.
AudienceID string `json:"audience_id"`
// CreatedAt: creation date of the JWT.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of the JWT.
UpdatedAt *time.Time `json:"updated_at"`
// ExpiresAt: expiration date of the JWT.
ExpiresAt *time.Time `json:"expires_at"`
// IP: IP address used during the creation of the JWT.
IP net.IP `json:"ip"`
// UserAgent: user-agent used during the creation of the JWT.
UserAgent string `json:"user_agent"`
}
// RuleSpecs: rule specs.
type RuleSpecs struct {
// PermissionSetNames: names of permission sets bound to the rule.
PermissionSetNames *[]string `json:"permission_set_names"`
// Condition: condition expression to evaluate.
Condition string `json:"condition"`
// ProjectIDs: list of Project IDs the rule is scoped to.
// Precisely one of ProjectIDs, OrganizationID must be set.
ProjectIDs *[]string `json:"project_ids,omitempty"`
// OrganizationID: ID of Organization the rule is scoped to.
// Precisely one of ProjectIDs, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
}
// CreateUserRequestMember: create user request member.
type CreateUserRequestMember struct {
// Email: email of the user to create.
Email string `json:"email"`
// SendPasswordEmail: whether or not to send an email containing the member's password.
SendPasswordEmail bool `json:"send_password_email"`
// SendWelcomeEmail: whether or not to send a welcome email that includes onboarding information.
SendWelcomeEmail bool `json:"send_welcome_email"`
// Username: the member's username.
Username string `json:"username"`
// Password: the member's password.
Password string `json:"password"`
}
// APIKey: api key.
type APIKey struct {
// AccessKey: access key of the API key.
AccessKey string `json:"access_key"`
// SecretKey: secret key of the API Key.
SecretKey *string `json:"secret_key"`
// ApplicationID: ID of application that bears the API key.
// Precisely one of ApplicationID, UserID must be set.
ApplicationID *string `json:"application_id,omitempty"`
// UserID: ID of user that bears the API key.
// Precisely one of ApplicationID, UserID must be set.
UserID *string `json:"user_id,omitempty"`
// Description: description of API key.
Description string `json:"description"`
// CreatedAt: date and time of API key creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last API key update.
UpdatedAt *time.Time `json:"updated_at"`
// ExpiresAt: date and time of API key expiration.
ExpiresAt *time.Time `json:"expires_at"`
// DefaultProjectID: default Project ID specified for this API key.
DefaultProjectID string `json:"default_project_id"`
// Editable: defines whether or not the API key is editable.
Editable bool `json:"editable"`
// Deletable: defines whether or not the API key is deletable.
Deletable bool `json:"deletable"`
// Managed: defines whether or not the API key is managed.
Managed bool `json:"managed"`
// CreationIP: IP address of the device that created the API key.
CreationIP string `json:"creation_ip"`
}
// Application: application.
type Application struct {
// ID: ID of the application.
ID string `json:"id"`
// Name: name of the application.
Name string `json:"name"`
// Description: description of the application.
Description string `json:"description"`
// CreatedAt: date and time application was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last application update.
UpdatedAt *time.Time `json:"updated_at"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
// Editable: defines whether or not the application is editable.
Editable bool `json:"editable"`
// Deletable: defines whether or not the application is deletable.
Deletable bool `json:"deletable"`
// Managed: defines whether or not the application is managed.
Managed bool `json:"managed"`
// NbAPIKeys: number of API keys attributed to the application.
NbAPIKeys uint32 `json:"nb_api_keys"`
// Tags: tags associated with the user.
Tags []string `json:"tags"`
}
// GracePeriod: grace period.
type GracePeriod struct {
// Type: type of grace period.
// Default value: unknown_grace_period_type
Type GracePeriodType `json:"type"`
// CreatedAt: date and time the grace period was created.
CreatedAt *time.Time `json:"created_at"`
// ExpiresAt: date and time the grace period expires.
ExpiresAt *time.Time `json:"expires_at"`
}
// Group: group.
type Group struct {
// ID: ID of the group.
ID string `json:"id"`
// CreatedAt: date and time of group creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last group update.
UpdatedAt *time.Time `json:"updated_at"`
// OrganizationID: ID of Organization linked to the group.
OrganizationID string `json:"organization_id"`
// Name: name of the group.
Name string `json:"name"`
// Description: description of the group.
Description string `json:"description"`
// UserIDs: iDs of users attached to this group.
UserIDs []string `json:"user_ids"`
// ApplicationIDs: iDs of applications attached to this group.
ApplicationIDs []string `json:"application_ids"`
// Tags: tags associated to the group.
Tags []string `json:"tags"`
// Editable: defines whether or not the group is editable.
Editable bool `json:"editable"`
// Deletable: defines whether or not the group is deletable.
Deletable bool `json:"deletable"`
// Managed: defines whether or not the group is managed.
Managed bool `json:"managed"`
}
// Log: log.
type Log struct {
// ID: log ID.
ID string `json:"id"`
// CreatedAt: creation date of the log.
CreatedAt *time.Time `json:"created_at"`
// IP: IP address of the HTTP request linked to the log.
IP net.IP `json:"ip"`
// UserAgent: user-Agent of the HTTP request linked to the log.
UserAgent string `json:"user_agent"`
// Action: action linked to the log.
// Default value: unknown_action
Action LogAction `json:"action"`
// BearerID: ID of the principal at the origin of the log.
BearerID string `json:"bearer_id"`
// OrganizationID: ID of Organization linked to the log.
OrganizationID string `json:"organization_id"`
// ResourceType: type of the resource linked to the log.
// Default value: unknown_resource_type
ResourceType LogResourceType `json:"resource_type"`
// ResourceID: ID of the resource linked to the log.
ResourceID string `json:"resource_id"`
}
// PermissionSet: permission set.
type PermissionSet struct {
// ID: id of the permission set.
ID string `json:"id"`
// Name: name of the permission set.
Name string `json:"name"`
// ScopeType: scope of the permission set.
// Default value: unknown_scope_type
ScopeType PermissionSetScopeType `json:"scope_type"`
// Description: description of the permission set.
Description string `json:"description"`
// Categories: categories of the permission set.
Categories *[]string `json:"categories"`
}
// Policy: policy.
type Policy struct {
// ID: id of the policy.
ID string `json:"id"`
// Name: name of the policy.
Name string `json:"name"`
// Description: description of the policy.
Description string `json:"description"`
// OrganizationID: organization ID of the policy.
OrganizationID string `json:"organization_id"`
// CreatedAt: date and time of policy creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last policy update.
UpdatedAt *time.Time `json:"updated_at"`
// Editable: defines whether or not a policy is editable.
Editable bool `json:"editable"`
// Deletable: defines whether or not a policy is deletable.
Deletable bool `json:"deletable"`
// Managed: defines whether or not a policy is managed.
Managed bool `json:"managed"`
// NbRules: number of rules of the policy.
NbRules uint32 `json:"nb_rules"`
// NbScopes: number of policy scopes.
NbScopes uint32 `json:"nb_scopes"`
// NbPermissionSets: number of permission sets of the policy.
NbPermissionSets uint32 `json:"nb_permission_sets"`
// Tags: tags associated with the policy.
Tags []string `json:"tags"`
// UserID: ID of the user attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
UserID *string `json:"user_id,omitempty"`
// GroupID: ID of the group attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
GroupID *string `json:"group_id,omitempty"`
// ApplicationID: ID of the application attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
ApplicationID *string `json:"application_id,omitempty"`
// NoPrincipal: defines whether or not a policy is attributed to a principal.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
NoPrincipal *bool `json:"no_principal,omitempty"`
}
// Quotum: quotum.
type Quotum struct {
// Name: name of the quota.
Name string `json:"name"`
// Deprecated: Limit: maximum limit of the quota.
// Precisely one of Limit, Unlimited must be set.
Limit *uint64 `json:"limit,omitempty"`
// Deprecated: Unlimited: defines whether or not the quota is unlimited.
// Precisely one of Limit, Unlimited must be set.
Unlimited *bool `json:"unlimited,omitempty"`
// PrettyName: a human-readable name for the quota.
PrettyName string `json:"pretty_name"`
// Unit: the unit in which the quota is expressed.
Unit string `json:"unit"`
// Description: details about the quota.
Description string `json:"description"`
// LocalityType: whether this quotum is applied on at the zone level, region level, or globally.
// Default value: global
LocalityType LocalityType `json:"locality_type"`
// Limits: limits per locality.
Limits []*QuotumLimit `json:"limits"`
}
// Rule: rule.
type Rule struct {
// ID: id of rule.
ID string `json:"id"`
// PermissionSetNames: names of permission sets bound to the rule.
PermissionSetNames *[]string `json:"permission_set_names"`
// PermissionSetsScopeType: permission_set_names have the same scope_type.
// Default value: unknown_scope_type
PermissionSetsScopeType PermissionSetScopeType `json:"permission_sets_scope_type"`
// Condition: condition expression to evaluate.
Condition string `json:"condition"`
// ProjectIDs: list of Project IDs the rule is scoped to.
// Precisely one of ProjectIDs, OrganizationID, AccountRootUserID must be set.
ProjectIDs *[]string `json:"project_ids,omitempty"`
// OrganizationID: ID of Organization the rule is scoped to.
// Precisely one of ProjectIDs, OrganizationID, AccountRootUserID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// AccountRootUserID: ID of account root user the rule is scoped to.
// Precisely one of ProjectIDs, OrganizationID, AccountRootUserID must be set.
AccountRootUserID *string `json:"account_root_user_id,omitempty"`
}
// SSHKey: ssh key.
type SSHKey struct {
// ID: ID of SSH key.
ID string `json:"id"`
// Name: name of SSH key.
Name string `json:"name"`
// PublicKey: public key of SSH key.
PublicKey string `json:"public_key"`
// Fingerprint: fingerprint of the SSH key.
Fingerprint string `json:"fingerprint"`
// CreatedAt: creation date of SSH key.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update date of SSH key.
UpdatedAt *time.Time `json:"updated_at"`
// OrganizationID: ID of Organization linked to the SSH key.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of Project linked to the SSH key.
ProjectID string `json:"project_id"`
// Disabled: SSH key status.
Disabled bool `json:"disabled"`
}
// User: user.
type User struct {
// ID: ID of user.
ID string `json:"id"`
// Email: email of user.
Email string `json:"email"`
// Username: user identifier unique to the Organization.
Username string `json:"username"`
// CreatedAt: date user was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date of last user update.
UpdatedAt *time.Time `json:"updated_at"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
// Deletable: deletion status of user. Owners cannot be deleted.
Deletable bool `json:"deletable"`
// LastLoginAt: date of the last login.
LastLoginAt *time.Time `json:"last_login_at"`
// Type: type of user.
// Default value: unknown_type
Type UserType `json:"type"`
// Deprecated: TwoFactorEnabled: deprecated, use "mfa" instead.
TwoFactorEnabled *bool `json:"two_factor_enabled,omitempty"`
// Status: status of user invitation.
// Default value: unknown_status
Status UserStatus `json:"status"`
// Mfa: defines whether MFA is enabled.
Mfa bool `json:"mfa"`
// AccountRootUserID: ID of the account root user associated with the user.
AccountRootUserID string `json:"account_root_user_id"`
// Tags: tags associated with the user.
Tags []string `json:"tags"`
// Locked: defines whether the user is locked.
Locked bool `json:"locked"`
}
// AddGroupMemberRequest: add group member request.
type AddGroupMemberRequest struct {
// GroupID: ID of the group.
GroupID string `json:"-"`
// UserID: ID of the user to add.
// Precisely one of UserID, ApplicationID must be set.
UserID *string `json:"user_id,omitempty"`
// ApplicationID: ID of the application to add.
// Precisely one of UserID, ApplicationID must be set.
ApplicationID *string `json:"application_id,omitempty"`
}
// AddGroupMembersRequest: add group members request.
type AddGroupMembersRequest struct {
// GroupID: ID of the group.
GroupID string `json:"-"`
// UserIDs: iDs of the users to add.
UserIDs []string `json:"user_ids"`
// ApplicationIDs: iDs of the applications to add.
ApplicationIDs []string `json:"application_ids"`
}
// ClonePolicyRequest: clone policy request.
type ClonePolicyRequest struct {
PolicyID string `json:"-"`
}
// CreateAPIKeyRequest: create api key request.
type CreateAPIKeyRequest struct {
// ApplicationID: ID of the application.
// Precisely one of ApplicationID, UserID must be set.
ApplicationID *string `json:"application_id,omitempty"`
// UserID: ID of the user.
// Precisely one of ApplicationID, UserID must be set.
UserID *string `json:"user_id,omitempty"`
// ExpiresAt: expiration date of the API key.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
// DefaultProjectID: default Project ID to use with Object Storage.
DefaultProjectID *string `json:"default_project_id,omitempty"`
// Description: description of the API key (max length is 200 characters).
Description string `json:"description"`
}
// CreateApplicationRequest: create application request.
type CreateApplicationRequest struct {
// Name: name of the application to create (max length is 64 characters).
Name string `json:"name"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
// Description: description of the application (max length is 200 characters).
Description string `json:"description"`
// Tags: tags associated with the application (maximum of 10 tags).
Tags []string `json:"tags"`
}
// CreateGroupRequest: create group request.
type CreateGroupRequest struct {
// OrganizationID: ID of Organization linked to the group.
OrganizationID string `json:"organization_id"`
// Name: name of the group to create (max length is 64 chars). MUST be unique inside an Organization.
Name string `json:"name"`
// Description: description of the group to create (max length is 200 chars).
Description string `json:"description"`
// Tags: tags associated with the group (maximum of 10 tags).
Tags []string `json:"tags"`
}
// CreateJWTRequest: create jwt request.
type CreateJWTRequest struct {
// UserID: ID of the user the JWT will be created for.
UserID string `json:"user_id"`
// Referrer: referrer of the JWT.
Referrer string `json:"referrer"`
}
// CreatePolicyRequest: create policy request.
type CreatePolicyRequest struct {
// Name: name of the policy to create (max length is 64 characters).
Name string `json:"name"`
// Description: description of the policy to create (max length is 200 characters).
Description string `json:"description"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
// Rules: rules of the policy to create.
Rules []*RuleSpecs `json:"rules"`
// Tags: tags associated with the policy (maximum of 10 tags).
Tags []string `json:"tags"`
// UserID: ID of user attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
UserID *string `json:"user_id,omitempty"`
// GroupID: ID of group attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
GroupID *string `json:"group_id,omitempty"`
// ApplicationID: ID of application attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
ApplicationID *string `json:"application_id,omitempty"`
// NoPrincipal: defines whether or not a policy is attributed to a principal.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
NoPrincipal *bool `json:"no_principal,omitempty"`
}
// CreateSSHKeyRequest: create ssh key request.
type CreateSSHKeyRequest struct {
// Name: name of the SSH key. Max length is 1000.
Name string `json:"name"`
// PublicKey: SSH public key. Currently only the ssh-rsa, ssh-dss (DSA), ssh-ed25519 and ecdsa keys with NIST curves are supported. Max length is 65000.
PublicKey string `json:"public_key"`
// ProjectID: project the resource is attributed to.
ProjectID string `json:"project_id"`
}
// CreateUserMFAOTPRequest: create user mfaotp request.
type CreateUserMFAOTPRequest struct {
// UserID: user ID of the MFA OTP.
UserID string `json:"-"`
}
// CreateUserRequest: create user request.
type CreateUserRequest struct {
// OrganizationID: ID of the Organization.
OrganizationID string `json:"organization_id"`
// Email: email of the user.
// Precisely one of Email, Member must be set.
Email *string `json:"email,omitempty"`
// Tags: tags associated with the user.
Tags []string `json:"tags"`
// Member: details of IAM member. Private Beta feature.
// Precisely one of Email, Member must be set.
Member *CreateUserRequestMember `json:"member,omitempty"`
}
// DeleteAPIKeyRequest: delete api key request.
type DeleteAPIKeyRequest struct {
// AccessKey: access key to delete.
AccessKey string `json:"-"`
}
// DeleteApplicationRequest: delete application request.
type DeleteApplicationRequest struct {
// ApplicationID: ID of the application to delete.
ApplicationID string `json:"-"`
}
// DeleteGroupRequest: delete group request.
type DeleteGroupRequest struct {
// GroupID: ID of the group to delete.
GroupID string `json:"-"`
}
// DeleteJWTRequest: delete jwt request.
type DeleteJWTRequest struct {
// Jti: jWT ID of the JWT to delete.
Jti string `json:"-"`
}
// DeletePolicyRequest: delete policy request.
type DeletePolicyRequest struct {
// PolicyID: id of policy to delete.
PolicyID string `json:"-"`
}
// DeleteSSHKeyRequest: delete ssh key request.
type DeleteSSHKeyRequest struct {
SSHKeyID string `json:"-"`
}
// DeleteUserMFAOTPRequest: delete user mfaotp request.
type DeleteUserMFAOTPRequest struct {
// UserID: user ID of the MFA OTP.
UserID string `json:"-"`
}
// DeleteUserRequest: delete user request.
type DeleteUserRequest struct {
// UserID: ID of the user to delete.
UserID string `json:"-"`
}
// EncodedJWT: encoded jwt.
type EncodedJWT struct {
// Jwt: the renewed JWT.
Jwt *JWT `json:"jwt"`
// Token: the encoded token of the renewed JWT.
Token string `json:"token"`
// RenewToken: the encoded renew token. This token is necessary to renew the JWT.
RenewToken string `json:"renew_token"`
}
// GetAPIKeyRequest: get api key request.
type GetAPIKeyRequest struct {
// AccessKey: access key to search for.
AccessKey string `json:"-"`
}
// GetApplicationRequest: get application request.
type GetApplicationRequest struct {
// ApplicationID: ID of the application to find.
ApplicationID string `json:"-"`
}
// GetGroupRequest: get group request.
type GetGroupRequest struct {
// GroupID: ID of the group.
GroupID string `json:"-"`
}
// GetJWTRequest: get jwt request.
type GetJWTRequest struct {
// Jti: jWT ID of the JWT to get.
Jti string `json:"-"`
}
// GetLogRequest: get log request.
type GetLogRequest struct {
// LogID: ID of the log.
LogID string `json:"-"`
}
// GetOrganizationSecuritySettingsRequest: get organization security settings request.
type GetOrganizationSecuritySettingsRequest struct {
// OrganizationID: ID of the Organization.
OrganizationID string `json:"-"`
}
// GetPolicyRequest: get policy request.
type GetPolicyRequest struct {
// PolicyID: id of policy to search.
PolicyID string `json:"-"`
}
// GetQuotumRequest: get quotum request.
type GetQuotumRequest struct {
// QuotumName: name of the quota to get.
QuotumName string `json:"-"`
// OrganizationID: ID of the Organization.
OrganizationID string `json:"-"`
}
// GetSSHKeyRequest: get ssh key request.
type GetSSHKeyRequest struct {
// SSHKeyID: ID of the SSH key.
SSHKeyID string `json:"-"`
}
// GetUserRequest: get user request.
type GetUserRequest struct {
// UserID: ID of the user to find.
UserID string `json:"-"`
}
// ListAPIKeysRequest: list api keys request.
type ListAPIKeysRequest struct {
// OrderBy: criteria for sorting results.
// Default value: created_at_asc
OrderBy ListAPIKeysRequestOrderBy `json:"-"`
// Page: page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// OrganizationID: ID of Organization.
OrganizationID *string `json:"-"`
// Deprecated: ApplicationID: ID of application that bears the API key.
// Precisely one of ApplicationID, UserID must be set.
ApplicationID *string `json:"application_id,omitempty"`
// Deprecated: UserID: ID of user that bears the API key.
// Precisely one of ApplicationID, UserID must be set.
UserID *string `json:"user_id,omitempty"`
// Editable: defines whether to filter out editable API keys or not.
Editable *bool `json:"-"`
// Expired: defines whether to filter out expired API keys or not.
Expired *bool `json:"-"`
// Deprecated: AccessKey: filter by access key (deprecated in favor of `access_keys`).
AccessKey *string `json:"-"`
// Description: filter by description.
Description *string `json:"-"`
// BearerID: filter by bearer ID.
BearerID *string `json:"-"`
// BearerType: filter by type of bearer.
// Default value: unknown_bearer_type
BearerType BearerType `json:"-"`
// AccessKeys: filter by a list of access keys.
AccessKeys []string `json:"-"`
}
// ListAPIKeysResponse: list api keys response.
type ListAPIKeysResponse struct {
// APIKeys: list of API keys.
APIKeys []*APIKey `json:"api_keys"`
// TotalCount: total count of API Keys.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListAPIKeysResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListAPIKeysResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListAPIKeysResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.APIKeys = append(r.APIKeys, results.APIKeys...)
r.TotalCount += uint32(len(results.APIKeys))
return uint32(len(results.APIKeys)), nil
}
// ListApplicationsRequest: list applications request.
type ListApplicationsRequest struct {
// OrderBy: criteria for sorting results.
// Default value: created_at_asc
OrderBy ListApplicationsRequestOrderBy `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater than 1.
Page *int32 `json:"-"`
// Name: name of the application to filter.
Name *string `json:"-"`
// OrganizationID: ID of the Organization to filter.
OrganizationID string `json:"-"`
// Editable: defines whether to filter out editable applications or not.
Editable *bool `json:"-"`
// ApplicationIDs: filter by list of IDs.
ApplicationIDs []string `json:"-"`
// Tag: filter by tags containing a given string.
Tag *string `json:"-"`
}
// ListApplicationsResponse: list applications response.
type ListApplicationsResponse struct {
// Applications: list of applications.
Applications []*Application `json:"applications"`
// TotalCount: total count of applications.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListApplicationsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListApplicationsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListApplicationsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Applications = append(r.Applications, results.Applications...)
r.TotalCount += uint32(len(results.Applications))
return uint32(len(results.Applications)), nil
}
// ListGracePeriodsRequest: list grace periods request.
type ListGracePeriodsRequest struct {
// UserID: ID of the user to list grace periods for.
UserID *string `json:"-"`
}
// ListGracePeriodsResponse: list grace periods response.
type ListGracePeriodsResponse struct {
// GracePeriods: list of grace periods.
GracePeriods []*GracePeriod `json:"grace_periods"`
}
// ListGroupsRequest: list groups request.
type ListGroupsRequest struct {
// OrderBy: sort order of groups.
// Default value: created_at_asc
OrderBy ListGroupsRequestOrderBy `json:"-"`
// Page: requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: number of items per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID string `json:"-"`
// Name: name of group to find.
Name *string `json:"-"`
// ApplicationIDs: filter by a list of application IDs.
ApplicationIDs []string `json:"-"`
// UserIDs: filter by a list of user IDs.
UserIDs []string `json:"-"`
// GroupIDs: filter by a list of group IDs.
GroupIDs []string `json:"-"`
// Tag: filter by tags containing a given string.
Tag *string `json:"-"`
}
// ListGroupsResponse: list groups response.
type ListGroupsResponse struct {
// Groups: list of groups.
Groups []*Group `json:"groups"`
// TotalCount: total count of groups.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGroupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListGroupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Groups = append(r.Groups, results.Groups...)
r.TotalCount += uint32(len(results.Groups))
return uint32(len(results.Groups)), nil
}
// ListJWTsRequest: list jw ts request.
type ListJWTsRequest struct {
// OrderBy: criteria for sorting results.
// Default value: created_at_asc
OrderBy ListJWTsRequestOrderBy `json:"-"`
// AudienceID: ID of the user to search.
AudienceID *string `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater to 1.
Page *int32 `json:"-"`
// Expired: filter out expired JWTs or not.
Expired *bool `json:"-"`
}
// ListJWTsResponse: list jw ts response.
type ListJWTsResponse struct {
Jwts []*JWT `json:"jwts"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJWTsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJWTsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJWTsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Jwts = append(r.Jwts, results.Jwts...)
r.TotalCount += uint64(len(results.Jwts))
return uint64(len(results.Jwts)), nil
}
// ListLogsRequest: list logs request.
type ListLogsRequest struct {
// OrderBy: criteria for sorting results.
// Default value: created_at_asc
OrderBy ListLogsRequestOrderBy `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID string `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater to 1.
Page *int32 `json:"-"`
// CreatedAfter: defined whether or not to filter out logs created after this timestamp.
CreatedAfter *time.Time `json:"-"`
// CreatedBefore: defined whether or not to filter out logs created before this timestamp.
CreatedBefore *time.Time `json:"-"`
// Action: defined whether or not to filter out by a specific action.
// Default value: unknown_action
Action LogAction `json:"-"`
// ResourceType: defined whether or not to filter out by a specific type of resource.
// Default value: unknown_resource_type
ResourceType LogResourceType `json:"-"`
// Search: defined whether or not to filter out log by bearer ID or resource ID.
Search *string `json:"-"`
}
// ListLogsResponse: list logs response.
type ListLogsResponse struct {
// Logs: list of logs.
Logs []*Log `json:"logs"`
// TotalCount: total count of logs.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLogsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLogsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListLogsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Logs = append(r.Logs, results.Logs...)
r.TotalCount += uint64(len(results.Logs))
return uint64(len(results.Logs)), nil
}
// ListPermissionSetsRequest: list permission sets request.
type ListPermissionSetsRequest struct {
// OrderBy: criteria for sorting results.
// Default value: name_asc
OrderBy ListPermissionSetsRequestOrderBy `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater than 1.
Page *int32 `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID string `json:"-"`
}
// ListPermissionSetsResponse: list permission sets response.
type ListPermissionSetsResponse struct {
// PermissionSets: list of permission sets.
PermissionSets []*PermissionSet `json:"permission_sets"`
// TotalCount: total count of permission sets.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPermissionSetsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPermissionSetsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPermissionSetsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PermissionSets = append(r.PermissionSets, results.PermissionSets...)
r.TotalCount += uint32(len(results.PermissionSets))
return uint32(len(results.PermissionSets)), nil
}
// ListPoliciesRequest: list policies request.
type ListPoliciesRequest struct {
// OrderBy: criteria for sorting results.
// Default value: policy_name_asc
OrderBy ListPoliciesRequestOrderBy `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater than 1.
Page *int32 `json:"-"`
// OrganizationID: ID of the Organization to filter.
OrganizationID string `json:"-"`
// Editable: defines whether or not filter out editable policies.
Editable *bool `json:"-"`
// UserIDs: defines whether or not to filter by list of user IDs.
UserIDs []string `json:"-"`
// GroupIDs: defines whether or not to filter by list of group IDs.
GroupIDs []string `json:"-"`
// ApplicationIDs: filter by a list of application IDs.
ApplicationIDs []string `json:"-"`
// NoPrincipal: defines whether or not the policy is attributed to a principal.
NoPrincipal *bool `json:"-"`
// PolicyName: name of the policy to fetch.
PolicyName *string `json:"-"`
// Tag: filter by tags containing a given string.
Tag *string `json:"-"`
// PolicyIDs: filter by a list of IDs.
PolicyIDs []string `json:"-"`
}
// ListPoliciesResponse: list policies response.
type ListPoliciesResponse struct {
// Policies: list of policies.
Policies []*Policy `json:"policies"`
// TotalCount: total count of policies.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPoliciesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPoliciesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPoliciesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Policies = append(r.Policies, results.Policies...)
r.TotalCount += uint32(len(results.Policies))
return uint32(len(results.Policies)), nil
}
// ListQuotaRequest: list quota request.
type ListQuotaRequest struct {
// OrderBy: criteria for sorting results.
// Default value: name_asc
OrderBy ListQuotaRequestOrderBy `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater than 1.
Page *int32 `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID string `json:"-"`
// QuotumNames: list of quotum names to filter from.
QuotumNames []string `json:"-"`
}
// ListQuotaResponse: list quota response.
type ListQuotaResponse struct {
// Quota: list of quota.
Quota []*Quotum `json:"quota"`
// TotalCount: total count of quota.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListQuotaResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListQuotaResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListQuotaResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Quota = append(r.Quota, results.Quota...)
r.TotalCount += uint64(len(results.Quota))
return uint64(len(results.Quota)), nil
}
// ListRulesRequest: list rules request.
type ListRulesRequest struct {
// PolicyID: id of policy to search.
PolicyID string `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater than 1.
Page *int32 `json:"-"`
}
// ListRulesResponse: list rules response.
type ListRulesResponse struct {
// Rules: rules of the policy.
Rules []*Rule `json:"rules"`
// TotalCount: total count of rules.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint32(len(results.Rules))
return uint32(len(results.Rules)), nil
}
// ListSSHKeysRequest: list ssh keys request.
type ListSSHKeysRequest struct {
// OrderBy: sort order of the SSH keys.
// Default value: created_at_asc
OrderBy ListSSHKeysRequestOrderBy `json:"-"`
// Page: requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: number of items per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// Name: name of group to find.
Name *string `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// Disabled: defines whether to include disabled SSH keys or not.
Disabled *bool `json:"-"`
}
// ListSSHKeysResponse: list ssh keys response.
type ListSSHKeysResponse struct {
// SSHKeys: list of SSH keys.
SSHKeys []*SSHKey `json:"ssh_keys"`
// TotalCount: total count of SSH keys.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSSHKeysResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSSHKeysResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSSHKeysResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SSHKeys = append(r.SSHKeys, results.SSHKeys...)
r.TotalCount += uint32(len(results.SSHKeys))
return uint32(len(results.SSHKeys)), nil
}
// ListUsersRequest: list users request.
type ListUsersRequest struct {
// OrderBy: criteria for sorting results.
// Default value: created_at_asc
OrderBy ListUsersRequestOrderBy `json:"-"`
// PageSize: number of results per page. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// Page: page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// OrganizationID: ID of the Organization to filter.
OrganizationID *string `json:"-"`
// UserIDs: filter by list of IDs.
UserIDs []string `json:"-"`
// Mfa: filter by MFA status.
Mfa *bool `json:"-"`
// Tag: filter by tags containing a given string.
Tag *string `json:"-"`
}
// ListUsersResponse: list users response.
type ListUsersResponse struct {
// Users: list of users.
Users []*User `json:"users"`
// TotalCount: total count of users.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Users = append(r.Users, results.Users...)
r.TotalCount += uint32(len(results.Users))
return uint32(len(results.Users)), nil
}
// LockUserRequest: lock user request.
type LockUserRequest struct {
// UserID: ID of the user to lock.
UserID string `json:"-"`
}
// MFAOTP: mfaotp.
type MFAOTP struct {
Secret string `json:"secret"`
}
// OrganizationSecuritySettings: organization security settings.
type OrganizationSecuritySettings struct {
// EnforcePasswordRenewal: defines whether password renewal is enforced during first login.
EnforcePasswordRenewal bool `json:"enforce_password_renewal"`
// GracePeriodDuration: duration of the grace period to renew password or enable MFA.
GracePeriodDuration *scw.Duration `json:"grace_period_duration"`
// LoginAttemptsBeforeLocked: number of login attempts before the account is locked.
LoginAttemptsBeforeLocked uint32 `json:"login_attempts_before_locked"`
}
// RemoveGroupMemberRequest: remove group member request.
type RemoveGroupMemberRequest struct {
// GroupID: ID of the group.
GroupID string `json:"-"`
// UserID: ID of the user to remove.
// Precisely one of UserID, ApplicationID must be set.
UserID *string `json:"user_id,omitempty"`
// ApplicationID: ID of the application to remove.
// Precisely one of UserID, ApplicationID must be set.
ApplicationID *string `json:"application_id,omitempty"`
}
// SetGroupMembersRequest: set group members request.
type SetGroupMembersRequest struct {
GroupID string `json:"-"`
UserIDs []string `json:"user_ids"`
ApplicationIDs []string `json:"application_ids"`
}
// SetRulesRequest: set rules request.
type SetRulesRequest struct {
// PolicyID: id of policy to update.
PolicyID string `json:"policy_id"`
// Rules: rules of the policy to set.
Rules []*RuleSpecs `json:"rules"`
}
// SetRulesResponse: set rules response.
type SetRulesResponse struct {
// Rules: rules of the policy.
Rules []*Rule `json:"rules"`
}
// UnlockUserRequest: unlock user request.
type UnlockUserRequest struct {
// UserID: ID of the user to unlock.
UserID string `json:"-"`
}
// UpdateAPIKeyRequest: update api key request.
type UpdateAPIKeyRequest struct {
// AccessKey: access key to update.
AccessKey string `json:"-"`
// DefaultProjectID: new default Project ID to set.
DefaultProjectID *string `json:"default_project_id,omitempty"`
// Description: new description to update.
Description *string `json:"description,omitempty"`
}
// UpdateApplicationRequest: update application request.
type UpdateApplicationRequest struct {
// ApplicationID: ID of the application to update.
ApplicationID string `json:"-"`
// Name: new name for the application (max length is 64 chars).
Name *string `json:"name,omitempty"`
// Description: new description for the application (max length is 200 chars).
Description *string `json:"description,omitempty"`
// Tags: new tags for the application (maximum of 10 tags).
Tags *[]string `json:"tags,omitempty"`
}
// UpdateGroupRequest: update group request.
type UpdateGroupRequest struct {
// GroupID: ID of the group to update.
GroupID string `json:"-"`
// Name: new name for the group (max length is 64 chars). MUST be unique inside an Organization.
Name *string `json:"name,omitempty"`
// Description: new description for the group (max length is 200 chars).
Description *string `json:"description,omitempty"`
// Tags: new tags for the group (maximum of 10 tags).
Tags *[]string `json:"tags,omitempty"`
}
// UpdateOrganizationSecuritySettingsRequest: update organization security settings request.
type UpdateOrganizationSecuritySettingsRequest struct {
// OrganizationID: ID of the Organization.
OrganizationID string `json:"-"`
// EnforcePasswordRenewal: defines whether password renewal is enforced during first login.
EnforcePasswordRenewal *bool `json:"enforce_password_renewal,omitempty"`
// GracePeriodDuration: duration of the grace period to renew password or enable MFA.
GracePeriodDuration *scw.Duration `json:"grace_period_duration,omitempty"`
// LoginAttemptsBeforeLocked: number of login attempts before the account is locked.
LoginAttemptsBeforeLocked *uint32 `json:"login_attempts_before_locked,omitempty"`
}
// UpdatePolicyRequest: update policy request.
type UpdatePolicyRequest struct {
// PolicyID: id of policy to update.
PolicyID string `json:"-"`
// Name: new name for the policy (max length is 64 characters).
Name *string `json:"name,omitempty"`
// Description: new description of policy (max length is 200 characters).
Description *string `json:"description,omitempty"`
// Tags: new tags for the policy (maximum of 10 tags).
Tags *[]string `json:"tags,omitempty"`
// UserID: new ID of user attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
UserID *string `json:"user_id,omitempty"`
// GroupID: new ID of group attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
GroupID *string `json:"group_id,omitempty"`
// ApplicationID: new ID of application attributed to the policy.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
ApplicationID *string `json:"application_id,omitempty"`
// NoPrincipal: defines whether or not the policy is attributed to a principal.
// Precisely one of UserID, GroupID, ApplicationID, NoPrincipal must be set.
NoPrincipal *bool `json:"no_principal,omitempty"`
}
// UpdateSSHKeyRequest: update ssh key request.
type UpdateSSHKeyRequest struct {
SSHKeyID string `json:"-"`
// Name: name of the SSH key. Max length is 1000.
Name *string `json:"name,omitempty"`
// Disabled: enable or disable the SSH key.
Disabled *bool `json:"disabled,omitempty"`
}
// UpdateUserPasswordRequest: update user password request.
type UpdateUserPasswordRequest struct {
// UserID: ID of the user to update.
UserID string `json:"-"`
// Password: the new password.
Password string `json:"password"`
}
// UpdateUserRequest: update user request.
type UpdateUserRequest struct {
// UserID: ID of the user to update.
UserID string `json:"-"`
// Tags: new tags for the user (maximum of 10 tags).
Tags *[]string `json:"tags,omitempty"`
// Email: iAM member email.
Email *string `json:"email,omitempty"`
}
// UpdateUserUsernameRequest: update user username request.
type UpdateUserUsernameRequest struct {
// UserID: ID of the user to update.
UserID string `json:"-"`
// Username: the new username.
Username string `json:"username"`
}
// ValidateUserMFAOTPRequest: validate user mfaotp request.
type ValidateUserMFAOTPRequest struct {
// UserID: user ID of the MFA OTP.
UserID string `json:"-"`
// OneTimePassword: a password generated using the OTP.
OneTimePassword string `json:"one_time_password"`
}
// ValidateUserMFAOTPResponse: validate user mfaotp response.
type ValidateUserMFAOTPResponse struct {
// RecoveryCodes: list of recovery codes usable for this OTP method.
RecoveryCodes []string `json:"recovery_codes"`
}
// This API allows you to manage Identity and Access Management (IAM) across your Scaleway Organizations, Projects and resources.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// ListSSHKeys: List SSH keys. By default, the SSH keys listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You can define additional parameters for your query such as `organization_id`, `name`, `project_id` and `disabled`.
func (s *API) ListSSHKeys(req *ListSSHKeysRequest, opts ...scw.RequestOption) (*ListSSHKeysResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "disabled", req.Disabled)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/ssh-keys",
Query: query,
}
var resp ListSSHKeysResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSSHKey: Add a new SSH key to a Scaleway Project. You must specify the `name`, `public_key` and `project_id`.
func (s *API) CreateSSHKey(req *CreateSSHKeyRequest, opts ...scw.RequestOption) (*SSHKey, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("key")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/ssh-keys",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SSHKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSSHKey: Retrieve information about a given SSH key, specified by the `ssh_key_id` parameter. The SSH key's full details, including `id`, `name`, `public_key`, and `project_id` are returned in the response.
func (s *API) GetSSHKey(req *GetSSHKeyRequest, opts ...scw.RequestOption) (*SSHKey, error) {
var err error
if fmt.Sprint(req.SSHKeyID) == "" {
return nil, errors.New("field SSHKeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/ssh-keys/" + fmt.Sprint(req.SSHKeyID) + "",
}
var resp SSHKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSSHKey: Update the parameters of an SSH key, including `name` and `disable`.
func (s *API) UpdateSSHKey(req *UpdateSSHKeyRequest, opts ...scw.RequestOption) (*SSHKey, error) {
var err error
if fmt.Sprint(req.SSHKeyID) == "" {
return nil, errors.New("field SSHKeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/ssh-keys/" + fmt.Sprint(req.SSHKeyID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SSHKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSSHKey: Delete a given SSH key, specified by the `ssh_key_id`. Deleting an SSH is permanent, and cannot be undone. Note that you might need to update any configurations that used the SSH key.
func (s *API) DeleteSSHKey(req *DeleteSSHKeyRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.SSHKeyID) == "" {
return errors.New("field SSHKeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/ssh-keys/" + fmt.Sprint(req.SSHKeyID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListUsers: List the users of an Organization. By default, the users listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You must define the `organization_id` in the query path of your request. You can also define additional parameters for your query such as `user_ids`.
func (s *API) ListUsers(req *ListUsersRequest, opts ...scw.RequestOption) (*ListUsersResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "user_ids", req.UserIDs)
parameter.AddToQuery(query, "mfa", req.Mfa)
parameter.AddToQuery(query, "tag", req.Tag)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/users",
Query: query,
}
var resp ListUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetUser: Retrieve information about a user, specified by the `user_id` parameter. The user's full details, including `id`, `email`, `organization_id`, `status` and `mfa` are returned in the response.
func (s *API) GetUser(req *GetUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "",
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUser: Update the parameters of a user, including `tags`.
func (s *API) UpdateUser(req *UpdateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteUser: Remove a user from an Organization in which they are a guest. You must define the `user_id` in your request. Note that removing a user from an Organization automatically deletes their API keys, and any policies directly attached to them become orphaned.
func (s *API) DeleteUser(req *DeleteUserRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.UserID) == "" {
return errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateUser: Create a new user. You must define the `organization_id` and the `email` in your request.
func (s *API) CreateUser(req *CreateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUserUsername: Update an user's username. Private Beta feature.
func (s *API) UpdateUserUsername(req *UpdateUserUsernameRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/update-username",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUserPassword: Update an user's password. Private Beta feature.
func (s *API) UpdateUserPassword(req *UpdateUserPasswordRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/update-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateUserMFAOTP: Create a MFA OTP. Private Beta feature.
func (s *API) CreateUserMFAOTP(req *CreateUserMFAOTPRequest, opts ...scw.RequestOption) (*MFAOTP, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/mfa-otp",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp MFAOTP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ValidateUserMFAOTP: Validate a MFA OTP. Private Beta feature.
func (s *API) ValidateUserMFAOTP(req *ValidateUserMFAOTPRequest, opts ...scw.RequestOption) (*ValidateUserMFAOTPResponse, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/validate-mfa-otp",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ValidateUserMFAOTPResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteUserMFAOTP: Delete a MFA OTP. Private Beta feature.
func (s *API) DeleteUserMFAOTP(req *DeleteUserMFAOTPRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.UserID) == "" {
return errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/mfa-otp",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// LockUser: Lock a member. A locked member cannot log in or use API keys until the locked status is removed. Private Beta feature.
func (s *API) LockUser(req *LockUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/lock",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnlockUser: Unlock a member. Private Beta feature.
func (s *API) UnlockUser(req *UnlockUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if fmt.Sprint(req.UserID) == "" {
return nil, errors.New("field UserID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/users/" + fmt.Sprint(req.UserID) + "/unlock",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListGracePeriods: List the grace periods of a member. Private Beta feature.
func (s *API) ListGracePeriods(req *ListGracePeriodsRequest, opts ...scw.RequestOption) (*ListGracePeriodsResponse, error) {
var err error
query := url.Values{}
parameter.AddToQuery(query, "user_id", req.UserID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/grace-periods",
Query: query,
}
var resp ListGracePeriodsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListApplications: List the applications of an Organization. By default, the applications listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You must define the `organization_id` in the query path of your request. You can also define additional parameters for your query such as `application_ids`.
func (s *API) ListApplications(req *ListApplicationsRequest, opts ...scw.RequestOption) (*ListApplicationsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "editable", req.Editable)
parameter.AddToQuery(query, "application_ids", req.ApplicationIDs)
parameter.AddToQuery(query, "tag", req.Tag)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/applications",
Query: query,
}
var resp ListApplicationsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateApplication: Create a new application. You must define the `name` parameter in the request.
func (s *API) CreateApplication(req *CreateApplicationRequest, opts ...scw.RequestOption) (*Application, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("app")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/applications",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Application
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetApplication: Retrieve information about an application, specified by the `application_id` parameter. The application's full details, including `id`, `email`, `organization_id`, `status` and `two_factor_enabled` are returned in the response.
func (s *API) GetApplication(req *GetApplicationRequest, opts ...scw.RequestOption) (*Application, error) {
var err error
if fmt.Sprint(req.ApplicationID) == "" {
return nil, errors.New("field ApplicationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/applications/" + fmt.Sprint(req.ApplicationID) + "",
}
var resp Application
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateApplication: Update the parameters of an application, including `name` and `description`.
func (s *API) UpdateApplication(req *UpdateApplicationRequest, opts ...scw.RequestOption) (*Application, error) {
var err error
if fmt.Sprint(req.ApplicationID) == "" {
return nil, errors.New("field ApplicationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/applications/" + fmt.Sprint(req.ApplicationID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Application
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteApplication: Delete an application. Note that this action is irreversible and will automatically delete the application's API keys. Policies attached to users and applications via this group will no longer apply.
func (s *API) DeleteApplication(req *DeleteApplicationRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.ApplicationID) == "" {
return errors.New("field ApplicationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/applications/" + fmt.Sprint(req.ApplicationID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListGroups: List groups. By default, the groups listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You can define additional parameters to filter your query. Use `user_ids` or `application_ids` to list all groups certain users or applications belong to.
func (s *API) ListGroups(req *ListGroupsRequest, opts ...scw.RequestOption) (*ListGroupsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "application_ids", req.ApplicationIDs)
parameter.AddToQuery(query, "user_ids", req.UserIDs)
parameter.AddToQuery(query, "group_ids", req.GroupIDs)
parameter.AddToQuery(query, "tag", req.Tag)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/groups",
Query: query,
}
var resp ListGroupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateGroup: Create a new group. You must define the `name` and `organization_id` parameters in the request.
func (s *API) CreateGroup(req *CreateGroupRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("grp")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/groups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGroup: Retrive information about a given group, specified by the `group_id` parameter. The group's full details, including `user_ids` and `application_ids` are returned in the response.
func (s *API) GetGroup(req *GetGroupRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "",
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateGroup: Update the parameters of group, including `name` and `description`.
func (s *API) UpdateGroup(req *UpdateGroupRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetGroupMembers: Overwrite users and applications configuration in a group. Any information that you add using this command will overwrite the previous configuration.
func (s *API) SetGroupMembers(req *SetGroupMembersRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "/members",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddGroupMember: Add a user or an application to a group. You can specify a `user_id` and and `application_id` in the body of your request. Note that you can only add one of each per request.
func (s *API) AddGroupMember(req *AddGroupMemberRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "/add-member",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddGroupMembers: Add multiple users and applications to a group in a single call. You can specify an array of `user_id`s and `application_id`s. Note that any existing users and applications in the group will remain. To add new users/applications and delete pre-existing ones, use the [Overwrite users and applications of a group](#path-groups-overwrite-users-and-applications-of-a-group) method.
func (s *API) AddGroupMembers(req *AddGroupMembersRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "/add-members",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RemoveGroupMember: Remove a user or an application from a group. You can specify a `user_id` and and `application_id` in the body of your request. Note that you can only remove one of each per request. Removing a user from a group means that any permissions given to them via the group (i.e. from an attached policy) will no longer apply. Be sure you want to remove these permissions from the user before proceeding.
func (s *API) RemoveGroupMember(req *RemoveGroupMemberRequest, opts ...scw.RequestOption) (*Group, error) {
var err error
if fmt.Sprint(req.GroupID) == "" {
return nil, errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "/remove-member",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Group
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGroup: Delete a group. Note that this action is irreversible and could delete permissions for group members. Policies attached to users and applications via this group will no longer apply.
func (s *API) DeleteGroup(req *DeleteGroupRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.GroupID) == "" {
return errors.New("field GroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/groups/" + fmt.Sprint(req.GroupID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPolicies: List the policies of an Organization. By default, the policies listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You must define the `organization_id` in the query path of your request. You can also define additional parameters to filter your query, such as `user_ids`, `groups_ids`, `application_ids`, and `policy_name`.
func (s *API) ListPolicies(req *ListPoliciesRequest, opts ...scw.RequestOption) (*ListPoliciesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "editable", req.Editable)
parameter.AddToQuery(query, "user_ids", req.UserIDs)
parameter.AddToQuery(query, "group_ids", req.GroupIDs)
parameter.AddToQuery(query, "application_ids", req.ApplicationIDs)
parameter.AddToQuery(query, "no_principal", req.NoPrincipal)
parameter.AddToQuery(query, "policy_name", req.PolicyName)
parameter.AddToQuery(query, "tag", req.Tag)
parameter.AddToQuery(query, "policy_ids", req.PolicyIDs)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/policies",
Query: query,
}
var resp ListPoliciesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePolicy: Create a new application. You must define the `name` parameter in the request. You can specify parameters such as `user_id`, `groups_id`, `application_id`, `no_principal`, `rules` and its child attributes.
func (s *API) CreatePolicy(req *CreatePolicyRequest, opts ...scw.RequestOption) (*Policy, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("pol")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/policies",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Policy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPolicy: Retrieve information about a policy, speficified by the `policy_id` parameter. The policy's full details, including `id`, `name`, `organization_id`, `nb_rules` and `nb_scopes`, `nb_permission_sets` are returned in the response.
func (s *API) GetPolicy(req *GetPolicyRequest, opts ...scw.RequestOption) (*Policy, error) {
var err error
if fmt.Sprint(req.PolicyID) == "" {
return nil, errors.New("field PolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/policies/" + fmt.Sprint(req.PolicyID) + "",
}
var resp Policy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePolicy: Update the parameters of a policy, including `name`, `description`, `user_id`, `group_id`, `application_id` and `no_principal`.
func (s *API) UpdatePolicy(req *UpdatePolicyRequest, opts ...scw.RequestOption) (*Policy, error) {
var err error
if fmt.Sprint(req.PolicyID) == "" {
return nil, errors.New("field PolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/policies/" + fmt.Sprint(req.PolicyID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Policy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePolicy: Delete a policy. You must define specify the `policy_id` parameter in your request. Note that when deleting a policy, all permissions it gives to its principal (user, group or application) will be revoked.
func (s *API) DeletePolicy(req *DeletePolicyRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.PolicyID) == "" {
return errors.New("field PolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/policies/" + fmt.Sprint(req.PolicyID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ClonePolicy: Clone a policy. You must define specify the `policy_id` parameter in your request.
func (s *API) ClonePolicy(req *ClonePolicyRequest, opts ...scw.RequestOption) (*Policy, error) {
var err error
if fmt.Sprint(req.PolicyID) == "" {
return nil, errors.New("field PolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/policies/" + fmt.Sprint(req.PolicyID) + "/clone",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Policy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetRules: Overwrite the rules of a given policy. Any information that you add using this command will overwrite the previous configuration. If you include some of the rules you already had in your previous configuration in your new one, but you change their order, the new order of display will apply. While policy rules are ordered, they have no impact on the access logic of IAM because rules are allow-only.
func (s *API) SetRules(req *SetRulesRequest, opts ...scw.RequestOption) (*SetRulesResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/iam/v1alpha1/rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRules: List the rules of a given policy. By default, the rules listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You must define the `policy_id` in the query path of your request.
func (s *API) ListRules(req *ListRulesRequest, opts ...scw.RequestOption) (*ListRulesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "policy_id", req.PolicyID)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/rules",
Query: query,
}
var resp ListRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPermissionSets: List permission sets available for given Organization. You must define the `organization_id` in the query path of your request.
func (s *API) ListPermissionSets(req *ListPermissionSetsRequest, opts ...scw.RequestOption) (*ListPermissionSetsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/permission-sets",
Query: query,
}
var resp ListPermissionSetsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListAPIKeys: List API keys. By default, the API keys listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You can define additional parameters for your query such as `editable`, `expired`, `access_key` and `bearer_id`.
func (s *API) ListAPIKeys(req *ListAPIKeysRequest, opts ...scw.RequestOption) (*ListAPIKeysResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "editable", req.Editable)
parameter.AddToQuery(query, "expired", req.Expired)
parameter.AddToQuery(query, "access_key", req.AccessKey)
parameter.AddToQuery(query, "description", req.Description)
parameter.AddToQuery(query, "bearer_id", req.BearerID)
parameter.AddToQuery(query, "bearer_type", req.BearerType)
parameter.AddToQuery(query, "access_keys", req.AccessKeys)
parameter.AddToQuery(query, "application_id", req.ApplicationID)
parameter.AddToQuery(query, "user_id", req.UserID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/api-keys",
Query: query,
}
var resp ListAPIKeysResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateAPIKey: Create an API key. You must specify the `application_id` or the `user_id` and the description. You can also specify the `default_project_id`, which is the Project ID of your preferred Project, to use with Object Storage. The `access_key` and `secret_key` values are returned in the response. Note that the secret key is only shown once. Make sure that you copy and store both keys somewhere safe.
func (s *API) CreateAPIKey(req *CreateAPIKeyRequest, opts ...scw.RequestOption) (*APIKey, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/api-keys",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp APIKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetAPIKey: Retrive information about an API key, specified by the `access_key` parameter. The API key's details, including either the `user_id` or `application_id` of its bearer are returned in the response. Note that the string value for the `secret_key` is nullable, and therefore is not displayed in the response. The `secret_key` value is only displayed upon API key creation.
func (s *API) GetAPIKey(req *GetAPIKeyRequest, opts ...scw.RequestOption) (*APIKey, error) {
var err error
if fmt.Sprint(req.AccessKey) == "" {
return nil, errors.New("field AccessKey cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/api-keys/" + fmt.Sprint(req.AccessKey) + "",
}
var resp APIKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateAPIKey: Update the parameters of an API key, including `default_project_id` and `description`.
func (s *API) UpdateAPIKey(req *UpdateAPIKeyRequest, opts ...scw.RequestOption) (*APIKey, error) {
var err error
if fmt.Sprint(req.AccessKey) == "" {
return nil, errors.New("field AccessKey cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/api-keys/" + fmt.Sprint(req.AccessKey) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp APIKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteAPIKey: Delete an API key. Note that this action is irreversible and cannot be undone. Make sure you update any configurations using the API keys you delete.
func (s *API) DeleteAPIKey(req *DeleteAPIKeyRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.AccessKey) == "" {
return errors.New("field AccessKey cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/api-keys/" + fmt.Sprint(req.AccessKey) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListQuota: List all product and features quota for an Organization, with their associated limits. By default, the quota listed are ordered by creation date in ascending order. This can be modified via the `order_by` field. You must define the `organization_id` in the query path of your request.
func (s *API) ListQuota(req *ListQuotaRequest, opts ...scw.RequestOption) (*ListQuotaResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "quotum_names", req.QuotumNames)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/quota",
Query: query,
}
var resp ListQuotaResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetQuotum: Retrieve information about a resource quota, specified by the `quotum_name` parameter. The quota's `limit`, or whether it is unlimited, is returned in the response.
func (s *API) GetQuotum(req *GetQuotumRequest, opts ...scw.RequestOption) (*Quotum, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
if fmt.Sprint(req.QuotumName) == "" {
return nil, errors.New("field QuotumName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/quota/" + fmt.Sprint(req.QuotumName) + "",
Query: query,
}
var resp Quotum
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJWTs: List JWTs.
func (s *API) ListJWTs(req *ListJWTsRequest, opts ...scw.RequestOption) (*ListJWTsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "audience_id", req.AudienceID)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "expired", req.Expired)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/jwts",
Query: query,
}
var resp ListJWTsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateJWT: Create a JWT.
func (s *API) CreateJWT(req *CreateJWTRequest, opts ...scw.RequestOption) (*EncodedJWT, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iam/v1alpha1/jwts",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp EncodedJWT
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetJWT: Get a JWT.
func (s *API) GetJWT(req *GetJWTRequest, opts ...scw.RequestOption) (*JWT, error) {
var err error
if fmt.Sprint(req.Jti) == "" {
return nil, errors.New("field Jti cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/jwts/" + fmt.Sprint(req.Jti) + "",
}
var resp JWT
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteJWT: Delete a JWT.
func (s *API) DeleteJWT(req *DeleteJWTRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.Jti) == "" {
return errors.New("field Jti cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iam/v1alpha1/jwts/" + fmt.Sprint(req.Jti) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListLogs: List logs available for given Organization. You must define the `organization_id` in the query path of your request.
func (s *API) ListLogs(req *ListLogsRequest, opts ...scw.RequestOption) (*ListLogsResponse, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "created_after", req.CreatedAfter)
parameter.AddToQuery(query, "created_before", req.CreatedBefore)
parameter.AddToQuery(query, "action", req.Action)
parameter.AddToQuery(query, "resource_type", req.ResourceType)
parameter.AddToQuery(query, "search", req.Search)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/logs",
Query: query,
}
var resp ListLogsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetLog: Retrieve information about a log, specified by the `log_id` parameter. The log's full details, including `id`, `ip`, `user_agent`, `action`, `bearer_id`, `resource_type` and `resource_id` are returned in the response.
func (s *API) GetLog(req *GetLogRequest, opts ...scw.RequestOption) (*Log, error) {
var err error
if fmt.Sprint(req.LogID) == "" {
return nil, errors.New("field LogID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/logs/" + fmt.Sprint(req.LogID) + "",
}
var resp Log
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetOrganizationSecuritySettings: Retrieve information about the security settings of an Organization, specified by the `organization_id` parameter.
func (s *API) GetOrganizationSecuritySettings(req *GetOrganizationSecuritySettingsRequest, opts ...scw.RequestOption) (*OrganizationSecuritySettings, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if fmt.Sprint(req.OrganizationID) == "" {
return nil, errors.New("field OrganizationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iam/v1alpha1/organizations/" + fmt.Sprint(req.OrganizationID) + "/security-settings",
}
var resp OrganizationSecuritySettings
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateOrganizationSecuritySettings: Update the security settings of an Organization.
func (s *API) UpdateOrganizationSecuritySettings(req *UpdateOrganizationSecuritySettingsRequest, opts ...scw.RequestOption) (*OrganizationSecuritySettings, error) {
var err error
if req.OrganizationID == "" {
defaultOrganizationID, _ := s.client.GetDefaultOrganizationID()
req.OrganizationID = defaultOrganizationID
}
if fmt.Sprint(req.OrganizationID) == "" {
return nil, errors.New("field OrganizationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iam/v1alpha1/organizations/" + fmt.Sprint(req.OrganizationID) + "/security-settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp OrganizationSecuritySettings
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iam/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027035 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iam/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000010727 14747113137 0031230 0 ustar 00root root 0000000 0000000 package sweepers
import (
"errors"
"fmt"
iam "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepUser(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)
orgID, exists := scwClient.GetDefaultOrganizationID()
if !exists {
return errors.New("missing organizationID")
}
listUsers, err := api.ListUsers(&iam.ListUsersRequest{
OrganizationID: &orgID,
})
if err != nil {
return fmt.Errorf("failed to list users: %w", err)
}
for _, user := range listUsers.Users {
if !testhelpers.IsTestResource(user.Email) {
continue
}
err = api.DeleteUser(&iam.DeleteUserRequest{
UserID: user.ID,
})
if err != nil {
return fmt.Errorf("failed to delete user: %w", err)
}
}
return nil
}
func SweepSSHKey(scwClient *scw.Client) error {
iamAPI := iam.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the SSH keys")
listSSHKeys, err := iamAPI.ListSSHKeys(&iam.ListSSHKeysRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing SSH keys in sweeper: %s", err)
}
for _, sshKey := range listSSHKeys.SSHKeys {
err := iamAPI.DeleteSSHKey(&iam.DeleteSSHKeyRequest{
SSHKeyID: sshKey.ID,
})
if err != nil {
return fmt.Errorf("error deleting SSH key in sweeper: %s", err)
}
}
return nil
}
func SweepPolicy(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)
orgID, exists := scwClient.GetDefaultOrganizationID()
if !exists {
return errors.New("missing organizationID")
}
listPols, err := api.ListPolicies(&iam.ListPoliciesRequest{
OrganizationID: orgID,
})
if err != nil {
return fmt.Errorf("failed to list policies: %w", err)
}
for _, pol := range listPols.Policies {
if !testhelpers.IsTestResource(pol.Name) {
continue
}
err = api.DeletePolicy(&iam.DeletePolicyRequest{
PolicyID: pol.ID,
})
if err != nil {
return fmt.Errorf("failed to delete policy: %w", err)
}
}
return nil
}
func SweepGroup(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)
orgID, exists := scwClient.GetDefaultOrganizationID()
if !exists {
return errors.New("missing organizationID")
}
listApps, err := api.ListGroups(&iam.ListGroupsRequest{
OrganizationID: orgID,
})
if err != nil {
return fmt.Errorf("failed to list groups: %w", err)
}
for _, group := range listApps.Groups {
if !testhelpers.IsTestResource(group.Name) {
continue
}
err = api.DeleteGroup(&iam.DeleteGroupRequest{
GroupID: group.ID,
})
if err != nil {
return fmt.Errorf("failed to delete group: %w", err)
}
}
return nil
}
func SweepApplication(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)
orgID, exists := scwClient.GetDefaultOrganizationID()
if !exists {
return errors.New("missing organizationID")
}
listApps, err := api.ListApplications(&iam.ListApplicationsRequest{
OrganizationID: orgID,
})
if err != nil {
return fmt.Errorf("failed to list applications: %w", err)
}
for _, app := range listApps.Applications {
if !testhelpers.IsTestResource(app.Name) {
continue
}
err = api.DeleteApplication(&iam.DeleteApplicationRequest{
ApplicationID: app.ID,
})
if err != nil {
return fmt.Errorf("failed to delete application: %w", err)
}
}
return nil
}
func SweepAPIKey(scwClient *scw.Client) error {
api := iam.NewAPI(scwClient)
logger.Debugf("sweeper: destroying the api keys")
orgID, exists := scwClient.GetDefaultOrganizationID()
if !exists {
return errors.New("missing organizationID")
}
listAPIKeys, err := api.ListAPIKeys(&iam.ListAPIKeysRequest{
OrganizationID: &orgID,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list api keys: %w", err)
}
for _, key := range listAPIKeys.APIKeys {
if !testhelpers.IsTestResource(key.Description) {
continue
}
err = api.DeleteAPIKey(&iam.DeleteAPIKeyRequest{
AccessKey: key.AccessKey,
})
if err != nil {
return fmt.Errorf("failed to delete api key: %w", err)
}
}
return nil
}
func SweepAll(scwClient *scw.Client) error {
if err := SweepUser(scwClient); err != nil {
return err
}
if err := SweepSSHKey(scwClient); err != nil {
return err
}
if err := SweepPolicy(scwClient); err != nil {
return err
}
if err := SweepGroup(scwClient); err != nil {
return err
}
if err := SweepApplication(scwClient); err != nil {
return err
}
if err := SweepAPIKey(scwClient); err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/ 0000775 0000000 0000000 00000000000 14747113137 0024753 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0026216 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/v1beta1/inference_sdk.go 0000664 0000000 0000000 00000115154 14747113137 0031353 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package inference provides methods and message types of the inference v1beta1 API.
package inference
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DeploymentStatus string
const (
DeploymentStatusUnknownStatus = DeploymentStatus("unknown_status")
DeploymentStatusCreating = DeploymentStatus("creating")
DeploymentStatusDeploying = DeploymentStatus("deploying")
DeploymentStatusReady = DeploymentStatus("ready")
DeploymentStatusError = DeploymentStatus("error")
DeploymentStatusDeleting = DeploymentStatus("deleting")
DeploymentStatusLocked = DeploymentStatus("locked")
)
func (enum DeploymentStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DeploymentStatus) Values() []DeploymentStatus {
return []DeploymentStatus{
"unknown_status",
"creating",
"deploying",
"ready",
"error",
"deleting",
"locked",
}
}
func (enum DeploymentStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DeploymentStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DeploymentStatus(DeploymentStatus(tmp).String())
return nil
}
type ListDeploymentsRequestOrderBy string
const (
ListDeploymentsRequestOrderByCreatedAtDesc = ListDeploymentsRequestOrderBy("created_at_desc")
ListDeploymentsRequestOrderByCreatedAtAsc = ListDeploymentsRequestOrderBy("created_at_asc")
ListDeploymentsRequestOrderByNameAsc = ListDeploymentsRequestOrderBy("name_asc")
ListDeploymentsRequestOrderByNameDesc = ListDeploymentsRequestOrderBy("name_desc")
)
func (enum ListDeploymentsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListDeploymentsRequestOrderBy) Values() []ListDeploymentsRequestOrderBy {
return []ListDeploymentsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"name_asc",
"name_desc",
}
}
func (enum ListDeploymentsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDeploymentsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDeploymentsRequestOrderBy(ListDeploymentsRequestOrderBy(tmp).String())
return nil
}
type ListModelsRequestOrderBy string
const (
ListModelsRequestOrderByDisplayRankAsc = ListModelsRequestOrderBy("display_rank_asc")
ListModelsRequestOrderByCreatedAtAsc = ListModelsRequestOrderBy("created_at_asc")
ListModelsRequestOrderByCreatedAtDesc = ListModelsRequestOrderBy("created_at_desc")
ListModelsRequestOrderByNameAsc = ListModelsRequestOrderBy("name_asc")
ListModelsRequestOrderByNameDesc = ListModelsRequestOrderBy("name_desc")
)
func (enum ListModelsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "display_rank_asc"
}
return string(enum)
}
func (enum ListModelsRequestOrderBy) Values() []ListModelsRequestOrderBy {
return []ListModelsRequestOrderBy{
"display_rank_asc",
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListModelsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListModelsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListModelsRequestOrderBy(ListModelsRequestOrderBy(tmp).String())
return nil
}
type NodeTypeStock string
const (
NodeTypeStockUnknownStock = NodeTypeStock("unknown_stock")
NodeTypeStockLowStock = NodeTypeStock("low_stock")
NodeTypeStockOutOfStock = NodeTypeStock("out_of_stock")
NodeTypeStockAvailable = NodeTypeStock("available")
)
func (enum NodeTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown_stock"
}
return string(enum)
}
func (enum NodeTypeStock) Values() []NodeTypeStock {
return []NodeTypeStock{
"unknown_stock",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum NodeTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeStock(NodeTypeStock(tmp).String())
return nil
}
// EndpointPrivateNetworkDetails: endpoint private network details.
type EndpointPrivateNetworkDetails struct {
// PrivateNetworkID: ID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
}
// EndpointPublicAccessDetails: endpoint public access details.
type EndpointPublicAccessDetails struct {
}
// EndpointSpecPrivateNetwork: endpoint spec private network.
type EndpointSpecPrivateNetwork struct {
// PrivateNetworkID: ID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
}
// EndpointSpecPublic: endpoint spec public.
type EndpointSpecPublic struct {
}
// Endpoint: endpoint.
type Endpoint struct {
// ID: unique identifier.
ID string `json:"id"`
// URL: for private endpoints, the URL will be accessible only from the Private Network.
// In addition, private endpoints will expose a CA certificate that can be used to verify the server's identity.
// This CA certificate can be retrieved using the `GetDeploymentCertificate` API call.
URL string `json:"url"`
// PublicAccess: defines whether the endpoint is public.
// Precisely one of PublicAccess, PrivateNetwork must be set.
PublicAccess *EndpointPublicAccessDetails `json:"public_access,omitempty"`
// PrivateNetwork: details of the Private Network.
// Precisely one of PublicAccess, PrivateNetwork must be set.
PrivateNetwork *EndpointPrivateNetworkDetails `json:"private_network,omitempty"`
// DisableAuth: defines whether the authentication is disabled.
DisableAuth bool `json:"disable_auth"`
}
// ModelS3Model: model s3 model.
type ModelS3Model struct {
S3URL string `json:"s3_url"`
PythonDependencies map[string]string `json:"python_dependencies"`
NodeType *string `json:"node_type"`
TritonServerVersion *string `json:"triton_server_version"`
}
// ACLRuleRequest: acl rule request.
type ACLRuleRequest struct {
// IP: it can be specified as a single IP address or a range of IP addresses in CIDR notation.
IP scw.IPNet `json:"ip"`
// Description: description of the ACL rule.
Description string `json:"description"`
}
// ACLRule: acl rule.
type ACLRule struct {
// ID: unique identifier.
ID string `json:"id"`
// IP: allowed IP address or CIDR range.
IP scw.IPNet `json:"ip"`
// Description: description of the ACL rule.
Description string `json:"description"`
}
// EndpointSpec: endpoint spec.
type EndpointSpec struct {
// Public: set the endpoint as public.
// Precisely one of Public, PrivateNetwork must be set.
Public *EndpointSpecPublic `json:"public,omitempty"`
// PrivateNetwork: private endpoints are only accessible from the Private Network.
// Precisely one of Public, PrivateNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetwork `json:"private_network,omitempty"`
// DisableAuth: by default, deployments are protected by IAM authentication.
// When setting this field to true, the authentication will be disabled.
DisableAuth bool `json:"disable_auth"`
}
// Deployment: deployment.
type Deployment struct {
// ID: unique identifier.
ID string `json:"id"`
// Name: name of the deployment.
Name string `json:"name"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// Status: status of the deployment.
// Default value: unknown_status
Status DeploymentStatus `json:"status"`
// Tags: list of tags applied to the deployment.
Tags []string `json:"tags"`
// NodeType: node type of the deployment.
NodeType string `json:"node_type"`
// Endpoints: list of endpoints.
Endpoints []*Endpoint `json:"endpoints"`
// Size: current size of the pool.
Size uint32 `json:"size"`
// MinSize: defines the minimum size of the pool.
MinSize uint32 `json:"min_size"`
// MaxSize: defines the maximum size of the pool.
MaxSize uint32 `json:"max_size"`
// ErrorMessage: displays information if your deployment is in error state.
ErrorMessage *string `json:"error_message"`
// ModelName: the inference model used for the deployment.
ModelName string `json:"model_name"`
// ModelID: ID of the model used for the deployment.
ModelID string `json:"model_id"`
// CreatedAt: creation date of the deployment.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the deployment.
UpdatedAt *time.Time `json:"updated_at"`
// Region: region of the deployment.
Region scw.Region `json:"region"`
}
// Model: model.
type Model struct {
// ID: unique identifier.
ID string `json:"id"`
// Name: unique Name identifier.
Name string `json:"name"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// Provider: name of the model provider.
Provider string `json:"provider"`
// Tags: list of tags applied to the model.
Tags []string `json:"tags"`
// Description: purpose of the model.
Description string `json:"description"`
// HasEula: defines whether the model has an end user license agreement.
HasEula bool `json:"has_eula"`
// CreatedAt: creation date of the model.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the model.
UpdatedAt *time.Time `json:"updated_at"`
// Region: region of the model.
Region scw.Region `json:"region"`
// S3Model: object Storage URL pointing to the model source weight.
// Precisely one of S3Model must be set.
S3Model *ModelS3Model `json:"s3_model,omitempty"`
// IsPublic: defines whether the model is public or not.
IsPublic bool `json:"is_public"`
// CompatibleNodeTypes: names of the node types compatible with the model.
CompatibleNodeTypes []string `json:"compatible_node_types"`
// QuantizationLevel: quantization level of the model.
QuantizationLevel string `json:"quantization_level"`
}
// NodeType: node type.
type NodeType struct {
// Name: name of the node type.
Name string `json:"name"`
// StockStatus: current stock status for the node type.
// Default value: unknown_stock
StockStatus NodeTypeStock `json:"stock_status"`
// Description: current specs of the offer.
Description string `json:"description"`
// Vcpus: number of virtual CPUs.
Vcpus uint32 `json:"vcpus"`
// Memory: quantity of RAM.
Memory scw.Size `json:"memory"`
// Vram: quantity of GPU RAM.
Vram scw.Size `json:"vram"`
// Disabled: the node type is currently disabled.
Disabled bool `json:"disabled"`
// Beta: the node type is currently in beta.
Beta bool `json:"beta"`
// CreatedAt: creation date of the node type.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the node type.
UpdatedAt *time.Time `json:"updated_at"`
// Gpus: number of GPUs.
Gpus uint32 `json:"gpus"`
// Region: region of the node type.
Region scw.Region `json:"region"`
}
// AddDeploymentACLRulesRequest: add deployment acl rules request.
type AddDeploymentACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to add ACL rules to.
DeploymentID string `json:"-"`
// ACLs: list of ACL rules to add.
ACLs []*ACLRuleRequest `json:"acls"`
}
// AddDeploymentACLRulesResponse: add deployment acl rules response.
type AddDeploymentACLRulesResponse struct {
// Rules: list of ACL rules added.
Rules []*ACLRule `json:"rules"`
}
// CreateDeploymentRequest: create deployment request.
type CreateDeploymentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the deployment.
Name string `json:"name"`
// ProjectID: ID of the Project to create the deployment in.
ProjectID string `json:"project_id"`
// ModelName: name of the model to use.
ModelName string `json:"model_name"`
// AcceptEula: if the model has an EULA, you must accept it before proceeding.
// The terms of the EULA can be retrieved using the `GetModelEula` API call.
AcceptEula *bool `json:"accept_eula,omitempty"`
// NodeType: name of the node type to use.
NodeType string `json:"node_type"`
// Tags: list of tags to apply to the deployment.
Tags []string `json:"tags"`
// MinSize: defines the minimum size of the pool.
MinSize *uint32 `json:"min_size,omitempty"`
// MaxSize: defines the maximum size of the pool.
MaxSize *uint32 `json:"max_size,omitempty"`
// Endpoints: list of endpoints to create.
Endpoints []*EndpointSpec `json:"endpoints"`
}
// CreateEndpointRequest: create endpoint request.
type CreateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to create the endpoint for.
DeploymentID string `json:"deployment_id"`
// Endpoint: specification of the endpoint.
Endpoint *EndpointSpec `json:"endpoint"`
}
// DeleteDeploymentACLRuleRequest: delete deployment acl rule request.
type DeleteDeploymentACLRuleRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ACLID: ID of the ACL rule to delete.
ACLID string `json:"-"`
}
// DeleteDeploymentRequest: delete deployment request.
type DeleteDeploymentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to delete.
DeploymentID string `json:"-"`
}
// DeleteEndpointRequest: delete endpoint request.
type DeleteEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: ID of the endpoint to delete.
EndpointID string `json:"-"`
}
// Eula: eula.
type Eula struct {
// Content: content of the end user license agreement.
Content string `json:"content"`
}
// GetDeploymentCertificateRequest: get deployment certificate request.
type GetDeploymentCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
DeploymentID string `json:"-"`
}
// GetDeploymentRequest: get deployment request.
type GetDeploymentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to get.
DeploymentID string `json:"-"`
}
// GetModelEulaRequest: get model eula request.
type GetModelEulaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
ModelID string `json:"-"`
}
// GetModelRequest: get model request.
type GetModelRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ModelID: ID of the model to get.
ModelID string `json:"-"`
}
// ListDeploymentACLRulesRequest: list deployment acl rules request.
type ListDeploymentACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to list ACL rules for.
DeploymentID string `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of ACL rules to return per page.
PageSize *uint32 `json:"-"`
}
// ListDeploymentACLRulesResponse: list deployment acl rules response.
type ListDeploymentACLRulesResponse struct {
// Rules: list of ACL rules on the current page.
Rules []*ACLRule `json:"rules"`
// TotalCount: total number of ACL rules.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDeploymentACLRulesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDeploymentACLRulesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDeploymentACLRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint64(len(results.Rules))
return uint64(len(results.Rules)), nil
}
// ListDeploymentsRequest: list deployments request.
type ListDeploymentsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of deployments to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_desc
OrderBy ListDeploymentsRequestOrderBy `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// Name: filter by deployment name.
Name *string `json:"-"`
// Tags: filter by tags.
Tags []string `json:"-"`
}
// ListDeploymentsResponse: list deployments response.
type ListDeploymentsResponse struct {
// Deployments: list of deployments on the current page.
Deployments []*Deployment `json:"deployments"`
// TotalCount: total number of deployments.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDeploymentsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDeploymentsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDeploymentsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Deployments = append(r.Deployments, results.Deployments...)
r.TotalCount += uint64(len(results.Deployments))
return uint64(len(results.Deployments)), nil
}
// ListModelsRequest: list models request.
type ListModelsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: order in which to return results.
// Default value: display_rank_asc
OrderBy ListModelsRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of models to return per page.
PageSize *uint32 `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// Name: filter by model name.
Name *string `json:"-"`
// Tags: filter by tags.
Tags []string `json:"-"`
}
// ListModelsResponse: list models response.
type ListModelsResponse struct {
// Models: list of models on the current page.
Models []*Model `json:"models"`
// TotalCount: total number of models.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListModelsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListModelsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListModelsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Models = append(r.Models, results.Models...)
r.TotalCount += uint64(len(results.Models))
return uint64(len(results.Models)), nil
}
// ListNodeTypesRequest: list node types request.
type ListNodeTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of node types to return per page.
PageSize *uint32 `json:"-"`
// IncludeDisabledTypes: include disabled node types in the response.
IncludeDisabledTypes bool `json:"-"`
}
// ListNodeTypesResponse: list node types response.
type ListNodeTypesResponse struct {
// NodeTypes: list of node types.
NodeTypes []*NodeType `json:"node_types"`
// TotalCount: total number of node types.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListNodeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NodeTypes = append(r.NodeTypes, results.NodeTypes...)
r.TotalCount += uint64(len(results.NodeTypes))
return uint64(len(results.NodeTypes)), nil
}
// SetDeploymentACLRulesRequest: set deployment acl rules request.
type SetDeploymentACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to set ACL rules for.
DeploymentID string `json:"-"`
// ACLs: all existing ACL rules will be replaced by the new ones.
ACLs []*ACLRuleRequest `json:"acls"`
}
// SetDeploymentACLRulesResponse: set deployment acl rules response.
type SetDeploymentACLRulesResponse struct {
// Rules: list of ACL rules that were set.
Rules []*ACLRule `json:"rules"`
}
// UpdateDeploymentRequest: update deployment request.
type UpdateDeploymentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeploymentID: ID of the deployment to update.
DeploymentID string `json:"-"`
// Name: name of the deployment.
Name *string `json:"name,omitempty"`
// Tags: list of tags to apply to the deployment.
Tags *[]string `json:"tags,omitempty"`
// MinSize: defines the new minimum size of the pool.
MinSize *uint32 `json:"min_size,omitempty"`
// MaxSize: defines the new maximum size of the pool.
MaxSize *uint32 `json:"max_size,omitempty"`
}
// UpdateEndpointRequest: update endpoint request.
type UpdateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: ID of the endpoint to update.
EndpointID string `json:"-"`
// DisableAuth: by default, deployments are protected by IAM authentication.
// When setting this field to true, the authentication will be disabled.
DisableAuth *bool `json:"disable_auth,omitempty"`
}
// This API allows you to manage your Inference services.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar}
}
// ListDeployments: List all your inference deployments.
func (s *API) ListDeployments(req *ListDeploymentsRequest, opts ...scw.RequestOption) (*ListDeploymentsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments",
Query: query,
}
var resp ListDeploymentsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDeployment: Get the deployment for the given ID.
func (s *API) GetDeployment(req *GetDeploymentRequest, opts ...scw.RequestOption) (*Deployment, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "",
}
var resp Deployment
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDeployment: Create a new inference deployment related to a specific model.
func (s *API) CreateDeployment(req *CreateDeploymentRequest, opts ...scw.RequestOption) (*Deployment, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("inference")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Deployment
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDeployment: Update an existing inference deployment.
func (s *API) UpdateDeployment(req *UpdateDeploymentRequest, opts ...scw.RequestOption) (*Deployment, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Deployment
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDeployment: Delete an existing inference deployment.
func (s *API) DeleteDeployment(req *DeleteDeploymentRequest, opts ...scw.RequestOption) (*Deployment, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "",
}
var resp Deployment
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDeploymentCertificate: Get the CA certificate used for the deployment of private endpoints.
// The CA certificate will be returned as a PEM file.
func (s *API) GetDeploymentCertificate(req *GetDeploymentCertificateRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "/certificate",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateEndpoint: Create a new Endpoint related to a specific deployment.
func (s *API) CreateEndpoint(req *CreateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateEndpoint: Update an existing Endpoint.
func (s *API) UpdateEndpoint(req *UpdateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteEndpoint: Delete an existing Endpoint.
func (s *API) DeleteEndpoint(req *DeleteEndpointRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDeploymentACLRules: List ACLs for a specific deployment.
func (s *API) ListDeploymentACLRules(req *ListDeploymentACLRulesRequest, opts ...scw.RequestOption) (*ListDeploymentACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "/acls",
Query: query,
}
var resp ListDeploymentACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddDeploymentACLRules: Add new ACL rules for a specific deployment.
func (s *API) AddDeploymentACLRules(req *AddDeploymentACLRulesRequest, opts ...scw.RequestOption) (*AddDeploymentACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddDeploymentACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetDeploymentACLRules: Set new ACL rules for a specific deployment.
func (s *API) SetDeploymentACLRules(req *SetDeploymentACLRulesRequest, opts ...scw.RequestOption) (*SetDeploymentACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeploymentID) == "" {
return nil, errors.New("field DeploymentID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deployments/" + fmt.Sprint(req.DeploymentID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetDeploymentACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDeploymentACLRule: Delete an exising ACL.
func (s *API) DeleteDeploymentACLRule(req *DeleteDeploymentACLRuleRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListModels: List all available models.
func (s *API) ListModels(req *ListModelsRequest, opts ...scw.RequestOption) (*ListModelsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/models",
Query: query,
}
var resp ListModelsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetModel: Get the model for the given ID.
func (s *API) GetModel(req *GetModelRequest, opts ...scw.RequestOption) (*Model, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ModelID) == "" {
return nil, errors.New("field ModelID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/models/" + fmt.Sprint(req.ModelID) + "",
}
var resp Model
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetModelEula:
func (s *API) GetModelEula(req *GetModelEulaRequest, opts ...scw.RequestOption) (*Eula, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ModelID) == "" {
return nil, errors.New("field ModelID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/models/" + fmt.Sprint(req.ModelID) + "/eula",
}
var resp Eula
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNodeTypes: List all available node types. By default, the node types returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListNodeTypes(req *ListNodeTypesRequest, opts ...scw.RequestOption) (*ListNodeTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "include_disabled_types", req.IncludeDisabledTypes)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/inference/v1beta1/regions/" + fmt.Sprint(req.Region) + "/node-types",
Query: query,
}
var resp ListNodeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/v1beta1/inference_utils.go 0000664 0000000 0000000 00000002757 14747113137 0031736 0 ustar 00root root 0000000 0000000 package inference
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 30 * time.Minute
)
type WaitForDeploymentRequest struct {
DeploymentID string
Region scw.Region
Status DeploymentStatus
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForDeployment(req *WaitForDeploymentRequest, opts ...scw.RequestOption) (*Deployment, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DeploymentStatus]struct{}{
DeploymentStatusReady: {},
DeploymentStatusError: {},
DeploymentStatusLocked: {},
}
deployment, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
deployment, err := s.GetDeployment(&GetDeploymentRequest{
Region: req.Region,
DeploymentID: req.DeploymentID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[deployment.Status]
return deployment, isTerminal, nil
},
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
Timeout: timeout,
})
if err != nil {
return nil, errors.Wrap(err, "waiting for deployment failed")
}
return deployment.(*Deployment), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/v1beta1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0030053 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/inference/v1beta1/sweepers/sweepers.go 0000664 0000000 0000000 00000002206 14747113137 0032237 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
inference "github.com/scaleway/scaleway-sdk-go/api/inference/v1beta1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepDeployment(scwClient *scw.Client, region scw.Region) error {
inferenceAPI := inference.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the inference deployments in (%s)", region)
listDeployments, err := inferenceAPI.ListDeployments(
&inference.ListDeploymentsRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing deployment in (%s) in sweeper: %s", region, err)
}
for _, deployment := range listDeployments.Deployments {
_, err := inferenceAPI.DeleteDeployment(&inference.DeleteDeploymentRequest{
DeploymentID: deployment.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting deployment in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, locality := range (&inference.API{}).Regions() {
err := SweepDeployment(scwClient, locality)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/ 0000775 0000000 0000000 00000000000 14747113137 0024621 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/ 0000775 0000000 0000000 00000000000 14747113137 0025147 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/image_utils.go 0000664 0000000 0000000 00000002601 14747113137 0027777 0 ustar 00root root 0000000 0000000 package instance
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForImageRequest is used by WaitForImage method.
type WaitForImageRequest struct {
ImageID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForImage wait for the image to be in a "terminal state" before returning.
func (s *API) WaitForImage(req *WaitForImageRequest, opts ...scw.RequestOption) (*Image, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ImageState]struct{}{
ImageStateAvailable: {},
ImageStateError: {},
}
image, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetImage(&GetImageRequest{
ImageID: req.ImageID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Image.State]
return res.Image, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for image failed")
}
return image.(*Image), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/image_utils_test.go 0000664 0000000 0000000 00000004475 14747113137 0031051 0 ustar 00root root 0000000 0000000 package instance
import (
"strings"
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestWaitForImage(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("image-wait-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
imageName := "backup"
image, cleanup := createImage(t, instanceAPI, imageName)
defer cleanup()
res, err := instanceAPI.WaitForImage(&WaitForImageRequest{
ImageID: image.ID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, image.ID, res.ID)
testhelpers.Equals(t, ImageStateAvailable, res.State)
testhelpers.Equals(t, imageName, res.Name)
}
// createImage cis a helper that create an image.
// It return the newly created image and a cleanup function
func createImage(t *testing.T, instanceAPI *API, imageName string) (*Image, func()) {
t.Helper()
serverRes, err := instanceAPI.CreateServer(&CreateServerRequest{
CommercialType: "DEV1-M",
Image: scw.StringPtr("ubuntu_focal"),
})
testhelpers.AssertNoError(t, err)
// Backup will create a snapshot for each volume + an image base on all snapshots.
backupRes, err := instanceAPI.ServerAction(&ServerActionRequest{
ServerID: serverRes.Server.ID,
Action: ServerActionBackup,
Name: &imageName,
})
testhelpers.AssertNoError(t, err)
tmp := strings.Split(backupRes.Task.HrefResult, "/")
imageID := tmp[2]
imageRes, err := instanceAPI.GetImage(&GetImageRequest{
ImageID: imageID,
})
testhelpers.AssertNoError(t, err)
return imageRes.Image, func() {
// Delete all created resources
err := instanceAPI.DeleteServer(&DeleteServerRequest{
ServerID: serverRes.Server.ID,
})
testhelpers.AssertNoError(t, err)
err = instanceAPI.DeleteVolume(&DeleteVolumeRequest{
VolumeID: serverRes.Server.Volumes["0"].ID,
})
testhelpers.AssertNoError(t, err)
err = instanceAPI.DeleteImage(&DeleteImageRequest{
ImageID: imageRes.Image.ID,
})
testhelpers.AssertNoError(t, err)
err = instanceAPI.DeleteSnapshot(&DeleteSnapshotRequest{
SnapshotID: imageRes.Image.RootVolume.ID,
})
testhelpers.AssertNoError(t, err)
}
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/instance_metadata_sdk.go 0000664 0000000 0000000 00000025352 14747113137 0032012 0 ustar 00root root 0000000 0000000 package instance
import (
"bytes"
"context"
"encoding/json"
"io"
"math/rand"
"net"
"net/http"
"strconv"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/logger"
)
var metadataRetryBindPort = 200
const (
metadataAPIv4 = "http://169.254.42.42"
metadataAPIv6 = "http://[fd00:42::42]"
)
// MetadataAPI metadata API
type MetadataAPI struct {
MetadataURL *string
}
// NewMetadataAPI returns a MetadataAPI object from a Scaleway client.
func NewMetadataAPI() *MetadataAPI {
return &MetadataAPI{}
}
func (meta *MetadataAPI) getMetadataURL() string {
if meta.MetadataURL != nil {
return *meta.MetadataURL
}
ctx := context.Background()
for _, url := range []string{metadataAPIv4, metadataAPIv6} {
http.DefaultClient.Timeout = 3 * time.Second
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, bytes.NewBufferString(""))
if err != nil {
logger.Warningf("Failed to create metadata URL %s: %v", url, err)
}
resp, err := http.DefaultClient.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
meta.MetadataURL = &url
return url
}
defer resp.Body.Close()
}
return metadataAPIv4
}
// GetMetadata returns the metadata available from the server
func (meta *MetadataAPI) GetMetadata() (m *Metadata, err error) {
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, meta.getMetadataURL()+"/conf?format=json", bytes.NewBufferString(""))
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error getting metadataURL")
}
defer resp.Body.Close()
metadata := &Metadata{}
err = json.NewDecoder(resp.Body).Decode(metadata)
if err != nil {
return nil, errors.Wrap(err, "error decoding metadata")
}
return metadata, nil
}
// MetadataIP represents all public IPs attached
type MetadataIP struct {
ID string `json:"id"`
Address string `json:"address"`
Dynamic bool `json:"dynamic"`
Gateway string `json:"gateway"`
Netmask string `json:"netmask"`
Family string `json:"family"`
ProvisioningMode string `json:"provisioning_mode"`
Tags []string `json:"tags"`
}
// Metadata represents the struct return by the metadata API
type Metadata struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Hostname string `json:"hostname,omitempty"`
Organization string `json:"organization,omitempty"`
Project string `json:"project,omitempty"`
CommercialType string `json:"commercial_type,omitempty"`
// PublicIP IPv4 only
PublicIP struct {
ID string `json:"id"`
Address string `json:"address"`
Dynamic bool `json:"dynamic"`
Gateway string `json:"gateway"`
Netmask string `json:"netmask"`
Family string `json:"family"`
ProvisioningMode string `json:"provisioning_mode"`
} `json:"public_ip,omitempty"`
PublicIpsV4 []MetadataIP `json:"public_ips_v4,omitempty"`
PublicIpsV6 []MetadataIP `json:"public_ips_v6,omitempty"`
PrivateIP string `json:"private_ip,omitempty"`
IPv6 struct {
Netmask string `json:"netmask,omitempty"`
Gateway string `json:"gateway,omitempty"`
Address string `json:"address,omitempty"`
} `json:"ipv6,omitempty"`
Location struct {
PlatformID string `json:"platform_id,omitempty"`
HypervisorID string `json:"hypervisor_id,omitempty"`
NodeID string `json:"node_id,omitempty"`
ClusterID string `json:"cluster_id,omitempty"`
ZoneID string `json:"zone_id,omitempty"`
} `json:"location,omitempty"`
Tags []string `json:"tags,omitempty"`
StateDetail string `json:"state_detail,omitempty"`
SSHPublicKeys []struct {
Description string `json:"description,omitempty"`
ModificationDate string `json:"modification_date,omitempty"`
IP string `json:"ip,omitempty"`
Key string `json:"key,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
ID string `json:"id,omitempty"`
CreationDate string `json:"creation_date,omitempty"`
} `json:"ssh_public_keys,omitempty"`
Timezone string `json:"timezone,omitempty"`
Bootscript struct {
Kernel string `json:"kernel,omitempty"`
Title string `json:"title,omitempty"`
Default bool `json:"default,omitempty"`
Dtb string `json:"dtb,omitempty"`
Public bool `json:"publc,omitempty"`
Initrd string `json:"initrd,omitempty"`
Bootcmdargs string `json:"bootcmdargs,omitempty"`
Architecture string `json:"architecture,omitempty"`
Organization string `json:"organization,omitempty"`
Project string `json:"project,omitempty"`
ID string `json:"id,omitempty"`
} `json:"bootscript,omitempty"`
Volumes map[string]struct {
Name string `json:"name,omitempty"`
ModificationDate string `json:"modification_date,omitempty"`
ExportURI string `json:"export_uri,omitempty"`
VolumeType string `json:"volume_type,omitempty"`
CreationDate string `json:"creation_date,omitempty"`
State string `json:"state,omitempty"`
Organization string `json:"organization,omitempty"`
Project string `json:"project,omitempty"`
Server struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
} `json:"server,omitempty"`
ID string `json:"id,omitempty"`
Size int `json:"size,omitempty"`
} `json:"volumes,omitempty"`
PrivateNICs []struct {
ID string `json:"id,omitempty"`
PrivateNetworkID string `json:"private_network_id,omitempty"`
ServerID string `json:"server_id,omitempty"`
MacAddress string `json:"mac_address,omitempty"`
CreationDate string `json:"creation_date,omitempty"`
Zone string `json:"zone,omitempty"`
} `json:"private_nics,omitempty"`
}
// ListUserData returns the metadata available from the server
func (meta *MetadataAPI) ListUserData() (res *UserData, err error) {
retries := 0
ctx := context.Background()
for retries <= metadataRetryBindPort {
port := rand.Intn(1024)
localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port))
if err != nil {
return nil, errors.Wrap(err, "error resolving tcp address")
}
userdataClient := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
LocalAddr: localTCPAddr,
DualStack: false,
FallbackDelay: time.Second * -1,
}).DialContext,
},
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, meta.getMetadataURL()+"/user_data?format=json", bytes.NewBufferString(""))
if err != nil {
return nil, err
}
resp, err := userdataClient.Do(req)
if err != nil {
retries++ // retry with a different source port
continue
}
defer resp.Body.Close()
userdata := &UserData{}
err = json.NewDecoder(resp.Body).Decode(userdata)
if err != nil {
return nil, errors.Wrap(err, "error decoding userdata")
}
return userdata, nil
}
return nil, errors.New("too many bind port retries for ListUserData")
}
// GetUserData returns the value for the given metadata key
func (meta *MetadataAPI) GetUserData(key string) ([]byte, error) {
if key == "" {
return make([]byte, 0), errors.New("key must not be empty in GetUserData")
}
ctx := context.Background()
retries := 0
for retries <= metadataRetryBindPort {
port := rand.Intn(1024)
localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port))
if err != nil {
return make([]byte, 0), errors.Wrap(err, "error resolving tcp address")
}
userdataClient := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
LocalAddr: localTCPAddr,
DualStack: false,
FallbackDelay: time.Second * -1,
}).DialContext,
},
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, meta.getMetadataURL()+"/user_data/"+key, bytes.NewBufferString(""))
if err != nil {
return nil, err
}
resp, err := userdataClient.Do(req)
if err != nil {
retries++ // retry with a different source port
continue
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return make([]byte, 0), errors.Wrap(err, "error reading userdata body")
}
return body, nil
}
return make([]byte, 0), errors.New("too may bind port retries for GetUserData")
}
// SetUserData sets the userdata key with the given value
func (meta *MetadataAPI) SetUserData(key string, value []byte) error {
if key == "" {
return errors.New("key must not be empty in SetUserData")
}
ctx := context.Background()
retries := 0
for retries <= metadataRetryBindPort {
port := rand.Intn(1024)
localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port))
if err != nil {
return errors.Wrap(err, "error resolving tcp address")
}
userdataClient := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
LocalAddr: localTCPAddr,
DualStack: false,
FallbackDelay: time.Second * -1,
}).DialContext,
},
}
request, err := http.NewRequestWithContext(ctx, http.MethodPatch, meta.getMetadataURL()+"/user_data/"+key, bytes.NewBuffer(value))
if err != nil {
return errors.Wrap(err, "error creating patch userdata request")
}
request.Header.Set("Content-Type", "text/plain")
resp, err := userdataClient.Do(request)
if err != nil {
retries++ // retry with a different source port
continue
}
defer resp.Body.Close()
return nil
}
return errors.New("too may bind port retries for SetUserData")
}
// DeleteUserData deletes the userdata key and the associated value
func (meta *MetadataAPI) DeleteUserData(key string) error {
if key == "" {
return errors.New("key must not be empty in DeleteUserData")
}
ctx := context.Background()
retries := 0
for retries <= metadataRetryBindPort {
port := rand.Intn(1024)
localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port))
if err != nil {
return errors.Wrap(err, "error resolving tcp address")
}
userdataClient := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
LocalAddr: localTCPAddr,
DualStack: false,
FallbackDelay: time.Second * -1,
}).DialContext,
},
}
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, meta.getMetadataURL()+"/user_data/"+key, bytes.NewBufferString(""))
if err != nil {
return errors.Wrap(err, "error creating delete userdata request")
}
resp, err := userdataClient.Do(request)
if err != nil {
retries++ // retry with a different source port
continue
}
defer resp.Body.Close()
return nil
}
return errors.New("too may bind port retries for DeleteUserData")
}
// UserData represents the user data
type UserData struct {
UserData []string `json:"user_data,omitempty"`
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/instance_sdk.go 0000664 0000000 0000000 00000560345 14747113137 0030160 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package instance provides methods and message types of the instance v1 API.
package instance
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type Arch string
const (
ArchUnknownArch = Arch("unknown_arch")
ArchX86_64 = Arch("x86_64")
ArchArm = Arch("arm")
ArchArm64 = Arch("arm64")
)
func (enum Arch) String() string {
if enum == "" {
// return default value if empty
return "unknown_arch"
}
return string(enum)
}
func (enum Arch) Values() []Arch {
return []Arch{
"unknown_arch",
"x86_64",
"arm",
"arm64",
}
}
func (enum Arch) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Arch) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Arch(Arch(tmp).String())
return nil
}
type AttachServerVolumeRequestVolumeType string
const (
AttachServerVolumeRequestVolumeTypeUnknownVolumeType = AttachServerVolumeRequestVolumeType("unknown_volume_type")
AttachServerVolumeRequestVolumeTypeLSSD = AttachServerVolumeRequestVolumeType("l_ssd")
AttachServerVolumeRequestVolumeTypeBSSD = AttachServerVolumeRequestVolumeType("b_ssd")
AttachServerVolumeRequestVolumeTypeSbsVolume = AttachServerVolumeRequestVolumeType("sbs_volume")
)
func (enum AttachServerVolumeRequestVolumeType) String() string {
if enum == "" {
// return default value if empty
return "unknown_volume_type"
}
return string(enum)
}
func (enum AttachServerVolumeRequestVolumeType) Values() []AttachServerVolumeRequestVolumeType {
return []AttachServerVolumeRequestVolumeType{
"unknown_volume_type",
"l_ssd",
"b_ssd",
"sbs_volume",
}
}
func (enum AttachServerVolumeRequestVolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *AttachServerVolumeRequestVolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = AttachServerVolumeRequestVolumeType(AttachServerVolumeRequestVolumeType(tmp).String())
return nil
}
type BootType string
const (
BootTypeLocal = BootType("local")
BootTypeBootscript = BootType("bootscript")
BootTypeRescue = BootType("rescue")
)
func (enum BootType) String() string {
if enum == "" {
// return default value if empty
return "local"
}
return string(enum)
}
func (enum BootType) Values() []BootType {
return []BootType{
"local",
"bootscript",
"rescue",
}
}
func (enum BootType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BootType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BootType(BootType(tmp).String())
return nil
}
type IPState string
const (
IPStateUnknownState = IPState("unknown_state")
IPStateDetached = IPState("detached")
IPStateAttached = IPState("attached")
IPStatePending = IPState("pending")
IPStateError = IPState("error")
)
func (enum IPState) String() string {
if enum == "" {
// return default value if empty
return "unknown_state"
}
return string(enum)
}
func (enum IPState) Values() []IPState {
return []IPState{
"unknown_state",
"detached",
"attached",
"pending",
"error",
}
}
func (enum IPState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPState(IPState(tmp).String())
return nil
}
type IPType string
const (
IPTypeUnknownIptype = IPType("unknown_iptype")
IPTypeRoutedIPv4 = IPType("routed_ipv4")
IPTypeRoutedIPv6 = IPType("routed_ipv6")
)
func (enum IPType) String() string {
if enum == "" {
// return default value if empty
return "unknown_iptype"
}
return string(enum)
}
func (enum IPType) Values() []IPType {
return []IPType{
"unknown_iptype",
"routed_ipv4",
"routed_ipv6",
}
}
func (enum IPType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *IPType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = IPType(IPType(tmp).String())
return nil
}
type ImageState string
const (
ImageStateAvailable = ImageState("available")
ImageStateCreating = ImageState("creating")
ImageStateError = ImageState("error")
)
func (enum ImageState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum ImageState) Values() []ImageState {
return []ImageState{
"available",
"creating",
"error",
}
}
func (enum ImageState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ImageState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ImageState(ImageState(tmp).String())
return nil
}
type ListServersRequestOrder string
const (
ListServersRequestOrderCreationDateDesc = ListServersRequestOrder("creation_date_desc")
ListServersRequestOrderCreationDateAsc = ListServersRequestOrder("creation_date_asc")
ListServersRequestOrderModificationDateDesc = ListServersRequestOrder("modification_date_desc")
ListServersRequestOrderModificationDateAsc = ListServersRequestOrder("modification_date_asc")
)
func (enum ListServersRequestOrder) String() string {
if enum == "" {
// return default value if empty
return "creation_date_desc"
}
return string(enum)
}
func (enum ListServersRequestOrder) Values() []ListServersRequestOrder {
return []ListServersRequestOrder{
"creation_date_desc",
"creation_date_asc",
"modification_date_desc",
"modification_date_asc",
}
}
func (enum ListServersRequestOrder) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListServersRequestOrder) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListServersRequestOrder(ListServersRequestOrder(tmp).String())
return nil
}
type PlacementGroupPolicyMode string
const (
PlacementGroupPolicyModeOptional = PlacementGroupPolicyMode("optional")
PlacementGroupPolicyModeEnforced = PlacementGroupPolicyMode("enforced")
)
func (enum PlacementGroupPolicyMode) String() string {
if enum == "" {
// return default value if empty
return "optional"
}
return string(enum)
}
func (enum PlacementGroupPolicyMode) Values() []PlacementGroupPolicyMode {
return []PlacementGroupPolicyMode{
"optional",
"enforced",
}
}
func (enum PlacementGroupPolicyMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlacementGroupPolicyMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlacementGroupPolicyMode(PlacementGroupPolicyMode(tmp).String())
return nil
}
type PlacementGroupPolicyType string
const (
PlacementGroupPolicyTypeMaxAvailability = PlacementGroupPolicyType("max_availability")
PlacementGroupPolicyTypeLowLatency = PlacementGroupPolicyType("low_latency")
)
func (enum PlacementGroupPolicyType) String() string {
if enum == "" {
// return default value if empty
return "max_availability"
}
return string(enum)
}
func (enum PlacementGroupPolicyType) Values() []PlacementGroupPolicyType {
return []PlacementGroupPolicyType{
"max_availability",
"low_latency",
}
}
func (enum PlacementGroupPolicyType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlacementGroupPolicyType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlacementGroupPolicyType(PlacementGroupPolicyType(tmp).String())
return nil
}
type PrivateNICState string
const (
PrivateNICStateAvailable = PrivateNICState("available")
PrivateNICStateSyncing = PrivateNICState("syncing")
PrivateNICStateSyncingError = PrivateNICState("syncing_error")
)
func (enum PrivateNICState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum PrivateNICState) Values() []PrivateNICState {
return []PrivateNICState{
"available",
"syncing",
"syncing_error",
}
}
func (enum PrivateNICState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PrivateNICState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PrivateNICState(PrivateNICState(tmp).String())
return nil
}
type SecurityGroupPolicy string
const (
SecurityGroupPolicyUnknownPolicy = SecurityGroupPolicy("unknown_policy")
SecurityGroupPolicyAccept = SecurityGroupPolicy("accept")
SecurityGroupPolicyDrop = SecurityGroupPolicy("drop")
)
func (enum SecurityGroupPolicy) String() string {
if enum == "" {
// return default value if empty
return "unknown_policy"
}
return string(enum)
}
func (enum SecurityGroupPolicy) Values() []SecurityGroupPolicy {
return []SecurityGroupPolicy{
"unknown_policy",
"accept",
"drop",
}
}
func (enum SecurityGroupPolicy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecurityGroupPolicy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecurityGroupPolicy(SecurityGroupPolicy(tmp).String())
return nil
}
type SecurityGroupRuleAction string
const (
SecurityGroupRuleActionUnknownAction = SecurityGroupRuleAction("unknown_action")
SecurityGroupRuleActionAccept = SecurityGroupRuleAction("accept")
SecurityGroupRuleActionDrop = SecurityGroupRuleAction("drop")
)
func (enum SecurityGroupRuleAction) String() string {
if enum == "" {
// return default value if empty
return "unknown_action"
}
return string(enum)
}
func (enum SecurityGroupRuleAction) Values() []SecurityGroupRuleAction {
return []SecurityGroupRuleAction{
"unknown_action",
"accept",
"drop",
}
}
func (enum SecurityGroupRuleAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecurityGroupRuleAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecurityGroupRuleAction(SecurityGroupRuleAction(tmp).String())
return nil
}
type SecurityGroupRuleDirection string
const (
SecurityGroupRuleDirectionUnknownDirection = SecurityGroupRuleDirection("unknown_direction")
SecurityGroupRuleDirectionInbound = SecurityGroupRuleDirection("inbound")
SecurityGroupRuleDirectionOutbound = SecurityGroupRuleDirection("outbound")
)
func (enum SecurityGroupRuleDirection) String() string {
if enum == "" {
// return default value if empty
return "unknown_direction"
}
return string(enum)
}
func (enum SecurityGroupRuleDirection) Values() []SecurityGroupRuleDirection {
return []SecurityGroupRuleDirection{
"unknown_direction",
"inbound",
"outbound",
}
}
func (enum SecurityGroupRuleDirection) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecurityGroupRuleDirection) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecurityGroupRuleDirection(SecurityGroupRuleDirection(tmp).String())
return nil
}
type SecurityGroupRuleProtocol string
const (
SecurityGroupRuleProtocolUnknownProtocol = SecurityGroupRuleProtocol("unknown_protocol")
SecurityGroupRuleProtocolTCP = SecurityGroupRuleProtocol("TCP")
SecurityGroupRuleProtocolUDP = SecurityGroupRuleProtocol("UDP")
SecurityGroupRuleProtocolICMP = SecurityGroupRuleProtocol("ICMP")
SecurityGroupRuleProtocolANY = SecurityGroupRuleProtocol("ANY")
)
func (enum SecurityGroupRuleProtocol) String() string {
if enum == "" {
// return default value if empty
return "unknown_protocol"
}
return string(enum)
}
func (enum SecurityGroupRuleProtocol) Values() []SecurityGroupRuleProtocol {
return []SecurityGroupRuleProtocol{
"unknown_protocol",
"TCP",
"UDP",
"ICMP",
"ANY",
}
}
func (enum SecurityGroupRuleProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecurityGroupRuleProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecurityGroupRuleProtocol(SecurityGroupRuleProtocol(tmp).String())
return nil
}
type SecurityGroupState string
const (
SecurityGroupStateAvailable = SecurityGroupState("available")
SecurityGroupStateSyncing = SecurityGroupState("syncing")
SecurityGroupStateSyncingError = SecurityGroupState("syncing_error")
)
func (enum SecurityGroupState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum SecurityGroupState) Values() []SecurityGroupState {
return []SecurityGroupState{
"available",
"syncing",
"syncing_error",
}
}
func (enum SecurityGroupState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecurityGroupState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecurityGroupState(SecurityGroupState(tmp).String())
return nil
}
type ServerAction string
const (
ServerActionPoweron = ServerAction("poweron")
ServerActionBackup = ServerAction("backup")
ServerActionStopInPlace = ServerAction("stop_in_place")
ServerActionPoweroff = ServerAction("poweroff")
ServerActionTerminate = ServerAction("terminate")
ServerActionReboot = ServerAction("reboot")
ServerActionEnableRoutedIP = ServerAction("enable_routed_ip")
)
func (enum ServerAction) String() string {
if enum == "" {
// return default value if empty
return "poweron"
}
return string(enum)
}
func (enum ServerAction) Values() []ServerAction {
return []ServerAction{
"poweron",
"backup",
"stop_in_place",
"poweroff",
"terminate",
"reboot",
"enable_routed_ip",
}
}
func (enum ServerAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerAction(ServerAction(tmp).String())
return nil
}
type ServerIPIPFamily string
const (
ServerIPIPFamilyInet = ServerIPIPFamily("inet")
ServerIPIPFamilyInet6 = ServerIPIPFamily("inet6")
)
func (enum ServerIPIPFamily) String() string {
if enum == "" {
// return default value if empty
return "inet"
}
return string(enum)
}
func (enum ServerIPIPFamily) Values() []ServerIPIPFamily {
return []ServerIPIPFamily{
"inet",
"inet6",
}
}
func (enum ServerIPIPFamily) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerIPIPFamily) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerIPIPFamily(ServerIPIPFamily(tmp).String())
return nil
}
type ServerIPProvisioningMode string
const (
ServerIPProvisioningModeManual = ServerIPProvisioningMode("manual")
ServerIPProvisioningModeDHCP = ServerIPProvisioningMode("dhcp")
ServerIPProvisioningModeSlaac = ServerIPProvisioningMode("slaac")
)
func (enum ServerIPProvisioningMode) String() string {
if enum == "" {
// return default value if empty
return "manual"
}
return string(enum)
}
func (enum ServerIPProvisioningMode) Values() []ServerIPProvisioningMode {
return []ServerIPProvisioningMode{
"manual",
"dhcp",
"slaac",
}
}
func (enum ServerIPProvisioningMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerIPProvisioningMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerIPProvisioningMode(ServerIPProvisioningMode(tmp).String())
return nil
}
type ServerIPState string
const (
ServerIPStateUnknownState = ServerIPState("unknown_state")
ServerIPStateDetached = ServerIPState("detached")
ServerIPStateAttached = ServerIPState("attached")
ServerIPStatePending = ServerIPState("pending")
ServerIPStateError = ServerIPState("error")
)
func (enum ServerIPState) String() string {
if enum == "" {
// return default value if empty
return "unknown_state"
}
return string(enum)
}
func (enum ServerIPState) Values() []ServerIPState {
return []ServerIPState{
"unknown_state",
"detached",
"attached",
"pending",
"error",
}
}
func (enum ServerIPState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerIPState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerIPState(ServerIPState(tmp).String())
return nil
}
type ServerState string
const (
ServerStateRunning = ServerState("running")
ServerStateStopped = ServerState("stopped")
ServerStateStoppedInPlace = ServerState("stopped in place")
ServerStateStarting = ServerState("starting")
ServerStateStopping = ServerState("stopping")
ServerStateLocked = ServerState("locked")
)
func (enum ServerState) String() string {
if enum == "" {
// return default value if empty
return "running"
}
return string(enum)
}
func (enum ServerState) Values() []ServerState {
return []ServerState{
"running",
"stopped",
"stopped in place",
"starting",
"stopping",
"locked",
}
}
func (enum ServerState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerState(ServerState(tmp).String())
return nil
}
type ServerTypesAvailability string
const (
ServerTypesAvailabilityAvailable = ServerTypesAvailability("available")
ServerTypesAvailabilityScarce = ServerTypesAvailability("scarce")
ServerTypesAvailabilityShortage = ServerTypesAvailability("shortage")
)
func (enum ServerTypesAvailability) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum ServerTypesAvailability) Values() []ServerTypesAvailability {
return []ServerTypesAvailability{
"available",
"scarce",
"shortage",
}
}
func (enum ServerTypesAvailability) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ServerTypesAvailability) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ServerTypesAvailability(ServerTypesAvailability(tmp).String())
return nil
}
type SnapshotState string
const (
SnapshotStateAvailable = SnapshotState("available")
SnapshotStateSnapshotting = SnapshotState("snapshotting")
SnapshotStateError = SnapshotState("error")
SnapshotStateInvalidData = SnapshotState("invalid_data")
SnapshotStateImporting = SnapshotState("importing")
SnapshotStateExporting = SnapshotState("exporting")
)
func (enum SnapshotState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum SnapshotState) Values() []SnapshotState {
return []SnapshotState{
"available",
"snapshotting",
"error",
"invalid_data",
"importing",
"exporting",
}
}
func (enum SnapshotState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotState(SnapshotState(tmp).String())
return nil
}
type SnapshotVolumeType string
const (
SnapshotVolumeTypeUnknownVolumeType = SnapshotVolumeType("unknown_volume_type")
SnapshotVolumeTypeLSSD = SnapshotVolumeType("l_ssd")
SnapshotVolumeTypeBSSD = SnapshotVolumeType("b_ssd")
SnapshotVolumeTypeUnified = SnapshotVolumeType("unified")
)
func (enum SnapshotVolumeType) String() string {
if enum == "" {
// return default value if empty
return "unknown_volume_type"
}
return string(enum)
}
func (enum SnapshotVolumeType) Values() []SnapshotVolumeType {
return []SnapshotVolumeType{
"unknown_volume_type",
"l_ssd",
"b_ssd",
"unified",
}
}
func (enum SnapshotVolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotVolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotVolumeType(SnapshotVolumeType(tmp).String())
return nil
}
type TaskStatus string
const (
TaskStatusPending = TaskStatus("pending")
TaskStatusStarted = TaskStatus("started")
TaskStatusSuccess = TaskStatus("success")
TaskStatusFailure = TaskStatus("failure")
TaskStatusRetry = TaskStatus("retry")
)
func (enum TaskStatus) String() string {
if enum == "" {
// return default value if empty
return "pending"
}
return string(enum)
}
func (enum TaskStatus) Values() []TaskStatus {
return []TaskStatus{
"pending",
"started",
"success",
"failure",
"retry",
}
}
func (enum TaskStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TaskStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TaskStatus(TaskStatus(tmp).String())
return nil
}
type VolumeServerState string
const (
VolumeServerStateAvailable = VolumeServerState("available")
VolumeServerStateSnapshotting = VolumeServerState("snapshotting")
VolumeServerStateFetching = VolumeServerState("fetching")
VolumeServerStateResizing = VolumeServerState("resizing")
VolumeServerStateSaving = VolumeServerState("saving")
VolumeServerStateHotsyncing = VolumeServerState("hotsyncing")
VolumeServerStateError = VolumeServerState("error")
)
func (enum VolumeServerState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum VolumeServerState) Values() []VolumeServerState {
return []VolumeServerState{
"available",
"snapshotting",
"fetching",
"resizing",
"saving",
"hotsyncing",
"error",
}
}
func (enum VolumeServerState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeServerState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeServerState(VolumeServerState(tmp).String())
return nil
}
type VolumeServerVolumeType string
const (
VolumeServerVolumeTypeLSSD = VolumeServerVolumeType("l_ssd")
VolumeServerVolumeTypeBSSD = VolumeServerVolumeType("b_ssd")
VolumeServerVolumeTypeSbsVolume = VolumeServerVolumeType("sbs_volume")
VolumeServerVolumeTypeScratch = VolumeServerVolumeType("scratch")
)
func (enum VolumeServerVolumeType) String() string {
if enum == "" {
// return default value if empty
return "l_ssd"
}
return string(enum)
}
func (enum VolumeServerVolumeType) Values() []VolumeServerVolumeType {
return []VolumeServerVolumeType{
"l_ssd",
"b_ssd",
"sbs_volume",
"scratch",
}
}
func (enum VolumeServerVolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeServerVolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeServerVolumeType(VolumeServerVolumeType(tmp).String())
return nil
}
type VolumeState string
const (
VolumeStateAvailable = VolumeState("available")
VolumeStateSnapshotting = VolumeState("snapshotting")
VolumeStateFetching = VolumeState("fetching")
VolumeStateResizing = VolumeState("resizing")
VolumeStateSaving = VolumeState("saving")
VolumeStateHotsyncing = VolumeState("hotsyncing")
VolumeStateError = VolumeState("error")
)
func (enum VolumeState) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum VolumeState) Values() []VolumeState {
return []VolumeState{
"available",
"snapshotting",
"fetching",
"resizing",
"saving",
"hotsyncing",
"error",
}
}
func (enum VolumeState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeState(VolumeState(tmp).String())
return nil
}
type VolumeVolumeType string
const (
VolumeVolumeTypeLSSD = VolumeVolumeType("l_ssd")
VolumeVolumeTypeBSSD = VolumeVolumeType("b_ssd")
VolumeVolumeTypeUnified = VolumeVolumeType("unified")
VolumeVolumeTypeScratch = VolumeVolumeType("scratch")
VolumeVolumeTypeSbsVolume = VolumeVolumeType("sbs_volume")
VolumeVolumeTypeSbsSnapshot = VolumeVolumeType("sbs_snapshot")
)
func (enum VolumeVolumeType) String() string {
if enum == "" {
// return default value if empty
return "l_ssd"
}
return string(enum)
}
func (enum VolumeVolumeType) Values() []VolumeVolumeType {
return []VolumeVolumeType{
"l_ssd",
"b_ssd",
"unified",
"scratch",
"sbs_volume",
"sbs_snapshot",
}
}
func (enum VolumeVolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeVolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeVolumeType(VolumeVolumeType(tmp).String())
return nil
}
// ServerSummary: server summary.
type ServerSummary struct {
ID string `json:"id"`
Name string `json:"name"`
}
// Bootscript: bootscript.
type Bootscript struct {
// Architecture: default value: unknown_arch
Architecture Arch `json:"architecture"`
Bootcmdargs string `json:"bootcmdargs"`
Default bool `json:"default"`
Dtb string `json:"dtb"`
ID string `json:"id"`
Initrd string `json:"initrd"`
Kernel string `json:"kernel"`
Organization string `json:"organization"`
Public bool `json:"public"`
Title string `json:"title"`
Project string `json:"project"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"zone"`
}
// Volume: volume.
type Volume struct {
// ID: volume unique ID.
ID string `json:"id"`
// Name: volume name.
Name string `json:"name"`
// Deprecated: ExportURI: show the volume NBD export URI.
ExportURI *string `json:"export_uri"`
// Size: volume disk size.
Size scw.Size `json:"size"`
// VolumeType: volume type.
// Default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type"`
// CreationDate: volume creation date.
CreationDate *time.Time `json:"creation_date"`
// ModificationDate: volume modification date.
ModificationDate *time.Time `json:"modification_date"`
// Organization: volume Organization ID.
Organization string `json:"organization"`
// Project: volume Project ID.
Project string `json:"project"`
// Tags: volume tags.
Tags []string `json:"tags"`
// Server: instance attached to the volume.
Server *ServerSummary `json:"server"`
// State: volume state.
// Default value: available
State VolumeState `json:"state"`
// Zone: zone in which the volume is located.
Zone scw.Zone `json:"zone"`
}
// VolumeSummary: volume summary.
type VolumeSummary struct {
ID string `json:"id"`
Name string `json:"name"`
Size scw.Size `json:"size"`
// VolumeType: default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type"`
}
// ServerTypeNetworkInterface: server type network interface.
type ServerTypeNetworkInterface struct {
// InternalBandwidth: maximum internal bandwidth in bits per seconds.
InternalBandwidth *uint64 `json:"internal_bandwidth"`
// InternetBandwidth: maximum internet bandwidth in bits per seconds.
InternetBandwidth *uint64 `json:"internet_bandwidth"`
}
// ServerTypeVolumeConstraintSizes: server type volume constraint sizes.
type ServerTypeVolumeConstraintSizes struct {
// MinSize: minimum volume size in bytes.
MinSize scw.Size `json:"min_size"`
// MaxSize: maximum volume size in bytes.
MaxSize scw.Size `json:"max_size"`
}
// Image: image.
type Image struct {
ID string `json:"id"`
Name string `json:"name"`
// Arch: default value: unknown_arch
Arch Arch `json:"arch"`
CreationDate *time.Time `json:"creation_date"`
ModificationDate *time.Time `json:"modification_date"`
// Deprecated
DefaultBootscript *Bootscript `json:"default_bootscript"`
ExtraVolumes map[string]*Volume `json:"extra_volumes"`
FromServer string `json:"from_server"`
Organization string `json:"organization"`
Public bool `json:"public"`
RootVolume *VolumeSummary `json:"root_volume"`
// State: default value: available
State ImageState `json:"state"`
Project string `json:"project"`
Tags []string `json:"tags"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"zone"`
}
// PlacementGroup: placement group.
type PlacementGroup struct {
// ID: placement group unique ID.
ID string `json:"id"`
// Name: placement group name.
Name string `json:"name"`
// Organization: placement group Organization ID.
Organization string `json:"organization"`
// Project: placement group Project ID.
Project string `json:"project"`
// Tags: placement group tags.
Tags []string `json:"tags"`
// PolicyMode: select the failure mode when the placement cannot be respected, either optional or enforced.
// Default value: optional
PolicyMode PlacementGroupPolicyMode `json:"policy_mode"`
// PolicyType: select the behavior of the placement group, either low_latency (group) or max_availability (spread).
// Default value: max_availability
PolicyType PlacementGroupPolicyType `json:"policy_type"`
// PolicyRespected: in the server endpoints the value is always false as it is deprecated.
// In the placement group endpoints the value is correct.
PolicyRespected bool `json:"policy_respected"`
// Zone: zone in which the placement group is located.
Zone scw.Zone `json:"zone"`
}
// PrivateNIC: private nic.
type PrivateNIC struct {
// ID: private NIC unique ID.
ID string `json:"id"`
// ServerID: instance to which the private NIC is attached.
ServerID string `json:"server_id"`
// PrivateNetworkID: private Network the private NIC is attached to.
PrivateNetworkID string `json:"private_network_id"`
// MacAddress: private NIC MAC address.
MacAddress string `json:"mac_address"`
// State: private NIC state.
// Default value: available
State PrivateNICState `json:"state"`
// Tags: private NIC tags.
Tags []string `json:"tags"`
}
// SecurityGroupSummary: security group summary.
type SecurityGroupSummary struct {
ID string `json:"id"`
Name string `json:"name"`
}
// ServerIP: server ip.
type ServerIP struct {
// ID: unique ID of the IP address.
ID string `json:"id"`
// Address: instance's public IP-Address.
Address net.IP `json:"address"`
// Gateway: gateway's IP address.
Gateway net.IP `json:"gateway"`
// Netmask: cIDR netmask.
Netmask string `json:"netmask"`
// Family: IP address family (inet or inet6).
// Default value: inet
Family ServerIPIPFamily `json:"family"`
// Dynamic: true if the IP address is dynamic.
Dynamic bool `json:"dynamic"`
// ProvisioningMode: information about this address provisioning mode.
// Default value: manual
ProvisioningMode ServerIPProvisioningMode `json:"provisioning_mode"`
// Tags: tags associated with the IP.
Tags []string `json:"tags"`
// IpamID: the ip_id of an IPAM ip if the ip is created from IPAM, null if not.
IpamID string `json:"ipam_id"`
// State: IP address state.
// Default value: unknown_state
State ServerIPState `json:"state"`
}
// ServerIPv6: server i pv6.
type ServerIPv6 struct {
// Address: instance IPv6 IP-Address.
Address net.IP `json:"address"`
// Gateway: iPv6 IP-addresses gateway.
Gateway net.IP `json:"gateway"`
// Netmask: iPv6 IP-addresses CIDR netmask.
Netmask string `json:"netmask"`
}
// ServerLocation: server location.
type ServerLocation struct {
ClusterID string `json:"cluster_id"`
HypervisorID string `json:"hypervisor_id"`
NodeID string `json:"node_id"`
PlatformID string `json:"platform_id"`
ZoneID string `json:"zone_id"`
}
// ServerMaintenance: server maintenance.
type ServerMaintenance struct {
Reason string `json:"reason"`
StartDate *time.Time `json:"start_date"`
}
// VolumeServer: volume server.
type VolumeServer struct {
ID string `json:"id"`
Name *string `json:"name"`
// Deprecated
ExportURI *string `json:"export_uri"`
Organization *string `json:"organization"`
Server *ServerSummary `json:"server"`
Size *scw.Size `json:"size"`
// VolumeType: default value: l_ssd
VolumeType VolumeServerVolumeType `json:"volume_type"`
CreationDate *time.Time `json:"creation_date"`
ModificationDate *time.Time `json:"modification_date"`
// State: default value: available
State *VolumeServerState `json:"state"`
Project *string `json:"project"`
Boot bool `json:"boot"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"zone"`
}
// SnapshotBaseVolume: snapshot base volume.
type SnapshotBaseVolume struct {
// ID: volume ID on which the snapshot is based.
ID string `json:"id"`
// Name: volume name on which the snapshot is based on.
Name string `json:"name"`
}
// ServerTypeCapabilities: server type capabilities.
type ServerTypeCapabilities struct {
// BlockStorage: defines whether the Instance supports block storage.
BlockStorage *bool `json:"block_storage"`
// BootTypes: list of supported boot types.
BootTypes []BootType `json:"boot_types"`
}
// ServerTypeNetwork: server type network.
type ServerTypeNetwork struct {
// Interfaces: list of available network interfaces.
Interfaces []*ServerTypeNetworkInterface `json:"interfaces"`
// SumInternalBandwidth: total maximum internal bandwidth in bits per seconds.
SumInternalBandwidth *uint64 `json:"sum_internal_bandwidth"`
// SumInternetBandwidth: total maximum internet bandwidth in bits per seconds.
SumInternetBandwidth *uint64 `json:"sum_internet_bandwidth"`
// IPv6Support: true if IPv6 is enabled.
IPv6Support bool `json:"ipv6_support"`
}
// ServerTypeVolumeConstraintsByType: server type volume constraints by type.
type ServerTypeVolumeConstraintsByType struct {
// LSSD: local SSD volumes.
LSSD *ServerTypeVolumeConstraintSizes `json:"l_ssd"`
}
// VolumeTypeCapabilities: volume type capabilities.
type VolumeTypeCapabilities struct {
Snapshot bool `json:"snapshot"`
}
// VolumeTypeConstraints: volume type constraints.
type VolumeTypeConstraints struct {
Min scw.Size `json:"min"`
Max scw.Size `json:"max"`
}
// Server: server.
type Server struct {
// ID: instance unique ID.
ID string `json:"id"`
// Name: instance name.
Name string `json:"name"`
// Organization: instance Organization ID.
Organization string `json:"organization"`
// Project: instance Project ID.
Project string `json:"project"`
// AllowedActions: list of allowed actions on the Instance.
AllowedActions []ServerAction `json:"allowed_actions"`
// Tags: tags associated with the Instance.
Tags []string `json:"tags"`
// CommercialType: instance commercial type (eg. GP1-M).
CommercialType string `json:"commercial_type"`
// CreationDate: instance creation date.
CreationDate *time.Time `json:"creation_date"`
// DynamicIPRequired: true if a dynamic IPv4 is required.
DynamicIPRequired bool `json:"dynamic_ip_required"`
// Deprecated: RoutedIPEnabled: true to configure the instance so it uses the routed IP mode. Use of `routed_ip_enabled` as `False` is deprecated.
RoutedIPEnabled *bool `json:"routed_ip_enabled"`
// Deprecated: EnableIPv6: true if IPv6 is enabled (deprecated and always `False` when `routed_ip_enabled` is `True`).
EnableIPv6 *bool `json:"enable_ipv6"`
// Hostname: instance host name.
Hostname string `json:"hostname"`
// Image: information about the Instance image.
Image *Image `json:"image"`
// Protected: defines whether the Instance protection option is activated.
Protected bool `json:"protected"`
// PrivateIP: private IP address of the Instance (deprecated and always `null` when `routed_ip_enabled` is `True`).
PrivateIP *string `json:"private_ip"`
// Deprecated: PublicIP: information about the public IP (deprecated in favor of `public_ips`).
PublicIP *ServerIP `json:"public_ip"`
// PublicIPs: information about all the public IPs attached to the server.
PublicIPs []*ServerIP `json:"public_ips"`
// MacAddress: the server's MAC address.
MacAddress string `json:"mac_address"`
// ModificationDate: instance modification date.
ModificationDate *time.Time `json:"modification_date"`
// State: instance state.
// Default value: running
State ServerState `json:"state"`
// Location: instance location.
Location *ServerLocation `json:"location"`
// Deprecated: IPv6: instance IPv6 address (deprecated when `routed_ip_enabled` is `True`).
IPv6 *ServerIPv6 `json:"ipv6"`
// BootType: instance boot type.
// Default value: local
BootType BootType `json:"boot_type"`
// Volumes: instance volumes.
Volumes map[string]*VolumeServer `json:"volumes"`
// SecurityGroup: instance security group.
SecurityGroup *SecurityGroupSummary `json:"security_group"`
// Maintenances: instance planned maintenance.
Maintenances []*ServerMaintenance `json:"maintenances"`
// StateDetail: detailed information about the Instance state.
StateDetail string `json:"state_detail"`
// Arch: instance architecture.
// Default value: unknown_arch
Arch Arch `json:"arch"`
// PlacementGroup: instance placement group.
PlacementGroup *PlacementGroup `json:"placement_group"`
// PrivateNics: instance private NICs.
PrivateNics []*PrivateNIC `json:"private_nics"`
// Zone: zone in which the Instance is located.
Zone scw.Zone `json:"zone"`
// AdminPasswordEncryptionSSHKeyID: the public_key value of this key is used to encrypt the admin password. When set to an empty string, reset this value and admin_password_encrypted_value to an empty string so a new password may be generated.
AdminPasswordEncryptionSSHKeyID *string `json:"admin_password_encryption_ssh_key_id"`
// AdminPasswordEncryptedValue: this value is reset when admin_password_encryption_ssh_key_id is set to an empty string.
AdminPasswordEncryptedValue *string `json:"admin_password_encrypted_value"`
}
// IP: ip.
type IP struct {
ID string `json:"id"`
Address net.IP `json:"address"`
Reverse *string `json:"reverse"`
Server *ServerSummary `json:"server"`
Organization string `json:"organization"`
Tags []string `json:"tags"`
Project string `json:"project"`
// Type: default value: unknown_iptype
Type IPType `json:"type"`
// State: default value: unknown_state
State IPState `json:"state"`
Prefix scw.IPNet `json:"prefix"`
IpamID string `json:"ipam_id"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"zone"`
}
// VolumeTemplate: volume template.
type VolumeTemplate struct {
// ID: UUID of the volume.
ID string `json:"id,omitempty"`
// Name: name of the volume.
Name string `json:"name,omitempty"`
// Size: disk size of the volume, must be a multiple of 512.
Size scw.Size `json:"size,omitempty"`
// VolumeType: type of the volume.
// Default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type,omitempty"`
// Deprecated: Organization: organization ID of the volume.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID of the volume.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
}
// SecurityGroup: security group.
type SecurityGroup struct {
// ID: security group unique ID.
ID string `json:"id"`
// Name: security group name.
Name string `json:"name"`
// Description: security group description.
Description string `json:"description"`
// EnableDefaultSecurity: true if SMTP is blocked on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable.
EnableDefaultSecurity bool `json:"enable_default_security"`
// InboundDefaultPolicy: default inbound policy.
// Default value: unknown_policy
InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"`
// OutboundDefaultPolicy: default outbound policy.
// Default value: unknown_policy
OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"`
// Organization: security group Organization ID.
Organization string `json:"organization"`
// Project: security group Project ID.
Project string `json:"project"`
// Tags: security group tags.
Tags []string `json:"tags"`
// Deprecated: OrganizationDefault: true if it is your default security group for this Organization ID.
OrganizationDefault *bool `json:"organization_default"`
// ProjectDefault: true if it is your default security group for this Project ID.
ProjectDefault bool `json:"project_default"`
// CreationDate: security group creation date.
CreationDate *time.Time `json:"creation_date"`
// ModificationDate: security group modification date.
ModificationDate *time.Time `json:"modification_date"`
// Servers: list of Instances attached to this security group.
Servers []*ServerSummary `json:"servers"`
// Stateful: defines whether the security group is stateful.
Stateful bool `json:"stateful"`
// State: security group state.
// Default value: available
State SecurityGroupState `json:"state"`
// Zone: zone in which the security group is located.
Zone scw.Zone `json:"zone"`
}
// SecurityGroupRule: security group rule.
type SecurityGroupRule struct {
ID string `json:"id"`
// Protocol: default value: unknown_protocol
Protocol SecurityGroupRuleProtocol `json:"protocol"`
// Direction: default value: unknown_direction
Direction SecurityGroupRuleDirection `json:"direction"`
// Action: default value: unknown_action
Action SecurityGroupRuleAction `json:"action"`
IPRange scw.IPNet `json:"ip_range"`
DestPortFrom *uint32 `json:"dest_port_from"`
DestPortTo *uint32 `json:"dest_port_to"`
Position uint32 `json:"position"`
Editable bool `json:"editable"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"zone"`
}
// VolumeServerTemplate: volume server template.
type VolumeServerTemplate struct {
// ID: UUID of the volume.
ID *string `json:"id,omitempty"`
// Boot: force the Instance to boot on this volume.
Boot *bool `json:"boot,omitempty"`
// Name: name of the volume.
Name *string `json:"name,omitempty"`
// Size: disk size of the volume, must be a multiple of 512.
Size *scw.Size `json:"size,omitempty"`
// VolumeType: type of the volume.
// Default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type,omitempty"`
// BaseSnapshot: ID of the snapshot on which this volume will be based.
BaseSnapshot *string `json:"base_snapshot,omitempty"`
// Organization: organization ID of the volume.
Organization *string `json:"organization,omitempty"`
// Project: project ID of the volume.
Project *string `json:"project,omitempty"`
}
// Snapshot: snapshot.
type Snapshot struct {
// ID: snapshot ID.
ID string `json:"id"`
// Name: snapshot name.
Name string `json:"name"`
// Organization: snapshot Organization ID.
Organization string `json:"organization"`
// Project: snapshot Project ID.
Project string `json:"project"`
// Tags: snapshot tags.
Tags []string `json:"tags"`
// VolumeType: snapshot volume type.
// Default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type"`
// Size: snapshot size.
Size scw.Size `json:"size"`
// State: snapshot state.
// Default value: available
State SnapshotState `json:"state"`
// BaseVolume: volume on which the snapshot is based on.
BaseVolume *SnapshotBaseVolume `json:"base_volume"`
// CreationDate: snapshot creation date.
CreationDate *time.Time `json:"creation_date"`
// ModificationDate: snapshot modification date.
ModificationDate *time.Time `json:"modification_date"`
// Zone: snapshot zone.
Zone scw.Zone `json:"zone"`
// ErrorReason: reason for the failed snapshot import.
ErrorReason *string `json:"error_reason"`
}
// Task: task.
type Task struct {
// ID: unique ID of the task.
ID string `json:"id"`
// Description: description of the task.
Description string `json:"description"`
// Progress: progress of the task in percent.
Progress int32 `json:"progress"`
// StartedAt: task start date.
StartedAt *time.Time `json:"started_at"`
// TerminatedAt: task end date.
TerminatedAt *time.Time `json:"terminated_at"`
// Status: task status.
// Default value: pending
Status TaskStatus `json:"status"`
HrefFrom string `json:"href_from"`
HrefResult string `json:"href_result"`
// Zone: zone in which the task is excecuted.
Zone scw.Zone `json:"zone"`
}
// Dashboard: dashboard.
type Dashboard struct {
VolumesCount uint32 `json:"volumes_count"`
RunningServersCount uint32 `json:"running_servers_count"`
ServersByTypes map[string]uint32 `json:"servers_by_types"`
ImagesCount uint32 `json:"images_count"`
SnapshotsCount uint32 `json:"snapshots_count"`
ServersCount uint32 `json:"servers_count"`
IPsCount uint32 `json:"ips_count"`
SecurityGroupsCount uint32 `json:"security_groups_count"`
IPsUnused uint32 `json:"ips_unused"`
VolumesLSSDCount uint32 `json:"volumes_l_ssd_count"`
// Deprecated
VolumesBSSDCount *uint32 `json:"volumes_b_ssd_count"`
VolumesLSSDTotalSize scw.Size `json:"volumes_l_ssd_total_size"`
// Deprecated
VolumesBSSDTotalSize *scw.Size `json:"volumes_b_ssd_total_size"`
PrivateNicsCount uint32 `json:"private_nics_count"`
PlacementGroupsCount uint32 `json:"placement_groups_count"`
}
// PlacementGroupServer: placement group server.
type PlacementGroupServer struct {
// ID: instance UUID.
ID string `json:"id"`
// Name: instance name.
Name string `json:"name"`
// PolicyRespected: defines whether the placement group policy is respected (either 1 or 0).
PolicyRespected bool `json:"policy_respected"`
}
// GetServerTypesAvailabilityResponseAvailability: get server types availability response availability.
type GetServerTypesAvailabilityResponseAvailability struct {
// Availability: default value: available
Availability ServerTypesAvailability `json:"availability"`
}
// ServerType: server type.
type ServerType struct {
// Deprecated: MonthlyPrice: estimated monthly price, for a 30 days month, in Euro.
MonthlyPrice *float32 `json:"monthly_price"`
// HourlyPrice: hourly price in Euro.
HourlyPrice float32 `json:"hourly_price"`
// AltNames: alternative Instance name, if any.
AltNames []string `json:"alt_names"`
// PerVolumeConstraint: additional volume constraints.
PerVolumeConstraint *ServerTypeVolumeConstraintsByType `json:"per_volume_constraint"`
// VolumesConstraint: initial volume constraints.
VolumesConstraint *ServerTypeVolumeConstraintSizes `json:"volumes_constraint"`
// Ncpus: number of CPU.
Ncpus uint32 `json:"ncpus"`
// Gpu: number of GPU.
Gpu *uint64 `json:"gpu"`
// RAM: available RAM in bytes.
RAM uint64 `json:"ram"`
// Arch: CPU architecture.
// Default value: unknown_arch
Arch Arch `json:"arch"`
// Baremetal: true if it is a baremetal Instance.
Baremetal bool `json:"baremetal"`
// Network: network available for the Instance.
Network *ServerTypeNetwork `json:"network"`
// Capabilities: capabilities.
Capabilities *ServerTypeCapabilities `json:"capabilities"`
// ScratchStorageMaxSize: maximum available scratch storage.
ScratchStorageMaxSize *scw.Size `json:"scratch_storage_max_size"`
// BlockBandwidth: the maximum bandwidth allocated to block storage access (in bytes per second).
BlockBandwidth *uint64 `json:"block_bandwidth"`
}
// VolumeType: volume type.
type VolumeType struct {
DisplayName string `json:"display_name"`
Capabilities *VolumeTypeCapabilities `json:"capabilities"`
Constraints *VolumeTypeConstraints `json:"constraints"`
}
// ServerActionRequestVolumeBackupTemplate: server action request volume backup template.
type ServerActionRequestVolumeBackupTemplate struct {
// VolumeType: overrides the `volume_type` of the snapshot for this volume.
// If omitted, the volume type of the original volume will be used.
// Default value: unknown_volume_type
VolumeType SnapshotVolumeType `json:"volume_type,omitempty"`
}
// SetSecurityGroupRulesRequestRule: set security group rules request rule.
type SetSecurityGroupRulesRequestRule struct {
// ID: UUID of the security rule to update. If no value is provided, a new rule will be created.
ID *string `json:"id"`
// Action: action to apply when the rule matches a packet.
// Default value: unknown_action
Action SecurityGroupRuleAction `json:"action"`
// Protocol: protocol family this rule applies to.
// Default value: unknown_protocol
Protocol SecurityGroupRuleProtocol `json:"protocol"`
// Direction: direction the rule applies to.
// Default value: unknown_direction
Direction SecurityGroupRuleDirection `json:"direction"`
// IPRange: range of IP addresses these rules apply to.
IPRange scw.IPNet `json:"ip_range"`
// DestPortFrom: beginning of the range of ports this rule applies to (inclusive). This value will be set to null if protocol is ICMP or ANY.
DestPortFrom *uint32 `json:"dest_port_from"`
// DestPortTo: end of the range of ports this rule applies to (inclusive). This value will be set to null if protocol is ICMP or ANY, or if it is equal to dest_port_from.
DestPortTo *uint32 `json:"dest_port_to"`
// Position: position of this rule in the security group rules list. If several rules are passed with the same position, the resulting order is undefined.
Position uint32 `json:"position"`
// Editable: indicates if this rule is editable. Rules with the value false will be ignored.
Editable *bool `json:"editable"`
// Zone: zone of the rule. This field is ignored.
Zone *scw.Zone `json:"zone"`
}
// NullableStringValue: nullable string value.
type NullableStringValue struct {
Null bool `json:"null,omitempty"`
Value string `json:"value,omitempty"`
}
// VolumeImageUpdateTemplate: volume image update template.
type VolumeImageUpdateTemplate struct {
// ID: UUID of the snapshot.
ID string `json:"id,omitempty"`
}
// SecurityGroupTemplate: security group template.
type SecurityGroupTemplate struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
// ApplyBlockMigrationRequest: apply block migration request.
type ApplyBlockMigrationRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: the volume to migrate, along with potentially other resources, according to the migration plan generated with a call to the [Get a volume or snapshot's migration plan](#path-volumes-get-a-volume-or-snapshots-migration-plan) endpoint.
// Precisely one of VolumeID, SnapshotID must be set.
VolumeID *string `json:"volume_id,omitempty"`
// SnapshotID: the snapshot to migrate, along with potentially other resources, according to the migration plan generated with a call to the [Get a volume or snapshot's migration plan](#path-volumes-get-a-volume-or-snapshots-migration-plan) endpoint.
// Precisely one of VolumeID, SnapshotID must be set.
SnapshotID *string `json:"snapshot_id,omitempty"`
// ValidationKey: a value to be retrieved from a call to the [Get a volume or snapshot's migration plan](#path-volumes-get-a-volume-or-snapshots-migration-plan) endpoint, to confirm that the volume and/or snapshots specified in said plan should be migrated.
ValidationKey string `json:"validation_key,omitempty"`
}
// AttachServerVolumeRequest: attach server volume request.
type AttachServerVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
VolumeID string `json:"volume_id,omitempty"`
// VolumeType: default value: unknown_volume_type
VolumeType AttachServerVolumeRequestVolumeType `json:"volume_type,omitempty"`
Boot *bool `json:"boot,omitempty"`
}
// AttachServerVolumeResponse: attach server volume response.
type AttachServerVolumeResponse struct {
Server *Server `json:"server"`
}
// CheckBlockMigrationOrganizationQuotasRequest: check block migration organization quotas request.
type CheckBlockMigrationOrganizationQuotasRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
Organization string `json:"organization,omitempty"`
}
// CreateIPRequest: create ip request.
type CreateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Deprecated: Organization: organization ID in which the IP is reserved.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID in which the IP is reserved.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: tags of the IP.
Tags []string `json:"tags,omitempty"`
// Server: UUID of the Instance you want to attach the IP to.
Server *string `json:"server,omitempty"`
// Type: IP type to reserve (either 'routed_ipv4' or 'routed_ipv6').
// Default value: unknown_iptype
Type IPType `json:"type,omitempty"`
}
// CreateIPResponse: create ip response.
type CreateIPResponse struct {
IP *IP `json:"ip"`
}
// CreateImageRequest: create image request.
type CreateImageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the image.
Name string `json:"name,omitempty"`
// RootVolume: UUID of the snapshot.
RootVolume string `json:"root_volume,omitempty"`
// Arch: architecture of the image.
// Default value: unknown_arch
Arch Arch `json:"arch,omitempty"`
// ExtraVolumes: additional volumes of the image.
ExtraVolumes map[string]*VolumeTemplate `json:"extra_volumes,omitempty"`
// Deprecated: Organization: organization ID of the image.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID of the image.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: tags of the image.
Tags []string `json:"tags,omitempty"`
// Public: true to create a public image.
Public *bool `json:"public,omitempty"`
}
// CreateImageResponse: create image response.
type CreateImageResponse struct {
Image *Image `json:"image"`
}
// CreatePlacementGroupRequest: create placement group request.
type CreatePlacementGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the placement group.
Name string `json:"name,omitempty"`
// Deprecated: Organization: organization ID of the placement group.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID of the placement group.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: tags of the placement group.
Tags []string `json:"tags,omitempty"`
// PolicyMode: operating mode of the placement group.
// Default value: optional
PolicyMode PlacementGroupPolicyMode `json:"policy_mode,omitempty"`
// PolicyType: policy type of the placement group.
// Default value: max_availability
PolicyType PlacementGroupPolicyType `json:"policy_type,omitempty"`
}
// CreatePlacementGroupResponse: create placement group response.
type CreatePlacementGroupResponse struct {
PlacementGroup *PlacementGroup `json:"placement_group"`
}
// CreatePrivateNICRequest: create private nic request.
type CreatePrivateNICRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance the private NIC will be attached to.
ServerID string `json:"-"`
// PrivateNetworkID: UUID of the private network where the private NIC will be attached.
PrivateNetworkID string `json:"private_network_id,omitempty"`
// Tags: private NIC tags.
Tags []string `json:"tags,omitempty"`
// Deprecated: IPIDs: ip_ids defined from IPAM.
IPIDs *[]string `json:"ip_ids,omitempty"`
// IpamIPIDs: UUID of IPAM ips, to be attached to the instance in the requested private network.
IpamIPIDs []string `json:"ipam_ip_ids,omitempty"`
}
// CreatePrivateNICResponse: create private nic response.
type CreatePrivateNICResponse struct {
PrivateNic *PrivateNIC `json:"private_nic"`
}
// CreateSecurityGroupRequest: create security group request.
type CreateSecurityGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the security group.
Name string `json:"name,omitempty"`
// Description: description of the security group.
Description string `json:"description,omitempty"`
// Deprecated: Organization: organization ID the security group belongs to.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID the security group belong to.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: tags of the security group.
Tags []string `json:"tags,omitempty"`
// Deprecated: OrganizationDefault: defines whether this security group becomes the default security group for new Instances.
// Precisely one of OrganizationDefault, ProjectDefault must be set.
OrganizationDefault *bool `json:"organization_default,omitempty"`
// ProjectDefault: whether this security group becomes the default security group for new Instances.
// Precisely one of OrganizationDefault, ProjectDefault must be set.
ProjectDefault *bool `json:"project_default,omitempty"`
// Stateful: whether the security group is stateful or not.
Stateful bool `json:"stateful,omitempty"`
// InboundDefaultPolicy: default policy for inbound rules.
// Default value: unknown_policy
InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy,omitempty"`
// OutboundDefaultPolicy: default policy for outbound rules.
// Default value: unknown_policy
OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy,omitempty"`
// EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable.
EnableDefaultSecurity *bool `json:"enable_default_security,omitempty"`
}
// CreateSecurityGroupResponse: create security group response.
type CreateSecurityGroupResponse struct {
SecurityGroup *SecurityGroup `json:"security_group"`
}
// CreateSecurityGroupRuleRequest: create security group rule request.
type CreateSecurityGroupRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group.
SecurityGroupID string `json:"-"`
// Protocol: default value: unknown_protocol
Protocol SecurityGroupRuleProtocol `json:"protocol,omitempty"`
// Direction: default value: unknown_direction
Direction SecurityGroupRuleDirection `json:"direction,omitempty"`
// Action: default value: unknown_action
Action SecurityGroupRuleAction `json:"action,omitempty"`
IPRange scw.IPNet `json:"ip_range,omitempty"`
// DestPortFrom: beginning of the range of ports to apply this rule to (inclusive).
DestPortFrom *uint32 `json:"dest_port_from,omitempty"`
// DestPortTo: end of the range of ports to apply this rule to (inclusive).
DestPortTo *uint32 `json:"dest_port_to,omitempty"`
// Position: position of this rule in the security group rules list.
Position uint32 `json:"position,omitempty"`
// Editable: indicates if this rule is editable (will be ignored).
Editable bool `json:"editable,omitempty"`
}
// CreateSecurityGroupRuleResponse: create security group rule response.
type CreateSecurityGroupRuleResponse struct {
Rule *SecurityGroupRule `json:"rule"`
}
// CreateServerRequest: create server request.
type CreateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: instance name.
Name string `json:"name,omitempty"`
// DynamicIPRequired: define if a dynamic IPv4 is required for the Instance.
DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"`
// Deprecated: RoutedIPEnabled: if true, configure the Instance so it uses the new routed IP mode.
RoutedIPEnabled *bool `json:"routed_ip_enabled,omitempty"`
// CommercialType: define the Instance commercial type (i.e. GP1-S).
CommercialType string `json:"commercial_type,omitempty"`
// Image: instance image ID or label.
Image *string `json:"image,omitempty"`
// Volumes: volumes attached to the server.
Volumes map[string]*VolumeServerTemplate `json:"volumes,omitempty"`
// Deprecated: EnableIPv6: true if IPv6 is enabled on the server (deprecated and always `False` when `routed_ip_enabled` is `True`).
EnableIPv6 *bool `json:"enable_ipv6,omitempty"`
// Deprecated: PublicIP: ID of the reserved IP to attach to the Instance.
PublicIP *string `json:"public_ip,omitempty"`
// PublicIPs: a list of reserved IP IDs to attach to the Instance.
PublicIPs *[]string `json:"public_ips,omitempty"`
// BootType: boot type to use.
// Default value: local
BootType *BootType `json:"boot_type,omitempty"`
// Deprecated: Organization: instance Organization ID.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: instance Project ID.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: instance tags.
Tags []string `json:"tags,omitempty"`
// SecurityGroup: security group ID.
SecurityGroup *string `json:"security_group,omitempty"`
// PlacementGroup: placement group ID if Instance must be part of a placement group.
PlacementGroup *string `json:"placement_group,omitempty"`
// AdminPasswordEncryptionSSHKeyID: the public_key value of this key is used to encrypt the admin password.
AdminPasswordEncryptionSSHKeyID *string `json:"admin_password_encryption_ssh_key_id,omitempty"`
}
// CreateServerResponse: create server response.
type CreateServerResponse struct {
Server *Server `json:"server"`
}
// CreateSnapshotRequest: create snapshot request.
type CreateSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the snapshot.
Name string `json:"name,omitempty"`
// VolumeID: UUID of the volume.
VolumeID *string `json:"volume_id,omitempty"`
// Tags: tags of the snapshot.
Tags *[]string `json:"tags,omitempty"`
// Deprecated: Organization: organization ID of the snapshot.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: project ID of the snapshot.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// VolumeType: overrides the volume_type of the snapshot.
// If omitted, the volume type of the original volume will be used.
// Default value: unknown_volume_type
VolumeType SnapshotVolumeType `json:"volume_type,omitempty"`
// Bucket: bucket name for snapshot imports.
Bucket *string `json:"bucket,omitempty"`
// Key: object key for snapshot imports.
Key *string `json:"key,omitempty"`
// Size: imported snapshot size, must be a multiple of 512.
Size *scw.Size `json:"size,omitempty"`
}
// CreateSnapshotResponse: create snapshot response.
type CreateSnapshotResponse struct {
Snapshot *Snapshot `json:"snapshot"`
Task *Task `json:"task"`
}
// CreateVolumeRequest: create volume request.
type CreateVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: volume name.
Name string `json:"name,omitempty"`
// Deprecated: Organization: volume Organization ID.
// Precisely one of Project, Organization must be set.
Organization *string `json:"organization,omitempty"`
// Project: volume Project ID.
// Precisely one of Project, Organization must be set.
Project *string `json:"project,omitempty"`
// Tags: volume tags.
Tags []string `json:"tags,omitempty"`
// VolumeType: volume type.
// Default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type,omitempty"`
// Size: volume disk size, must be a multiple of 512.
// Precisely one of Size, BaseSnapshot must be set.
Size *scw.Size `json:"size,omitempty"`
// BaseSnapshot: ID of the snapshot on which this volume will be based.
// Precisely one of Size, BaseSnapshot must be set.
BaseSnapshot *string `json:"base_snapshot,omitempty"`
}
// CreateVolumeResponse: create volume response.
type CreateVolumeResponse struct {
Volume *Volume `json:"volume"`
}
// DeleteIPRequest: delete ip request.
type DeleteIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IP: ID or address of the IP to delete.
IP string `json:"-"`
}
// DeleteImageRequest: delete image request.
type DeleteImageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ImageID: UUID of the image you want to delete.
ImageID string `json:"-"`
}
// DeletePlacementGroupRequest: delete placement group request.
type DeletePlacementGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group you want to delete.
PlacementGroupID string `json:"-"`
}
// DeletePrivateNICRequest: delete private nic request.
type DeletePrivateNICRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: instance to which the private NIC is attached.
ServerID string `json:"-"`
// PrivateNicID: private NIC unique ID.
PrivateNicID string `json:"-"`
}
// DeleteSecurityGroupRequest: delete security group request.
type DeleteSecurityGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group you want to delete.
SecurityGroupID string `json:"-"`
}
// DeleteSecurityGroupRuleRequest: delete security group rule request.
type DeleteSecurityGroupRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
SecurityGroupID string `json:"-"`
SecurityGroupRuleID string `json:"-"`
}
// DeleteServerRequest: delete server request.
type DeleteServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
}
// DeleteServerUserDataRequest: delete server user data request.
type DeleteServerUserDataRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance.
ServerID string `json:"-"`
// Key: key of the user data to delete.
Key string `json:"-"`
}
// DeleteSnapshotRequest: delete snapshot request.
type DeleteSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot you want to delete.
SnapshotID string `json:"-"`
}
// DeleteVolumeRequest: delete volume request.
type DeleteVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume you want to delete.
VolumeID string `json:"-"`
}
// DetachServerVolumeRequest: detach server volume request.
type DetachServerVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
VolumeID string `json:"volume_id,omitempty"`
}
// DetachServerVolumeResponse: detach server volume response.
type DetachServerVolumeResponse struct {
Server *Server `json:"server"`
}
// ExportSnapshotRequest: export snapshot request.
type ExportSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: snapshot ID.
SnapshotID string `json:"-"`
// Bucket: object Storage bucket name.
Bucket string `json:"bucket,omitempty"`
// Key: object key.
Key string `json:"key,omitempty"`
}
// ExportSnapshotResponse: export snapshot response.
type ExportSnapshotResponse struct {
Task *Task `json:"task"`
}
// GetDashboardRequest: get dashboard request.
type GetDashboardRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
Organization *string `json:"-"`
Project *string `json:"-"`
}
// GetDashboardResponse: get dashboard response.
type GetDashboardResponse struct {
Dashboard *Dashboard `json:"dashboard"`
}
// GetIPRequest: get ip request.
type GetIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IP: IP ID or address to get.
IP string `json:"-"`
}
// GetIPResponse: get ip response.
type GetIPResponse struct {
IP *IP `json:"ip"`
}
// GetImageRequest: get image request.
type GetImageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ImageID: UUID of the image you want to get.
ImageID string `json:"-"`
}
// GetImageResponse: get image response.
type GetImageResponse struct {
Image *Image `json:"image"`
}
// GetPlacementGroupRequest: get placement group request.
type GetPlacementGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group you want to get.
PlacementGroupID string `json:"-"`
}
// GetPlacementGroupResponse: get placement group response.
type GetPlacementGroupResponse struct {
PlacementGroup *PlacementGroup `json:"placement_group"`
}
// GetPlacementGroupServersRequest: get placement group servers request.
type GetPlacementGroupServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group you want to get.
PlacementGroupID string `json:"-"`
}
// GetPlacementGroupServersResponse: get placement group servers response.
type GetPlacementGroupServersResponse struct {
// Servers: instances attached to the placement group.
Servers []*PlacementGroupServer `json:"servers"`
}
// GetPrivateNICRequest: get private nic request.
type GetPrivateNICRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: instance to which the private NIC is attached.
ServerID string `json:"-"`
// PrivateNicID: private NIC unique ID.
PrivateNicID string `json:"-"`
}
// GetPrivateNICResponse: get private nic response.
type GetPrivateNICResponse struct {
PrivateNic *PrivateNIC `json:"private_nic"`
}
// GetSecurityGroupRequest: get security group request.
type GetSecurityGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group you want to get.
SecurityGroupID string `json:"-"`
}
// GetSecurityGroupResponse: get security group response.
type GetSecurityGroupResponse struct {
SecurityGroup *SecurityGroup `json:"security_group"`
}
// GetSecurityGroupRuleRequest: get security group rule request.
type GetSecurityGroupRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
SecurityGroupID string `json:"-"`
SecurityGroupRuleID string `json:"-"`
}
// GetSecurityGroupRuleResponse: get security group rule response.
type GetSecurityGroupRuleResponse struct {
Rule *SecurityGroupRule `json:"rule"`
}
// GetServerRequest: get server request.
type GetServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance you want to get.
ServerID string `json:"-"`
}
// GetServerResponse: get server response.
type GetServerResponse struct {
Server *Server `json:"server"`
}
// GetServerTypesAvailabilityRequest: get server types availability request.
type GetServerTypesAvailabilityRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
}
// GetServerTypesAvailabilityResponse: get server types availability response.
type GetServerTypesAvailabilityResponse struct {
// Servers: map of server types.
Servers map[string]*GetServerTypesAvailabilityResponseAvailability `json:"servers"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *GetServerTypesAvailabilityResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *GetServerTypesAvailabilityResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*GetServerTypesAvailabilityResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
if r.Servers == nil {
r.Servers = make(map[string]*GetServerTypesAvailabilityResponseAvailability)
}
for k, v := range results.Servers {
r.Servers[k] = v
}
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// GetSnapshotRequest: get snapshot request.
type GetSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot you want to get.
SnapshotID string `json:"-"`
}
// GetSnapshotResponse: get snapshot response.
type GetSnapshotResponse struct {
Snapshot *Snapshot `json:"snapshot"`
}
// GetVolumeRequest: get volume request.
type GetVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume you want to get.
VolumeID string `json:"-"`
}
// GetVolumeResponse: get volume response.
type GetVolumeResponse struct {
Volume *Volume `json:"volume"`
}
// ListDefaultSecurityGroupRulesRequest: list default security group rules request.
type ListDefaultSecurityGroupRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Project: project ID in which the IPs are reserved.
Project *string `json:"-"`
// Organization: organization ID in which the IPs are reserved.
Organization *string `json:"-"`
// Tags: filter IPs with these exact tags (to filter with several tags, use commas to separate them).
Tags []string `json:"-"`
// Name: filter on the IP address (Works as a LIKE operation on the IP address).
Name *string `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
// Type: filter on the IP Mobility IP type (whose value should be either 'routed_ipv4' or 'routed_ipv6').
Type *string `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
// TotalCount: total number of ips.
TotalCount uint32 `json:"total_count"`
// IPs: list of ips.
IPs []*IP `json:"ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint32(len(results.IPs))
return uint32(len(results.IPs)), nil
}
// ListImagesRequest: list images request.
type ListImagesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
Organization *string `json:"-"`
PerPage *uint32 `json:"-"`
Page *int32 `json:"-"`
Name *string `json:"-"`
Public *bool `json:"-"`
Arch *string `json:"-"`
Project *string `json:"-"`
Tags *string `json:"-"`
}
// ListImagesResponse: list images response.
type ListImagesResponse struct {
// TotalCount: total number of images.
TotalCount uint32 `json:"total_count"`
// Images: list of images.
Images []*Image `json:"images"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListImagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Images = append(r.Images, results.Images...)
r.TotalCount += uint32(len(results.Images))
return uint32(len(results.Images)), nil
}
// ListPlacementGroupsRequest: list placement groups request.
type ListPlacementGroupsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
// Organization: list only placement groups of this Organization ID.
Organization *string `json:"-"`
// Project: list only placement groups of this Project ID.
Project *string `json:"-"`
// Tags: list placement groups with these exact tags (to filter with several tags, use commas to separate them).
Tags []string `json:"-"`
// Name: filter placement groups by name (for eg. "cluster1" will return "cluster100" and "cluster1" but not "foo").
Name *string `json:"-"`
}
// ListPlacementGroupsResponse: list placement groups response.
type ListPlacementGroupsResponse struct {
// TotalCount: total number of placement groups.
TotalCount uint32 `json:"total_count"`
// PlacementGroups: list of placement groups.
PlacementGroups []*PlacementGroup `json:"placement_groups"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPlacementGroupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPlacementGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPlacementGroupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PlacementGroups = append(r.PlacementGroups, results.PlacementGroups...)
r.TotalCount += uint32(len(results.PlacementGroups))
return uint32(len(results.PlacementGroups)), nil
}
// ListPrivateNICsRequest: list private ni cs request.
type ListPrivateNICsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: instance to which the private NIC is attached.
ServerID string `json:"-"`
// Tags: private NIC tags.
Tags []string `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
}
// ListPrivateNICsResponse: list private ni cs response.
type ListPrivateNICsResponse struct {
PrivateNics []*PrivateNIC `json:"private_nics"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPrivateNICsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPrivateNICsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPrivateNICsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PrivateNics = append(r.PrivateNics, results.PrivateNics...)
r.TotalCount += uint64(len(results.PrivateNics))
return uint64(len(results.PrivateNics)), nil
}
// ListSecurityGroupRulesRequest: list security group rules request.
type ListSecurityGroupRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group.
SecurityGroupID string `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
}
// ListSecurityGroupRulesResponse: list security group rules response.
type ListSecurityGroupRulesResponse struct {
// TotalCount: total number of security groups.
TotalCount uint32 `json:"total_count"`
// Rules: list of security rules.
Rules []*SecurityGroupRule `json:"rules"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSecurityGroupRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSecurityGroupRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSecurityGroupRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint32(len(results.Rules))
return uint32(len(results.Rules)), nil
}
// ListSecurityGroupsRequest: list security groups request.
type ListSecurityGroupsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: name of the security group.
Name *string `json:"-"`
// Organization: security group Organization ID.
Organization *string `json:"-"`
// Project: security group Project ID.
Project *string `json:"-"`
// Tags: list security groups with these exact tags (to filter with several tags, use commas to separate them).
Tags []string `json:"-"`
// ProjectDefault: filter security groups with this value for project_default.
ProjectDefault *bool `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
}
// ListSecurityGroupsResponse: list security groups response.
type ListSecurityGroupsResponse struct {
// TotalCount: total number of security groups.
TotalCount uint32 `json:"total_count"`
// SecurityGroups: list of security groups.
SecurityGroups []*SecurityGroup `json:"security_groups"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSecurityGroupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSecurityGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSecurityGroupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SecurityGroups = append(r.SecurityGroups, results.SecurityGroups...)
r.TotalCount += uint32(len(results.SecurityGroups))
return uint32(len(results.SecurityGroups)), nil
}
// ListServerActionsRequest: list server actions request.
type ListServerActionsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
}
// ListServerActionsResponse: list server actions response.
type ListServerActionsResponse struct {
Actions []ServerAction `json:"actions"`
}
// ListServerUserDataRequest: list server user data request.
type ListServerUserDataRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance.
ServerID string `json:"-"`
}
// ListServerUserDataResponse: list server user data response.
type ListServerUserDataResponse struct {
UserData []string `json:"user_data"`
}
// ListServersRequest: list servers request.
type ListServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
// Organization: list only Instances of this Organization ID.
Organization *string `json:"-"`
// Project: list only Instances of this Project ID.
Project *string `json:"-"`
// Name: filter Instances by name (eg. "server1" will return "server100" and "server1" but not "foo").
Name *string `json:"-"`
// Deprecated: PrivateIP: list Instances by private_ip.
PrivateIP *net.IP `json:"-"`
// WithoutIP: list Instances that are not attached to a public IP.
WithoutIP *bool `json:"-"`
// WithIP: list Instances by IP (both private_ip and public_ip are supported).
WithIP *net.IP `json:"-"`
// CommercialType: list Instances of this commercial type.
CommercialType *string `json:"-"`
// State: list Instances in this state.
// Default value: running
State *ServerState `json:"-"`
// Tags: list Instances with these exact tags (to filter with several tags, use commas to separate them).
Tags []string `json:"-"`
// PrivateNetwork: list Instances in this Private Network.
PrivateNetwork *string `json:"-"`
// Order: define the order of the returned servers.
// Default value: creation_date_desc
Order ListServersRequestOrder `json:"-"`
// PrivateNetworks: list Instances from the given Private Networks (use commas to separate them).
PrivateNetworks []string `json:"-"`
// PrivateNicMacAddress: list Instances associated with the given private NIC MAC address.
PrivateNicMacAddress *string `json:"-"`
// Servers: list Instances from these server ids (use commas to separate them).
Servers []string `json:"-"`
}
// ListServersResponse: list servers response.
type ListServersResponse struct {
// TotalCount: total number of Instances.
TotalCount uint32 `json:"total_count"`
// Servers: list of Instances.
Servers []*Server `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Servers = append(r.Servers, results.Servers...)
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListServersTypesRequest: list servers types request.
type ListServersTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
PerPage *uint32 `json:"-"`
Page *int32 `json:"-"`
}
// ListServersTypesResponse: list servers types response.
type ListServersTypesResponse struct {
// TotalCount: total number of Instance types.
TotalCount uint32 `json:"total_count"`
// Servers: list of Instance types.
Servers map[string]*ServerType `json:"servers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListServersTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListServersTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListServersTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
if r.Servers == nil {
r.Servers = make(map[string]*ServerType)
}
for k, v := range results.Servers {
r.Servers[k] = v
}
r.TotalCount += uint32(len(results.Servers))
return uint32(len(results.Servers)), nil
}
// ListSnapshotsRequest: list snapshots request.
type ListSnapshotsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Organization: list snapshots only for this Organization ID.
Organization *string `json:"-"`
// Project: list snapshots only for this Project ID.
Project *string `json:"-"`
// PerPage: number of snapshots returned per page (positive integer lower or equal to 100).
PerPage *uint32 `json:"-"`
// Page: page to be returned.
Page *int32 `json:"-"`
// Name: list snapshots of the requested name.
Name *string `json:"-"`
// Tags: list snapshots that have the requested tag.
Tags *string `json:"-"`
// BaseVolumeID: list snapshots originating only from this volume.
BaseVolumeID *string `json:"-"`
}
// ListSnapshotsResponse: list snapshots response.
type ListSnapshotsResponse struct {
// TotalCount: total number of snapshots.
TotalCount uint32 `json:"total_count"`
// Snapshots: list of snapshots.
Snapshots []*Snapshot `json:"snapshots"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSnapshotsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Snapshots = append(r.Snapshots, results.Snapshots...)
r.TotalCount += uint32(len(results.Snapshots))
return uint32(len(results.Snapshots)), nil
}
// ListVolumesRequest: list volumes request.
type ListVolumesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeType: filter by volume type.
// Default value: l_ssd
VolumeType *VolumeVolumeType `json:"-"`
// PerPage: a positive integer lower or equal to 100 to select the number of items to return.
PerPage *uint32 `json:"-"`
// Page: a positive integer to choose the page to return.
Page *int32 `json:"-"`
// Organization: filter volume by Organization ID.
Organization *string `json:"-"`
// Project: filter volume by Project ID.
Project *string `json:"-"`
// Tags: filter volumes with these exact tags (to filter with several tags, use commas to separate them).
Tags []string `json:"-"`
// Name: filter volume by name (for eg. "vol" will return "myvolume" but not "data").
Name *string `json:"-"`
}
// ListVolumesResponse: list volumes response.
type ListVolumesResponse struct {
// TotalCount: total number of volumes.
TotalCount uint32 `json:"total_count"`
// Volumes: list of volumes.
Volumes []*Volume `json:"volumes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVolumesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVolumesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListVolumesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Volumes = append(r.Volumes, results.Volumes...)
r.TotalCount += uint32(len(results.Volumes))
return uint32(len(results.Volumes)), nil
}
// ListVolumesTypesRequest: list volumes types request.
type ListVolumesTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
PerPage *uint32 `json:"-"`
Page *int32 `json:"-"`
}
// ListVolumesTypesResponse: list volumes types response.
type ListVolumesTypesResponse struct {
// TotalCount: total number of volume types.
TotalCount uint32 `json:"total_count"`
// Volumes: map of volume types.
Volumes map[string]*VolumeType `json:"volumes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVolumesTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVolumesTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListVolumesTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
if r.Volumes == nil {
r.Volumes = make(map[string]*VolumeType)
}
for k, v := range results.Volumes {
r.Volumes[k] = v
}
r.TotalCount += uint32(len(results.Volumes))
return uint32(len(results.Volumes)), nil
}
// MigrationPlan: migration plan.
type MigrationPlan struct {
// Volume: a volume which will be migrated to SBS together with the snapshots, if present.
Volume *Volume `json:"volume"`
// Snapshots: a list of snapshots which will be migrated to SBS together and with the volume, if present.
Snapshots []*Snapshot `json:"snapshots"`
// ValidationKey: a value to be passed to the call to the [Migrate a volume and/or snapshots to SBS](#path-volumes-migrate-a-volume-andor-snapshots-to-sbs-scaleway-block-storage) endpoint, to confirm that the execution of the plan is being requested.
ValidationKey string `json:"validation_key"`
}
// PlanBlockMigrationRequest: plan block migration request.
type PlanBlockMigrationRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: the volume for which the migration plan will be generated.
// Precisely one of VolumeID, SnapshotID must be set.
VolumeID *string `json:"volume_id,omitempty"`
// SnapshotID: the snapshot for which the migration plan will be generated.
// Precisely one of VolumeID, SnapshotID must be set.
SnapshotID *string `json:"snapshot_id,omitempty"`
}
// ServerActionRequest: server action request.
type ServerActionRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance.
ServerID string `json:"-"`
// Action: action to perform on the Instance.
// Default value: poweron
Action ServerAction `json:"action,omitempty"`
// Name: name of the backup you want to create.
// This field should only be specified when performing a backup action.
Name *string `json:"name,omitempty"`
// Volumes: for each volume UUID, the snapshot parameters of the volume.
// This field should only be specified when performing a backup action.
Volumes map[string]*ServerActionRequestVolumeBackupTemplate `json:"volumes,omitempty"`
// DisableIPv6: disable IPv6 on the Instance while performing migration to routed IPs.
// This field should only be specified when performing a enable_routed_ip action.
DisableIPv6 *bool `json:"disable_ipv6,omitempty"`
}
// ServerActionResponse: server action response.
type ServerActionResponse struct {
Task *Task `json:"task"`
}
// SetImageRequest: set image request.
type SetImageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
ID string `json:"-"`
Name string `json:"name"`
// Arch: default value: unknown_arch
Arch Arch `json:"arch"`
CreationDate *time.Time `json:"creation_date,omitempty"`
ModificationDate *time.Time `json:"modification_date,omitempty"`
// Deprecated
DefaultBootscript *Bootscript `json:"default_bootscript,omitempty"`
ExtraVolumes map[string]*Volume `json:"extra_volumes"`
FromServer string `json:"from_server"`
Organization string `json:"organization"`
Public bool `json:"public"`
RootVolume *VolumeSummary `json:"root_volume,omitempty"`
// State: default value: available
State ImageState `json:"state"`
Project string `json:"project"`
Tags *[]string `json:"tags,omitempty"`
}
// SetPlacementGroupRequest: set placement group request.
type SetPlacementGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
PlacementGroupID string `json:"-"`
Name string `json:"name"`
Organization string `json:"organization"`
// PolicyMode: default value: optional
PolicyMode PlacementGroupPolicyMode `json:"policy_mode"`
// PolicyType: default value: max_availability
PolicyType PlacementGroupPolicyType `json:"policy_type"`
Project string `json:"project"`
Tags *[]string `json:"tags,omitempty"`
}
// SetPlacementGroupResponse: set placement group response.
type SetPlacementGroupResponse struct {
PlacementGroup *PlacementGroup `json:"placement_group"`
}
// SetPlacementGroupServersRequest: set placement group servers request.
type SetPlacementGroupServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group you want to set.
PlacementGroupID string `json:"-"`
// Servers: an array of the Instances' UUIDs you want to configure.
Servers []string `json:"servers"`
}
// SetPlacementGroupServersResponse: set placement group servers response.
type SetPlacementGroupServersResponse struct {
// Servers: instances attached to the placement group.
Servers []*PlacementGroupServer `json:"servers"`
}
// SetSecurityGroupRulesRequest: set security group rules request.
type SetSecurityGroupRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group to update the rules on.
SecurityGroupID string `json:"-"`
// Rules: list of rules to update in the security group.
Rules []*SetSecurityGroupRulesRequestRule `json:"rules"`
}
// SetSecurityGroupRulesResponse: set security group rules response.
type SetSecurityGroupRulesResponse struct {
Rules []*SecurityGroupRule `json:"rules"`
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IP: IP ID or IP address.
IP string `json:"-"`
// Reverse: reverse domain name.
Reverse *NullableStringValue `json:"reverse,omitempty"`
// Type: should have no effect.
// Default value: unknown_iptype
Type IPType `json:"type,omitempty"`
// Tags: an array of keywords you want to tag this IP with.
Tags *[]string `json:"tags,omitempty"`
Server *NullableStringValue `json:"server,omitempty"`
}
// UpdateIPResponse: update ip response.
type UpdateIPResponse struct {
IP *IP `json:"ip"`
}
// UpdateImageRequest: update image request.
type UpdateImageRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ImageID: UUID of the image.
ImageID string `json:"-"`
// Name: name of the image.
Name *string `json:"name,omitempty"`
// Arch: architecture of the image.
// Default value: unknown_arch
Arch Arch `json:"arch,omitempty"`
// ExtraVolumes: additional snapshots of the image, with extra_volumeKey being the position of the snapshot in the image.
ExtraVolumes map[string]*VolumeImageUpdateTemplate `json:"extra_volumes,omitempty"`
// Tags: tags of the image.
Tags *[]string `json:"tags,omitempty"`
// Public: true to set the image as public.
Public *bool `json:"public,omitempty"`
}
// UpdateImageResponse: update image response.
type UpdateImageResponse struct {
Image *Image `json:"image"`
}
// UpdatePlacementGroupRequest: update placement group request.
type UpdatePlacementGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group.
PlacementGroupID string `json:"-"`
// Name: name of the placement group.
Name *string `json:"name,omitempty"`
// Tags: tags of the placement group.
Tags *[]string `json:"tags,omitempty"`
// PolicyMode: operating mode of the placement group.
// Default value: optional
PolicyMode *PlacementGroupPolicyMode `json:"policy_mode,omitempty"`
// PolicyType: policy type of the placement group.
// Default value: max_availability
PolicyType *PlacementGroupPolicyType `json:"policy_type,omitempty"`
}
// UpdatePlacementGroupResponse: update placement group response.
type UpdatePlacementGroupResponse struct {
PlacementGroup *PlacementGroup `json:"placement_group"`
}
// UpdatePlacementGroupServersRequest: update placement group servers request.
type UpdatePlacementGroupServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PlacementGroupID: UUID of the placement group you want to update.
PlacementGroupID string `json:"-"`
// Servers: an array of the Instances' UUIDs you want to configure.
Servers []string `json:"servers,omitempty"`
}
// UpdatePlacementGroupServersResponse: update placement group servers response.
type UpdatePlacementGroupServersResponse struct {
// Servers: instances attached to the placement group.
Servers []*PlacementGroupServer `json:"servers"`
}
// UpdatePrivateNICRequest: update private nic request.
type UpdatePrivateNICRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance the private NIC will be attached to.
ServerID string `json:"-"`
// PrivateNicID: private NIC unique ID.
PrivateNicID string `json:"-"`
// Tags: tags used to select private NIC/s.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateSecurityGroupRequest: update security group request.
type UpdateSecurityGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group.
SecurityGroupID string `json:"-"`
// Name: name of the security group.
Name *string `json:"name,omitempty"`
// Description: description of the security group.
Description *string `json:"description,omitempty"`
// EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable.
EnableDefaultSecurity *bool `json:"enable_default_security,omitempty"`
// InboundDefaultPolicy: default inbound policy.
// Default value: unknown_policy
InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy,omitempty"`
// Tags: tags of the security group.
Tags *[]string `json:"tags,omitempty"`
// Deprecated: OrganizationDefault: please use project_default instead.
OrganizationDefault *bool `json:"organization_default,omitempty"`
// ProjectDefault: true use this security group for future Instances created in this project.
ProjectDefault *bool `json:"project_default,omitempty"`
// OutboundDefaultPolicy: default outbound policy.
// Default value: unknown_policy
OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy,omitempty"`
// Stateful: true to set the security group as stateful.
Stateful *bool `json:"stateful,omitempty"`
}
// UpdateSecurityGroupResponse: update security group response.
type UpdateSecurityGroupResponse struct {
SecurityGroup *SecurityGroup `json:"security_group"`
}
// UpdateSecurityGroupRuleRequest: update security group rule request.
type UpdateSecurityGroupRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SecurityGroupID: UUID of the security group.
SecurityGroupID string `json:"-"`
// SecurityGroupRuleID: UUID of the rule.
SecurityGroupRuleID string `json:"-"`
// Protocol: protocol family this rule applies to.
// Default value: unknown_protocol
Protocol SecurityGroupRuleProtocol `json:"protocol,omitempty"`
// Direction: direction the rule applies to.
// Default value: unknown_direction
Direction SecurityGroupRuleDirection `json:"direction,omitempty"`
// Action: action to apply when the rule matches a packet.
// Default value: unknown_action
Action SecurityGroupRuleAction `json:"action,omitempty"`
// IPRange: range of IP addresses these rules apply to.
IPRange *scw.IPNet `json:"ip_range,omitempty"`
// DestPortFrom: beginning of the range of ports this rule applies to (inclusive). If 0 is provided, unset the parameter.
DestPortFrom *uint32 `json:"dest_port_from,omitempty"`
// DestPortTo: end of the range of ports this rule applies to (inclusive). If 0 is provided, unset the parameter.
DestPortTo *uint32 `json:"dest_port_to,omitempty"`
// Position: position of this rule in the security group rules list.
Position *uint32 `json:"position,omitempty"`
}
// UpdateSecurityGroupRuleResponse: update security group rule response.
type UpdateSecurityGroupRuleResponse struct {
Rule *SecurityGroupRule `json:"rule"`
}
// UpdateServerRequest: update server request.
type UpdateServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ServerID: UUID of the Instance.
ServerID string `json:"-"`
// Name: name of the Instance.
Name *string `json:"name,omitempty"`
// BootType: default value: local
BootType *BootType `json:"boot_type,omitempty"`
// Tags: tags of the Instance.
Tags *[]string `json:"tags,omitempty"`
Volumes *map[string]*VolumeServerTemplate `json:"volumes,omitempty"`
DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"`
// Deprecated: RoutedIPEnabled: true to configure the instance so it uses the new routed IP mode (once this is set to True you cannot set it back to False).
RoutedIPEnabled *bool `json:"routed_ip_enabled,omitempty"`
// PublicIPs: a list of reserved IP IDs to attach to the Instance.
PublicIPs *[]string `json:"public_ips,omitempty"`
// Deprecated
EnableIPv6 *bool `json:"enable_ipv6,omitempty"`
Protected *bool `json:"protected,omitempty"`
SecurityGroup *SecurityGroupTemplate `json:"security_group,omitempty"`
// PlacementGroup: placement group ID if Instance must be part of a placement group.
PlacementGroup *NullableStringValue `json:"placement_group,omitempty"`
// PrivateNics: instance private NICs.
PrivateNics *[]string `json:"private_nics,omitempty"`
// CommercialType: warning: This field has some restrictions:
// - Cannot be changed if the Instance is not in `stopped` state.
// - Cannot be changed if the Instance is in a placement group.
// - Cannot be changed from/to a Windows offer to/from a Linux offer.
// - Local storage requirements of the target commercial_types must be fulfilled (i.e. if an Instance has 80GB of local storage, it can be changed into a GP1-XS, which has a maximum of 150GB, but it cannot be changed into a DEV1-S, which has only 20GB).
CommercialType *string `json:"commercial_type,omitempty"`
// AdminPasswordEncryptionSSHKeyID: the public_key value of this key is used to encrypt the admin password. When set to an empty string, reset this value and admin_password_encrypted_value to an empty string so a new password may be generated.
AdminPasswordEncryptionSSHKeyID *string `json:"admin_password_encryption_ssh_key_id,omitempty"`
}
// UpdateServerResponse: update server response.
type UpdateServerResponse struct {
Server *Server `json:"server"`
}
// UpdateSnapshotRequest: update snapshot request.
type UpdateSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
// Name: name of the snapshot.
Name *string `json:"name,omitempty"`
// Tags: tags of the snapshot.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateSnapshotResponse: update snapshot response.
type UpdateSnapshotResponse struct {
Snapshot *Snapshot `json:"snapshot"`
}
// UpdateVolumeRequest: update volume request.
type UpdateVolumeRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// VolumeID: UUID of the volume.
VolumeID string `json:"-"`
// Name: volume name.
Name *string `json:"name,omitempty"`
// Tags: tags of the volume.
Tags *[]string `json:"tags,omitempty"`
// Size: volume disk size, must be a multiple of 512.
Size *scw.Size `json:"size,omitempty"`
}
// UpdateVolumeResponse: update volume response.
type UpdateVolumeResponse struct {
Volume *Volume `json:"volume"`
}
// setImageResponse: set image response.
type setImageResponse struct {
Image *Image `json:"image"`
}
// setSecurityGroupRequest: set security group request.
type setSecurityGroupRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ID: UUID of the security group.
ID string `json:"-"`
// Name: name of the security group.
Name string `json:"name"`
// Tags: tags of the security group.
Tags *[]string `json:"tags,omitempty"`
// CreationDate: creation date of the security group (will be ignored).
CreationDate *time.Time `json:"creation_date,omitempty"`
// ModificationDate: modification date of the security group (will be ignored).
ModificationDate *time.Time `json:"modification_date,omitempty"`
// Description: description of the security group.
Description string `json:"description"`
// EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable.
EnableDefaultSecurity bool `json:"enable_default_security"`
// InboundDefaultPolicy: default inbound policy.
// Default value: unknown_policy
InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"`
// OutboundDefaultPolicy: default outbound policy.
// Default value: unknown_policy
OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"`
// Organization: security groups Organization ID.
Organization string `json:"organization"`
// Project: security group Project ID.
Project string `json:"project"`
// Deprecated: OrganizationDefault: please use project_default instead.
OrganizationDefault *bool `json:"organization_default,omitempty"`
// ProjectDefault: true use this security group for future Instances created in this project.
ProjectDefault bool `json:"project_default"`
// Servers: instances attached to this security group.
Servers []*ServerSummary `json:"servers"`
// Stateful: true to set the security group as stateful.
Stateful bool `json:"stateful"`
}
// setSecurityGroupResponse: set security group response.
type setSecurityGroupResponse struct {
SecurityGroup *SecurityGroup `json:"security_group"`
}
// setSecurityGroupRuleRequest: set security group rule request.
type setSecurityGroupRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
SecurityGroupID string `json:"-"`
SecurityGroupRuleID string `json:"-"`
ID string `json:"id"`
// Protocol: default value: unknown_protocol
Protocol SecurityGroupRuleProtocol `json:"protocol"`
// Direction: default value: unknown_direction
Direction SecurityGroupRuleDirection `json:"direction"`
// Action: default value: unknown_action
Action SecurityGroupRuleAction `json:"action"`
IPRange scw.IPNet `json:"ip_range"`
DestPortFrom *uint32 `json:"dest_port_from,omitempty"`
DestPortTo *uint32 `json:"dest_port_to,omitempty"`
Position uint32 `json:"position"`
Editable bool `json:"editable"`
}
// setSecurityGroupRuleResponse: set security group rule response.
type setSecurityGroupRuleResponse struct {
Rule *SecurityGroupRule `json:"rule"`
}
// setServerRequest: set server request.
type setServerRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ID: instance unique ID.
ID string `json:"-"`
// Name: instance name.
Name string `json:"name"`
// Organization: instance Organization ID.
Organization string `json:"organization"`
// Project: instance Project ID.
Project string `json:"project"`
// AllowedActions: provide a list of allowed actions on the server.
AllowedActions []ServerAction `json:"allowed_actions"`
// Tags: tags associated with the Instance.
Tags *[]string `json:"tags,omitempty"`
// CommercialType: instance commercial type (eg. GP1-M).
CommercialType string `json:"commercial_type"`
// CreationDate: instance creation date.
CreationDate *time.Time `json:"creation_date,omitempty"`
// DynamicIPRequired: true if a dynamic IPv4 is required.
DynamicIPRequired bool `json:"dynamic_ip_required"`
// Deprecated: RoutedIPEnabled: true to configure the instance so it uses the new routed IP mode (once this is set to True you cannot set it back to False).
RoutedIPEnabled *bool `json:"routed_ip_enabled,omitempty"`
// Deprecated: EnableIPv6: true if IPv6 is enabled (deprecated and always `False` when `routed_ip_enabled` is `True`).
EnableIPv6 *bool `json:"enable_ipv6,omitempty"`
// Hostname: instance host name.
Hostname string `json:"hostname"`
// Image: provide information on the Instance image.
Image *Image `json:"image,omitempty"`
// Protected: instance protection option is activated.
Protected bool `json:"protected"`
// Deprecated: PrivateIP: instance private IP address (deprecated and always `null` when `routed_ip_enabled` is `True`).
PrivateIP *string `json:"private_ip,omitempty"`
// Deprecated: PublicIP: information about the public IP (deprecated in favor of `public_ips`).
PublicIP *ServerIP `json:"public_ip,omitempty"`
// PublicIPs: information about all the public IPs attached to the server.
PublicIPs []*ServerIP `json:"public_ips"`
// ModificationDate: instance modification date.
ModificationDate *time.Time `json:"modification_date,omitempty"`
// State: instance state.
// Default value: running
State ServerState `json:"state"`
// Location: instance location.
Location *ServerLocation `json:"location,omitempty"`
// Deprecated: IPv6: instance IPv6 address (deprecated when `routed_ip_enabled` is `True`).
IPv6 *ServerIPv6 `json:"ipv6,omitempty"`
// BootType: instance boot type.
// Default value: local
BootType BootType `json:"boot_type"`
// Volumes: instance volumes.
Volumes map[string]*Volume `json:"volumes"`
// SecurityGroup: instance security group.
SecurityGroup *SecurityGroupSummary `json:"security_group,omitempty"`
// Maintenances: instance planned maintenances.
Maintenances []*ServerMaintenance `json:"maintenances"`
// StateDetail: instance state_detail.
StateDetail string `json:"state_detail"`
// Arch: instance architecture (refers to the CPU architecture used for the Instance, e.g. x86_64, arm64).
// Default value: unknown_arch
Arch Arch `json:"arch"`
// PlacementGroup: instance placement group.
PlacementGroup *PlacementGroup `json:"placement_group,omitempty"`
// PrivateNics: instance private NICs.
PrivateNics []*PrivateNIC `json:"private_nics"`
// AdminPasswordEncryptionSSHKeyID: the public_key value of this key is used to encrypt the admin password. When set to an empty string, reset this value and admin_password_encrypted_value to an empty string so a new password may be generated.
AdminPasswordEncryptionSSHKeyID *string `json:"admin_password_encryption_ssh_key_id,omitempty"`
}
// setServerResponse: set server response.
type setServerResponse struct {
Server *Server `json:"server"`
}
// setSnapshotRequest: set snapshot request.
type setSnapshotRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
SnapshotID string `json:"-"`
ID string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
// VolumeType: default value: l_ssd
VolumeType VolumeVolumeType `json:"volume_type"`
Size scw.Size `json:"size"`
// State: default value: available
State SnapshotState `json:"state"`
BaseVolume *SnapshotBaseVolume `json:"base_volume,omitempty"`
CreationDate *time.Time `json:"creation_date,omitempty"`
ModificationDate *time.Time `json:"modification_date,omitempty"`
Project string `json:"project"`
Tags *[]string `json:"tags,omitempty"`
}
// setSnapshotResponse: set snapshot response.
type setSnapshotResponse struct {
Snapshot *Snapshot `json:"snapshot"`
}
// This API allows you to manage your Instances.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// GetServerTypesAvailability: Get availability for all Instance types.
func (s *API) GetServerTypesAvailability(req *GetServerTypesAvailabilityRequest, opts ...scw.RequestOption) (*GetServerTypesAvailabilityResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/servers/availability",
Query: query,
}
var resp GetServerTypesAvailabilityResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServersTypes: List available Instance types and their technical details.
func (s *API) ListServersTypes(req *ListServersTypesRequest, opts ...scw.RequestOption) (*ListServersTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/servers",
Query: query,
}
var resp ListServersTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVolumesTypes: List all volume types and their technical details.
func (s *API) ListVolumesTypes(req *ListVolumesTypesRequest, opts ...scw.RequestOption) (*ListVolumesTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/volumes",
Query: query,
}
var resp ListVolumesTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServers: List all Instances in a specified Availability Zone, e.g. `fr-par-1`.
func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "private_ip", req.PrivateIP)
parameter.AddToQuery(query, "without_ip", req.WithoutIP)
parameter.AddToQuery(query, "with_ip", req.WithIP)
parameter.AddToQuery(query, "commercial_type", req.CommercialType)
parameter.AddToQuery(query, "state", req.State)
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "private_network", req.PrivateNetwork)
parameter.AddToQuery(query, "order", req.Order)
if len(req.PrivateNetworks) != 0 {
parameter.AddToQuery(query, "private_networks", strings.Join(req.PrivateNetworks, ","))
}
parameter.AddToQuery(query, "private_nic_mac_address", req.PrivateNicMacAddress)
if len(req.Servers) != 0 {
parameter.AddToQuery(query, "servers", strings.Join(req.Servers, ","))
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
Query: query,
}
var resp ListServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// createServer: Create a new Instance of the specified commercial type in the specified zone. Pay attention to the volumes parameter, which takes an object which can be used in different ways to achieve different behaviors.
// Get more information in the [Technical Information](#technical-information) section of the introduction.
func (s *API) createServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("srv")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateServerResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServer: Delete the Instance with the specified ID.
func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetServer: Get the details of a specified Instance.
func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*GetServerResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
var resp GetServerResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// setServer:
func (s *API) setServer(req *setServerRequest, opts ...scw.RequestOption) (*setServerResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if req.Project == "" {
defaultProject, _ := s.client.GetDefaultProjectID()
req.Project = defaultProject
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ID) == "" {
return nil, errors.New("field ID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp setServerResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// updateServer: Update the Instance information, such as name, boot mode, or tags.
func (s *API) updateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateServerResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerActions: List all actions (e.g. power on, power off, reboot) that can currently be performed on an Instance.
func (s *API) ListServerActions(req *ListServerActionsRequest, opts ...scw.RequestOption) (*ListServerActionsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/action",
}
var resp ListServerActionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ServerAction: Perform an action on an Instance.
// Available actions are:
// * `poweron`: Start a stopped Instance.
// * `poweroff`: Fully stop the Instance and release the hypervisor slot.
// * `stop_in_place`: Stop the Instance, but keep the slot on the hypervisor.
// * `reboot`: Stop the instance and restart it.
// * `backup`: Create an image with all the volumes of an Instance.
// * `terminate`: Delete the Instance along with its attached volumes, except for SBS volumes.
// * `enable_routed_ip`: Migrate the Instance to the new network stack.
//
// The `terminate` action will result in the deletion of `l_ssd`, `b_ssd` and `scratch` volumes types, `sbs_volume` volumes type will only be detached.
// If you want to preserve your volumes, you should detach them before the Instance deletion or `terminate` action.
//
// The `backup` action can be done with:
// * No `volumes` key in the body: an image is created with snapshots of all the server volumes, except for the `scratch` volumes types.
// * `volumes` key in the body with a dictionary as value, in this dictionary volumes UUID as keys and empty dictionaries as values : an image is created with the snapshots of the volumes in `volumes` key. `scratch` volumes types can't be shapshotted.
func (s *API) ServerAction(req *ServerActionRequest, opts ...scw.RequestOption) (*ServerActionResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/action",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ServerActionResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListServerUserData: List all user data keys registered on a specified Instance.
func (s *API) ListServerUserData(req *ListServerUserDataRequest, opts ...scw.RequestOption) (*ListServerUserDataResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data",
}
var resp ListServerUserDataResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteServerUserData: Delete the specified key from an Instance's user data.
func (s *API) DeleteServerUserData(req *DeleteServerUserDataRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.Key) == "" {
return errors.New("field Key cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AttachServerVolume:
func (s *API) AttachServerVolume(req *AttachServerVolumeRequest, opts ...scw.RequestOption) (*AttachServerVolumeResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/attach-volume",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AttachServerVolumeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachServerVolume:
func (s *API) DetachServerVolume(req *DetachServerVolumeRequest, opts ...scw.RequestOption) (*DetachServerVolumeResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/detach-volume",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DetachServerVolumeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListImages: List all existing Instance images.
func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "public", req.Public)
parameter.AddToQuery(query, "arch", req.Arch)
parameter.AddToQuery(query, "project", req.Project)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images",
Query: query,
}
var resp ListImagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetImage: Get details of an image with the specified ID.
func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*GetImageResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
var resp GetImageResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateImage: Create an Instance image from the specified snapshot ID.
func (s *API) CreateImage(req *CreateImageRequest, opts ...scw.RequestOption) (*CreateImageResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("img")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateImageResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// setImage: Replace all image properties with an image message.
func (s *API) setImage(req *SetImageRequest, opts ...scw.RequestOption) (*setImageResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if req.Project == "" {
defaultProject, _ := s.client.GetDefaultProjectID()
req.Project = defaultProject
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ID) == "" {
return nil, errors.New("field ID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp setImageResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateImage: Update the properties of an image.
func (s *API) UpdateImage(req *UpdateImageRequest, opts ...scw.RequestOption) (*UpdateImageResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateImageResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteImage: Delete the image with the specified ID.
func (s *API) DeleteImage(req *DeleteImageRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListSnapshots: List all snapshots of an Organization in a specified Availability Zone.
func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "base_volume_id", req.BaseVolumeID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots",
Query: query,
}
var resp ListSnapshotsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnapshot: Create a snapshot from a specified volume or from a QCOW2 file in a specified Availability Zone.
func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*CreateSnapshotResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("snp")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateSnapshotResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnapshot: Get details of a snapshot with the specified ID.
func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*GetSnapshotResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp GetSnapshotResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// setSnapshot: Replace all the properties of a snapshot.
func (s *API) setSnapshot(req *setSnapshotRequest, opts ...scw.RequestOption) (*setSnapshotResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if req.Project == "" {
defaultProject, _ := s.client.GetDefaultProjectID()
req.Project = defaultProject
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp setSnapshotResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSnapshot: Update the properties of a snapshot.
func (s *API) UpdateSnapshot(req *UpdateSnapshotRequest, opts ...scw.RequestOption) (*UpdateSnapshotResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateSnapshotResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnapshot: Delete the snapshot with the specified ID.
func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ExportSnapshot: Export a snapshot to a specified Object Storage bucket in the same region.
func (s *API) ExportSnapshot(req *ExportSnapshotRequest, opts ...scw.RequestOption) (*ExportSnapshotResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "/export",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ExportSnapshotResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVolumes: List volumes in the specified Availability Zone. You can filter the output by volume type.
func (s *API) ListVolumes(req *ListVolumesRequest, opts ...scw.RequestOption) (*ListVolumesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "volume_type", req.VolumeType)
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes",
Query: query,
}
var resp ListVolumesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateVolume: Create a volume of a specified type in an Availability Zone.
func (s *API) CreateVolume(req *CreateVolumeRequest, opts ...scw.RequestOption) (*CreateVolumeResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("vol")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateVolumeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetVolume: Get details of a volume with the specified ID.
func (s *API) GetVolume(req *GetVolumeRequest, opts ...scw.RequestOption) (*GetVolumeResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return nil, errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
var resp GetVolumeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateVolume: Replace the name and/or size properties of a volume specified by its ID, with the specified value(s). Any volume name can be changed, however only `b_ssd` volumes can currently be increased in size.
func (s *API) UpdateVolume(req *UpdateVolumeRequest, opts ...scw.RequestOption) (*UpdateVolumeResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return nil, errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateVolumeResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteVolume: Delete the volume with the specified ID.
func (s *API) DeleteVolume(req *DeleteVolumeRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.VolumeID) == "" {
return errors.New("field VolumeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListSecurityGroups: List all existing security groups.
func (s *API) ListSecurityGroups(req *ListSecurityGroupsRequest, opts ...scw.RequestOption) (*ListSecurityGroupsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "project_default", req.ProjectDefault)
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups",
Query: query,
}
var resp ListSecurityGroupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSecurityGroup: Create a security group with a specified name and description.
func (s *API) CreateSecurityGroup(req *CreateSecurityGroupRequest, opts ...scw.RequestOption) (*CreateSecurityGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("sg")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateSecurityGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSecurityGroup: Get the details of a security group with the specified ID.
func (s *API) GetSecurityGroup(req *GetSecurityGroupRequest, opts ...scw.RequestOption) (*GetSecurityGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "",
}
var resp GetSecurityGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSecurityGroup: Delete a security group with the specified ID.
func (s *API) DeleteSecurityGroup(req *DeleteSecurityGroupRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// setSecurityGroup: Replace all security group properties with a security group message.
func (s *API) setSecurityGroup(req *setSecurityGroupRequest, opts ...scw.RequestOption) (*setSecurityGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if req.Project == "" {
defaultProject, _ := s.client.GetDefaultProjectID()
req.Project = defaultProject
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ID) == "" {
return nil, errors.New("field ID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.ID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp setSecurityGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSecurityGroup: Update the properties of security group.
func (s *API) UpdateSecurityGroup(req *UpdateSecurityGroupRequest, opts ...scw.RequestOption) (*UpdateSecurityGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateSecurityGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDefaultSecurityGroupRules: Lists the default rules applied to all the security groups.
func (s *API) ListDefaultSecurityGroupRules(req *ListDefaultSecurityGroupRulesRequest, opts ...scw.RequestOption) (*ListSecurityGroupRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/default/rules",
}
var resp ListSecurityGroupRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSecurityGroupRules: List the rules of the a specified security group ID.
func (s *API) ListSecurityGroupRules(req *ListSecurityGroupRulesRequest, opts ...scw.RequestOption) (*ListSecurityGroupRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules",
Query: query,
}
var resp ListSecurityGroupRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSecurityGroupRule: Create a rule in the specified security group ID.
func (s *API) CreateSecurityGroupRule(req *CreateSecurityGroupRuleRequest, opts ...scw.RequestOption) (*CreateSecurityGroupRuleResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateSecurityGroupRuleResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetSecurityGroupRules: Replaces the existing rules of the security group with the rules provided. This endpoint supports the update of existing rules, creation of new rules and deletion of existing rules when they are not passed in the request.
func (s *API) SetSecurityGroupRules(req *SetSecurityGroupRulesRequest, opts ...scw.RequestOption) (*SetSecurityGroupRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetSecurityGroupRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSecurityGroupRule: Delete a security group rule with the specified ID.
func (s *API) DeleteSecurityGroupRule(req *DeleteSecurityGroupRuleRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return errors.New("field SecurityGroupID cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupRuleID) == "" {
return errors.New("field SecurityGroupRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetSecurityGroupRule: Get details of a security group rule with the specified ID.
func (s *API) GetSecurityGroupRule(req *GetSecurityGroupRuleRequest, opts ...scw.RequestOption) (*GetSecurityGroupRuleResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupRuleID) == "" {
return nil, errors.New("field SecurityGroupRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "",
}
var resp GetSecurityGroupRuleResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// setSecurityGroupRule: Replace all the properties of a rule from a specified security group.
func (s *API) setSecurityGroupRule(req *setSecurityGroupRuleRequest, opts ...scw.RequestOption) (*setSecurityGroupRuleResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupRuleID) == "" {
return nil, errors.New("field SecurityGroupRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp setSecurityGroupRuleResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSecurityGroupRule: Update the properties of a rule from a specified security group.
func (s *API) UpdateSecurityGroupRule(req *UpdateSecurityGroupRuleRequest, opts ...scw.RequestOption) (*UpdateSecurityGroupRuleResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupID) == "" {
return nil, errors.New("field SecurityGroupID cannot be empty in request")
}
if fmt.Sprint(req.SecurityGroupRuleID) == "" {
return nil, errors.New("field SecurityGroupRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateSecurityGroupRuleResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPlacementGroups: List all placement groups in a specified Availability Zone.
func (s *API) ListPlacementGroups(req *ListPlacementGroupsRequest, opts ...scw.RequestOption) (*ListPlacementGroupsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups",
Query: query,
}
var resp ListPlacementGroupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePlacementGroup: Create a new placement group in a specified Availability Zone.
func (s *API) CreatePlacementGroup(req *CreatePlacementGroupRequest, opts ...scw.RequestOption) (*CreatePlacementGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("pg")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreatePlacementGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPlacementGroup: Get the specified placement group.
func (s *API) GetPlacementGroup(req *GetPlacementGroupRequest, opts ...scw.RequestOption) (*GetPlacementGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "",
}
var resp GetPlacementGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPlacementGroup: Set all parameters of the specified placement group.
func (s *API) SetPlacementGroup(req *SetPlacementGroupRequest, opts ...scw.RequestOption) (*SetPlacementGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if req.Project == "" {
defaultProject, _ := s.client.GetDefaultProjectID()
req.Project = defaultProject
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetPlacementGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePlacementGroup: Update one or more parameter of the specified placement group.
func (s *API) UpdatePlacementGroup(req *UpdatePlacementGroupRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdatePlacementGroupResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePlacementGroup: Delete the specified placement group.
func (s *API) DeletePlacementGroup(req *DeletePlacementGroupRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetPlacementGroupServers: Get all Instances belonging to the specified placement group.
func (s *API) GetPlacementGroupServers(req *GetPlacementGroupServersRequest, opts ...scw.RequestOption) (*GetPlacementGroupServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers",
}
var resp GetPlacementGroupServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPlacementGroupServers: Set all Instances belonging to the specified placement group.
func (s *API) SetPlacementGroupServers(req *SetPlacementGroupServersRequest, opts ...scw.RequestOption) (*SetPlacementGroupServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetPlacementGroupServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePlacementGroupServers: Update all Instances belonging to the specified placement group.
func (s *API) UpdatePlacementGroupServers(req *UpdatePlacementGroupServersRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupServersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PlacementGroupID) == "" {
return nil, errors.New("field PlacementGroupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdatePlacementGroupServersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List all flexible IPs in a specified zone.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "project", req.Project)
parameter.AddToQuery(query, "organization", req.Organization)
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIP: Reserve a flexible IP and attach it to the specified Instance.
func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*CreateIPResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProject, exist := s.client.GetDefaultProjectID()
if exist && req.Project == nil && req.Organization == nil {
req.Project = &defaultProject
}
defaultOrganization, exist := s.client.GetDefaultOrganizationID()
if exist && req.Project == nil && req.Organization == nil {
req.Organization = &defaultOrganization
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateIPResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIP: Get details of an IP with the specified ID or address.
func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*GetIPResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IP) == "" {
return nil, errors.New("field IP cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "",
}
var resp GetIPResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateIP: Update a flexible IP in the specified zone with the specified ID.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*UpdateIPResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IP) == "" {
return nil, errors.New("field IP cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp UpdateIPResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteIP: Delete the IP with the specified ID.
func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IP) == "" {
return errors.New("field IP cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPrivateNICs: List all private NICs of a specified Instance.
func (s *API) ListPrivateNICs(req *ListPrivateNICsRequest, opts ...scw.RequestOption) (*ListPrivateNICsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
if len(req.Tags) != 0 {
parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ","))
}
parameter.AddToQuery(query, "per_page", req.PerPage)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics",
Query: query,
}
var resp ListPrivateNICsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePrivateNIC: Create a private NIC connecting an Instance to a Private Network.
func (s *API) CreatePrivateNIC(req *CreatePrivateNICRequest, opts ...scw.RequestOption) (*CreatePrivateNICResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreatePrivateNICResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPrivateNIC: Get private NIC properties.
func (s *API) GetPrivateNIC(req *GetPrivateNICRequest, opts ...scw.RequestOption) (*GetPrivateNICResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNicID) == "" {
return nil, errors.New("field PrivateNicID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics/" + fmt.Sprint(req.PrivateNicID) + "",
}
var resp GetPrivateNICResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePrivateNIC: Update one or more parameter(s) of a specified private NIC.
func (s *API) UpdatePrivateNIC(req *UpdatePrivateNICRequest, opts ...scw.RequestOption) (*PrivateNIC, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNicID) == "" {
return nil, errors.New("field PrivateNicID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics/" + fmt.Sprint(req.PrivateNicID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNIC
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePrivateNIC: Delete a private NIC.
func (s *API) DeletePrivateNIC(req *DeletePrivateNICRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNicID) == "" {
return errors.New("field PrivateNicID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics/" + fmt.Sprint(req.PrivateNicID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetDashboard:
func (s *API) GetDashboard(req *GetDashboardRequest, opts ...scw.RequestOption) (*GetDashboardResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "organization", req.Organization)
parameter.AddToQuery(query, "project", req.Project)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/dashboard",
Query: query,
}
var resp GetDashboardResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PlanBlockMigration: Given a volume or snapshot, returns the migration plan but does not perform the actual migration. To perform the migration, you have to call the [Migrate a volume and/or snapshots to SBS](#path-volumes-migrate-a-volume-andor-snapshots-to-sbs-scaleway-block-storage) endpoint afterward.
// The endpoint returns the resources that should be migrated together:
// - the volume and any snapshots created from the volume, if the call was made to plan a volume migration.
// - the base volume of the snapshot (if the volume is not deleted) and its related snapshots, if the call was made to plan a snapshot migration.
// The endpoint also returns the validation_key, which must be provided to the [Migrate a volume and/or snapshots to SBS](#path-volumes-migrate-a-volume-andor-snapshots-to-sbs-scaleway-block-storage) endpoint to confirm that all resources listed in the plan should be migrated.
func (s *API) PlanBlockMigration(req *PlanBlockMigrationRequest, opts ...scw.RequestOption) (*MigrationPlan, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/block-migration/plan",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp MigrationPlan
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ApplyBlockMigration: To be used, the call to this endpoint must be preceded by a call to the [Get a volume or snapshot's migration plan](#path-volumes-get-a-volume-or-snapshots-migration-plan) endpoint. To migrate all resources mentioned in the migration plan, the validation_key returned in the plan must be provided.
func (s *API) ApplyBlockMigration(req *ApplyBlockMigrationRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/block-migration/apply",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CheckBlockMigrationOrganizationQuotas:
func (s *API) CheckBlockMigrationOrganizationQuotas(req *CheckBlockMigrationOrganizationQuotasRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Organization == "" {
defaultOrganization, _ := s.client.GetDefaultOrganizationID()
req.Organization = defaultOrganization
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/block-migration/check-organization-quotas",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/instance_sdk_server_test.go 0000664 0000000 0000000 00000014427 14747113137 0032600 0 ustar 00root root 0000000 0000000 package instance
import (
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestServerUpdate(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("server-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
var (
serverID string
volumeID string
zone = scw.ZoneFrPar1
name = "instance_sdk_server_test"
dynamicIPRequired = scw.BoolPtr(true)
commercialType = "START1-S"
image = scw.StringPtr("f974feac-abae-4365-b988-8ec7d1cec10d")
enableIPv6 = scw.BoolPtr(true)
bootType = BootTypeLocal
tags = []string{"foo", "bar"}
project = "14d2f7ae-9775-414c-9bed-6810e060d500"
)
t.Run("create server", func(t *testing.T) {
// Create server
createServerResponse, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: zone,
Name: name,
Project: &project,
Image: image,
EnableIPv6: enableIPv6,
CommercialType: commercialType,
Tags: tags,
DynamicIPRequired: dynamicIPRequired,
BootType: &bootType,
})
testhelpers.AssertNoError(t, err)
serverID = createServerResponse.Server.ID
testhelpers.Assert(t, createServerResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, 1 == len(createServerResponse.Server.Volumes), "should have exactly one volume because we didn't pass volumes map in the requests.")
for _, volume := range createServerResponse.Server.Volumes {
volumeID = volume.ID
}
testhelpers.Equals(t, name, createServerResponse.Server.Name)
testhelpers.Equals(t, project, createServerResponse.Server.Project)
testhelpers.Equals(t, project, createServerResponse.Server.Organization)
testhelpers.Equals(t, *image, createServerResponse.Server.Image.ID)
testhelpers.Equals(t, enableIPv6, createServerResponse.Server.EnableIPv6)
testhelpers.Equals(t, bootType, createServerResponse.Server.BootType)
testhelpers.Equals(t, commercialType, createServerResponse.Server.CommercialType)
testhelpers.Equals(t, tags, createServerResponse.Server.Tags)
testhelpers.Equals(t, *dynamicIPRequired, createServerResponse.Server.DynamicIPRequired)
})
t.Run("create server with orga (deprecated)", func(t *testing.T) {
// Create server
createServerResponse, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: zone,
Name: name,
Organization: &project,
Image: image,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, project, createServerResponse.Server.Project)
testhelpers.Equals(t, project, createServerResponse.Server.Organization)
// Delete Server
err = instanceAPI.DeleteServer(&DeleteServerRequest{
Zone: zone,
ServerID: createServerResponse.Server.ID,
})
testhelpers.AssertNoError(t, err)
})
t.Run("update server", func(t *testing.T) {
var (
newName = "some_new_name_for_server"
updatedTags = []string{}
)
// Update server
updateServerResponse, err := instanceAPI.updateServer(&UpdateServerRequest{
ServerID: serverID,
Zone: zone,
Name: &newName,
Tags: &updatedTags,
})
testhelpers.Assert(t, updateServerResponse.Server != nil, "Should have server in response")
testhelpers.AssertNoError(t, err)
// Initial values that are not altered in the above request should remaining the same
testhelpers.Equals(t, project, updateServerResponse.Server.Project)
testhelpers.Equals(t, project, updateServerResponse.Server.Organization)
testhelpers.Equals(t, *image, updateServerResponse.Server.Image.ID)
testhelpers.Equals(t, enableIPv6, updateServerResponse.Server.EnableIPv6)
testhelpers.Equals(t, bootType, updateServerResponse.Server.BootType)
testhelpers.Equals(t, commercialType, updateServerResponse.Server.CommercialType)
testhelpers.Equals(t, *dynamicIPRequired, updateServerResponse.Server.DynamicIPRequired)
testhelpers.Assert(t, 1 == len(updateServerResponse.Server.Volumes), "should have exactly one volume because we didn't pass volumes map in the requests.")
testhelpers.Equals(t, newName, updateServerResponse.Server.Name)
testhelpers.Equals(t, updatedTags, updateServerResponse.Server.Tags)
})
t.Run("remove server volumes", func(t *testing.T) {
// Remove/detach volumes
updateServerResponse, err := instanceAPI.updateServer(&UpdateServerRequest{
ServerID: serverID,
Zone: zone,
Volumes: &map[string]*VolumeServerTemplate{},
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, updateServerResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, 0 == len(updateServerResponse.Server.Volumes), "volume should be detached from server.")
})
t.Run("cleanup server and volume", func(t *testing.T) {
// Delete Server
err = instanceAPI.DeleteServer(&DeleteServerRequest{
Zone: zone,
ServerID: serverID,
})
testhelpers.AssertNoError(t, err)
// Delete Volume
err = instanceAPI.DeleteVolume(&DeleteVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
})
}
func TestCreateServerWithIncorrectBody(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("server-incorrect-body")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
zone := scw.ZoneFrPar1
// Create server
_, err = instanceAPI.CreateServer(&CreateServerRequest{
Zone: zone,
})
testhelpers.Assert(t, err != nil, "This request should error")
}
func TestListServerMultipleZones(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("server-list-zones")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
// Create server
_, err = instanceAPI.ListServers(&ListServersRequest{}, scw.WithZones(instanceAPI.Zones()...))
testhelpers.Assert(t, err == nil, "This request should not error: %s", err)
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/instance_utils.go 0000664 0000000 0000000 00000025737 14747113137 0030540 0 ustar 00root root 0000000 0000000 package instance
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
var resourceLock sync.Map
// lockResource locks a resource from a specific resourceID
func lockResource(resourceID string) *sync.Mutex {
v, _ := resourceLock.LoadOrStore(resourceID, &sync.Mutex{})
mutex := v.(*sync.Mutex)
mutex.Lock()
return mutex
}
// lockServer locks a server from its zone and its ID
func lockServer(zone scw.Zone, serverID string) *sync.Mutex {
return lockResource(fmt.Sprint("server", zone, serverID))
}
// AttachIPRequest contains the parameters to attach an IP to a server
//
// Deprecated: UpdateIPRequest should be used instead
type AttachIPRequest struct {
Zone scw.Zone `json:"-"`
IP string `json:"-"`
ServerID string `json:"server_id"`
}
// AttachIPResponse contains the updated IP after attaching
//
// Deprecated: UpdateIPResponse should be used instead
type AttachIPResponse struct {
IP *IP
}
// AttachIP attaches an IP to a server.
//
// Deprecated: UpdateIP() should be used instead
func (s *API) AttachIP(req *AttachIPRequest, opts ...scw.RequestOption) (*AttachIPResponse, error) {
ipResponse, err := s.UpdateIP(&UpdateIPRequest{
Zone: req.Zone,
IP: req.IP,
Server: &NullableStringValue{Value: req.ServerID},
}, opts...)
if err != nil {
return nil, err
}
return &AttachIPResponse{IP: ipResponse.IP}, nil
}
// DetachIPRequest contains the parameters to detach an IP from a server
//
// Deprecated: UpdateIPRequest should be used instead
type DetachIPRequest struct {
Zone scw.Zone `json:"-"`
IP string `json:"-"`
}
// DetachIPResponse contains the updated IP after detaching
//
// Deprecated: UpdateIPResponse should be used instead
type DetachIPResponse struct {
IP *IP
}
// DetachIP detaches an IP from a server.
//
// Deprecated: UpdateIP() should be used instead
func (s *API) DetachIP(req *DetachIPRequest, opts ...scw.RequestOption) (*DetachIPResponse, error) {
ipResponse, err := s.UpdateIP(&UpdateIPRequest{
Zone: req.Zone,
IP: req.IP,
Server: &NullableStringValue{Null: true},
}, opts...)
if err != nil {
return nil, err
}
return &DetachIPResponse{IP: ipResponse.IP}, nil
}
// AttachVolumeRequest contains the parameters to attach a volume to a server
// Deprecated by AttachServerVolumeRequest
type AttachVolumeRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
VolumeID string `json:"-"`
}
// AttachVolumeResponse contains the updated server after attaching a volume
// Deprecated by AttachServerVolumeResponse
type AttachVolumeResponse struct {
Server *Server `json:"-"`
}
// AttachVolume attaches a volume to a server
//
// Note: Implementation is thread-safe.
// Deprecated by AttachServerVolume provided by instance API
func (s *API) AttachVolume(req *AttachVolumeRequest, opts ...scw.RequestOption) (*AttachVolumeResponse, error) {
defer lockServer(req.Zone, req.ServerID).Unlock()
// check where the volume comes from
volume, err := s.getUnknownVolume(&getUnknownVolumeRequest{
Zone: req.Zone,
VolumeID: req.VolumeID,
}, opts...)
if err != nil {
return nil, err
}
attachServerVolumeReq := &AttachServerVolumeRequest{
Zone: req.Zone,
ServerID: req.ServerID,
VolumeID: req.VolumeID,
VolumeType: AttachServerVolumeRequestVolumeType(volume.Type),
}
resp, err := s.AttachServerVolume(attachServerVolumeReq, opts...)
if err != nil {
return nil, err
}
return &AttachVolumeResponse{Server: resp.Server}, nil
}
// DetachVolumeRequest contains the parameters to detach a volume from a server
// Deprecated by DetachServerVolumeRequest
type DetachVolumeRequest struct {
Zone scw.Zone `json:"-"`
VolumeID string `json:"-"`
// IsBlockVolume should be set to true if volume is from block API,
// can be set to false if volume is from instance API,
// if left nil both API will be tried
IsBlockVolume *bool `json:"-"`
}
// DetachVolumeResponse contains the updated server after detaching a volume
// Deprecated by DetachServerVolumeResponse
type DetachVolumeResponse struct {
Server *Server `json:"-"`
}
// DetachVolume detaches a volume from a server
//
// Note: Implementation is thread-safe.
// Deprecated by DetachServerVolume provided by instance API
func (s *API) DetachVolume(req *DetachVolumeRequest, opts ...scw.RequestOption) (*DetachVolumeResponse, error) {
volume, err := s.getUnknownVolume(&getUnknownVolumeRequest{
Zone: req.Zone,
VolumeID: req.VolumeID,
}, opts...)
if err != nil {
return nil, err
}
if volume.ServerID == nil {
return nil, errors.New("volume should be attached to a server")
}
defer lockServer(req.Zone, *volume.ServerID).Unlock()
resp, err := s.DetachServerVolume(&DetachServerVolumeRequest{
Zone: req.Zone,
ServerID: *volume.ServerID,
VolumeID: volume.ID,
}, opts...)
if err != nil {
return nil, err
}
return &DetachVolumeResponse{Server: resp.Server}, nil
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListServersResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListSecurityGroupRulesResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListSecurityGroupsResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListServersTypesResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListVolumesResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
func (v *NullableStringValue) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
v.Null = true
return nil
}
var tmp string
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
v.Null = false
v.Value = tmp
return nil
}
func (v *NullableStringValue) MarshalJSON() ([]byte, error) {
if v.Null {
return []byte("null"), nil
}
return json.Marshal(v.Value)
}
// WaitForPrivateNICRequest is used by WaitForPrivateNIC method.
type WaitForPrivateNICRequest struct {
ServerID string
PrivateNicID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForPrivateNIC wait for the private network to be in a "terminal state" before returning.
// This function can be used to wait for the private network to be attached for example.
func (s *API) WaitForPrivateNIC(req *WaitForPrivateNICRequest, opts ...scw.RequestOption) (*PrivateNIC, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[PrivateNICState]struct{}{
PrivateNICStateAvailable: {},
PrivateNICStateSyncingError: {},
}
pn, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetPrivateNIC(&GetPrivateNICRequest{
ServerID: req.ServerID,
Zone: req.Zone,
PrivateNicID: req.PrivateNicID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.PrivateNic.State]
return res.PrivateNic, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return pn.(*PrivateNIC), nil
}
// WaitForMACAddressRequest is used by WaitForMACAddress method.
type WaitForMACAddressRequest struct {
ServerID string
PrivateNicID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForMACAddress wait for the MAC address be assigned on instance before returning.
// This function can be used to wait for the private network to be attached for example.
func (s *API) WaitForMACAddress(req *WaitForMACAddressRequest, opts ...scw.RequestOption) (*PrivateNIC, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
pn, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetPrivateNIC(&GetPrivateNICRequest{
ServerID: req.ServerID,
Zone: req.Zone,
PrivateNicID: req.PrivateNicID,
}, opts...)
if err != nil {
return nil, false, err
}
if len(res.PrivateNic.MacAddress) > 0 {
return res.PrivateNic, true, err
}
return res.PrivateNic, false, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return pn.(*PrivateNIC), nil
}
// UnsafeSetTotalCount should not be used
// Internal usage only
func (r *GetServerTypesAvailabilityResponse) UnsafeSetTotalCount(totalCount int) {
r.TotalCount = uint32(totalCount)
}
// WaitForServerRDPPasswordRequest is used by WaitForServerRDPPassword method.
type WaitForServerRDPPasswordRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServerRDPPassword wait for an RDP password to be generated for an instance before returning.
// This function can be used to wait for a windows instance to boot up.
func (s *API) WaitForServerRDPPassword(req *WaitForServerRDPPasswordRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
if res.Server.AdminPasswordEncryptedValue != nil && *res.Server.AdminPasswordEncryptedValue != "" {
return res.Server, true, err
}
return res.Server, false, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/instance_utils_test.go 0000664 0000000 0000000 00000020062 14747113137 0031561 0 ustar 00root root 0000000 0000000 package instance
import (
"testing"
block "github.com/scaleway/scaleway-sdk-go/api/block/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestInstanceHelpers(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("utils-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
var (
serverID string
ipID string
volumeID string
zone = scw.ZoneFrPar1
project = "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"
image = scw.StringPtr("81b9475d-e1b5-43c2-ac48-4c1a3b640686")
)
t.Run("create server", func(t *testing.T) {
createServerResponse, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: zone,
Name: "instance_utils_test",
Project: &project,
Image: image,
CommercialType: "PRO2-XXS",
})
testhelpers.AssertNoError(t, err)
serverID = createServerResponse.Server.ID
for _, volume := range createServerResponse.Server.Volumes {
volumeID = volume.ID
}
})
t.Run("test ip related functions", func(t *testing.T) {
// Create IP
createIPResponse, err := instanceAPI.CreateIP(&CreateIPRequest{
Zone: zone,
Project: &project,
})
testhelpers.AssertNoError(t, err)
ipID = createIPResponse.IP.ID
// Attach IP
ipAttachResponse, err := instanceAPI.AttachIP(&AttachIPRequest{
IP: ipID,
Zone: zone,
ServerID: serverID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, serverID, ipAttachResponse.IP.Server.ID)
// Detach IP
ipDetachResponse, err := instanceAPI.DetachIP(&DetachIPRequest{
IP: ipID,
Zone: zone,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, nil == ipDetachResponse.IP.Server, "Server object should be nil for detached IP.")
// Delete IP
err = instanceAPI.DeleteIP(&DeleteIPRequest{
Zone: zone,
IP: ipID,
})
testhelpers.AssertNoError(t, err)
})
t.Run("Test attach and detach volume", func(t *testing.T) {
detachVolumeResponse, err := instanceAPI.DetachVolume(&DetachVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, detachVolumeResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, detachVolumeResponse.Server.Volumes != nil, "Should have volumes in response")
testhelpers.Assert(t, len(detachVolumeResponse.Server.Volumes) == 0, "Server should have zero volumes after detaching")
attachVolumeResponse, err := instanceAPI.AttachVolume(&AttachVolumeRequest{
Zone: zone,
ServerID: serverID,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, attachVolumeResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, attachVolumeResponse.Server.Volumes != nil, "Should have volumes in response")
testhelpers.Assert(t, len(attachVolumeResponse.Server.Volumes) == 1, "Server should have one volumes after attaching")
testhelpers.Equals(t, volumeID, attachVolumeResponse.Server.Volumes["0"].ID)
})
t.Run("teardown: delete server and volume", func(t *testing.T) {
// Delete Server
err = instanceAPI.DeleteServer(&DeleteServerRequest{
Zone: zone,
ServerID: serverID,
})
testhelpers.AssertNoError(t, err)
// Delete Volume
err = instanceAPI.DeleteVolume(&DeleteVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
})
}
func TestInstanceHelpers_BlockVolume(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("utils-test-block")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
blockAPI := block.NewAPI(client)
var (
serverID string
volumeID string
volumeID2 string
zone = scw.ZoneFrPar1
project = "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"
image = scw.StringPtr("81b9475d-e1b5-43c2-ac48-4c1a3b640686")
)
t.Run("create server and volume", func(t *testing.T) {
createVolumeResponse, err := blockAPI.CreateVolume(&block.CreateVolumeRequest{
Zone: zone,
Name: "instance_utils_test",
ProjectID: project,
FromEmpty: &block.CreateVolumeRequestFromEmpty{
Size: scw.GB * 20,
},
Tags: nil,
})
testhelpers.AssertNoError(t, err)
volumeID = createVolumeResponse.ID
createVolumeResponse, err = blockAPI.CreateVolume(&block.CreateVolumeRequest{
Zone: zone,
Name: "instance_utils_test2",
ProjectID: project,
FromEmpty: &block.CreateVolumeRequestFromEmpty{
Size: scw.GB * 20,
},
Tags: nil,
})
testhelpers.AssertNoError(t, err)
volumeID2 = createVolumeResponse.ID
createServerResponse, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: zone,
Name: "instance_utils_test",
Project: &project,
Image: image,
CommercialType: "PRO2-XXS",
Volumes: map[string]*VolumeServerTemplate{
"0": {
ID: &volumeID,
VolumeType: VolumeVolumeTypeSbsVolume,
},
},
})
testhelpers.AssertNoError(t, err)
serverID = createServerResponse.Server.ID
})
t.Run("Test attach and detach volume", func(t *testing.T) {
detachVolumeResponse, err := instanceAPI.DetachVolume(&DetachVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, detachVolumeResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, detachVolumeResponse.Server.Volumes != nil, "Should have volumes in response")
testhelpers.Assert(t, len(detachVolumeResponse.Server.Volumes) == 0, "Server should have zero volumes after detaching")
attachVolumeResponse, err := instanceAPI.AttachVolume(&AttachVolumeRequest{
Zone: zone,
ServerID: serverID,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, attachVolumeResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, attachVolumeResponse.Server.Volumes != nil, "Should have volumes in response")
testhelpers.Assert(t, len(attachVolumeResponse.Server.Volumes) == 1, "Server should have one volumes after attaching")
testhelpers.Equals(t, volumeID, attachVolumeResponse.Server.Volumes["0"].ID)
attachVolumeResponse, err = instanceAPI.AttachVolume(&AttachVolumeRequest{
Zone: zone,
ServerID: serverID,
VolumeID: volumeID2,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, attachVolumeResponse.Server != nil, "Should have server in response")
testhelpers.Assert(t, attachVolumeResponse.Server.Volumes != nil, "Should have volumes in response")
testhelpers.Assert(t, len(attachVolumeResponse.Server.Volumes) == 2, "Server should have two volumes after attaching second volume")
testhelpers.Equals(t, volumeID2, attachVolumeResponse.Server.Volumes["1"].ID)
})
t.Run("teardown: delete server and volume", func(t *testing.T) {
// Delete Server
err = instanceAPI.DeleteServer(&DeleteServerRequest{
Zone: zone,
ServerID: serverID,
})
testhelpers.AssertNoError(t, err)
volumeStatusAvailable := block.VolumeStatusAvailable
_, err = blockAPI.WaitForVolumeAndReferences(&block.WaitForVolumeAndReferencesRequest{
VolumeID: volumeID,
Zone: zone,
VolumeTerminalStatus: &volumeStatusAvailable,
})
testhelpers.AssertNoError(t, err)
// Delete Volume
err = blockAPI.DeleteVolume(&block.DeleteVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
_, err = blockAPI.WaitForVolumeAndReferences(&block.WaitForVolumeAndReferencesRequest{
VolumeID: volumeID2,
Zone: zone,
VolumeTerminalStatus: &volumeStatusAvailable,
})
testhelpers.AssertNoError(t, err)
// Delete Volume
err = blockAPI.DeleteVolume(&block.DeleteVolumeRequest{
Zone: zone,
VolumeID: volumeID2,
})
testhelpers.AssertNoError(t, err)
})
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/security_group_utils_test.go 0000664 0000000 0000000 00000020162 14747113137 0033041 0 ustar 00root root 0000000 0000000 package instance
import (
"net"
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestAPI_UpdateSecurityGroup(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("security-group-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
createResponse, err := instanceAPI.CreateSecurityGroup(&CreateSecurityGroupRequest{
Name: "name",
Description: "description",
Stateful: true,
InboundDefaultPolicy: SecurityGroupPolicyAccept,
OutboundDefaultPolicy: SecurityGroupPolicyDrop,
})
testhelpers.AssertNoError(t, err)
accept := SecurityGroupPolicyAccept
drop := SecurityGroupPolicyDrop
updateResponse, err := instanceAPI.UpdateSecurityGroup(&UpdateSecurityGroupRequest{
SecurityGroupID: createResponse.SecurityGroup.ID,
Name: scw.StringPtr("new_name"),
Description: scw.StringPtr("new_description"),
Stateful: scw.BoolPtr(false),
InboundDefaultPolicy: drop,
OutboundDefaultPolicy: accept,
// Keep false here, switch it to true is too dangerous for the one who update the test cassette.
ProjectDefault: scw.BoolPtr(false),
Tags: scw.StringsPtr([]string{"foo", "bar"}),
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, "new_name", updateResponse.SecurityGroup.Name)
testhelpers.Equals(t, "new_description", updateResponse.SecurityGroup.Description)
testhelpers.Equals(t, SecurityGroupPolicyDrop, updateResponse.SecurityGroup.InboundDefaultPolicy)
testhelpers.Equals(t, SecurityGroupPolicyAccept, updateResponse.SecurityGroup.OutboundDefaultPolicy)
testhelpers.Equals(t, false, updateResponse.SecurityGroup.Stateful)
testhelpers.Equals(t, false, updateResponse.SecurityGroup.ProjectDefault)
testhelpers.Equals(t, false, *updateResponse.SecurityGroup.OrganizationDefault)
testhelpers.Equals(t, []string{"foo", "bar"}, updateResponse.SecurityGroup.Tags)
err = instanceAPI.DeleteSecurityGroup(&DeleteSecurityGroupRequest{
SecurityGroupID: createResponse.SecurityGroup.ID,
})
testhelpers.AssertNoError(t, err)
}
func TestAPI_UpdateSecurityGroupRule(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("security-group-rule-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
bootstrap := func(t *testing.T) (*SecurityGroup, *SecurityGroupRule, func()) {
t.Helper()
createSecurityGroupResponse, err := instanceAPI.CreateSecurityGroup(&CreateSecurityGroupRequest{
Name: "name",
Description: "description",
Stateful: true,
InboundDefaultPolicy: SecurityGroupPolicyAccept,
OutboundDefaultPolicy: SecurityGroupPolicyDrop,
})
testhelpers.AssertNoError(t, err)
_, ipNet, _ := net.ParseCIDR("8.8.8.8/32")
createRuleResponse, err := instanceAPI.CreateSecurityGroupRule(&CreateSecurityGroupRuleRequest{
SecurityGroupID: createSecurityGroupResponse.SecurityGroup.ID,
Direction: SecurityGroupRuleDirectionInbound,
Protocol: SecurityGroupRuleProtocolTCP,
DestPortFrom: scw.Uint32Ptr(1),
DestPortTo: scw.Uint32Ptr(1024),
IPRange: scw.IPNet{IPNet: *ipNet},
Action: SecurityGroupRuleActionAccept,
Position: 1,
})
testhelpers.AssertNoError(t, err)
return createSecurityGroupResponse.SecurityGroup, createRuleResponse.Rule, func() {
err = instanceAPI.DeleteSecurityGroup(&DeleteSecurityGroupRequest{
SecurityGroupID: createSecurityGroupResponse.SecurityGroup.ID,
})
testhelpers.AssertNoError(t, err)
}
}
t.Run("Simple update", func(t *testing.T) {
group, rule, cleanUp := bootstrap(t)
defer cleanUp()
_, ipNet, _ := net.ParseCIDR("1.1.1.1/32")
updateResponse, err := instanceAPI.UpdateSecurityGroupRule(&UpdateSecurityGroupRuleRequest{
SecurityGroupID: group.ID,
SecurityGroupRuleID: rule.ID,
Action: SecurityGroupRuleActionDrop,
IPRange: &scw.IPNet{IPNet: *ipNet},
DestPortFrom: scw.Uint32Ptr(1),
DestPortTo: scw.Uint32Ptr(2048),
Protocol: SecurityGroupRuleProtocolUDP,
Direction: SecurityGroupRuleDirectionOutbound,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, SecurityGroupRuleActionDrop, updateResponse.Rule.Action)
testhelpers.Equals(t, scw.IPNet{IPNet: net.IPNet{IP: net.IPv4(0x1, 0x1, 0x1, 0x1), Mask: net.IPMask{0xff, 0xff, 0xff, 0xff}}}, updateResponse.Rule.IPRange)
testhelpers.Equals(t, scw.Uint32Ptr(1), updateResponse.Rule.DestPortFrom)
testhelpers.Equals(t, scw.Uint32Ptr(2048), updateResponse.Rule.DestPortTo)
testhelpers.Equals(t, SecurityGroupRuleProtocolUDP, updateResponse.Rule.Protocol)
testhelpers.Equals(t, SecurityGroupRuleDirectionOutbound, updateResponse.Rule.Direction)
})
t.Run("From a port range to a single port", func(t *testing.T) {
group, rule, cleanUp := bootstrap(t)
defer cleanUp()
_, ipNet, _ := net.ParseCIDR("1.1.1.1/32")
updateResponse, err := instanceAPI.UpdateSecurityGroupRule(&UpdateSecurityGroupRuleRequest{
SecurityGroupID: group.ID,
SecurityGroupRuleID: rule.ID,
Action: SecurityGroupRuleActionDrop,
IPRange: &scw.IPNet{IPNet: *ipNet},
DestPortFrom: scw.Uint32Ptr(22),
DestPortTo: scw.Uint32Ptr(22),
Protocol: SecurityGroupRuleProtocolUDP,
Direction: SecurityGroupRuleDirectionOutbound,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, SecurityGroupRuleActionDrop, updateResponse.Rule.Action)
testhelpers.Equals(t, scw.IPNet{IPNet: net.IPNet{IP: net.IPv4(0x1, 0x1, 0x1, 0x1), Mask: net.IPMask{0xff, 0xff, 0xff, 0xff}}}, updateResponse.Rule.IPRange)
testhelpers.Equals(t, uint32(22), *updateResponse.Rule.DestPortFrom)
testhelpers.Equals(t, (*uint32)(nil), updateResponse.Rule.DestPortTo)
testhelpers.Equals(t, SecurityGroupRuleProtocolUDP, updateResponse.Rule.Protocol)
testhelpers.Equals(t, SecurityGroupRuleDirectionOutbound, updateResponse.Rule.Direction)
})
t.Run("Switching to ICMP", func(t *testing.T) {
group, rule, cleanUp := bootstrap(t)
defer cleanUp()
updateResponse, err := instanceAPI.UpdateSecurityGroupRule(&UpdateSecurityGroupRuleRequest{
SecurityGroupID: group.ID,
SecurityGroupRuleID: rule.ID,
Protocol: SecurityGroupRuleProtocolICMP,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, SecurityGroupRuleActionAccept, updateResponse.Rule.Action)
testhelpers.Equals(t, scw.IPNet{IPNet: net.IPNet{IP: net.IPv4(0x8, 0x8, 0x8, 0x8), Mask: net.IPMask{0xff, 0xff, 0xff, 0xff}}}, updateResponse.Rule.IPRange)
testhelpers.Equals(t, (*uint32)(nil), updateResponse.Rule.DestPortFrom)
testhelpers.Equals(t, (*uint32)(nil), updateResponse.Rule.DestPortTo)
testhelpers.Equals(t, SecurityGroupRuleProtocolICMP, updateResponse.Rule.Protocol)
testhelpers.Equals(t, SecurityGroupRuleDirectionInbound, updateResponse.Rule.Direction)
})
t.Run("Remove ports", func(t *testing.T) {
group, rule, cleanUp := bootstrap(t)
defer cleanUp()
updateResponse, err := instanceAPI.UpdateSecurityGroupRule(&UpdateSecurityGroupRuleRequest{
SecurityGroupID: group.ID,
SecurityGroupRuleID: rule.ID,
DestPortFrom: scw.Uint32Ptr(0),
DestPortTo: scw.Uint32Ptr(0),
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, SecurityGroupRuleActionAccept, updateResponse.Rule.Action)
testhelpers.Equals(t, scw.IPNet{IPNet: net.IPNet{IP: net.IPv4(0x8, 0x8, 0x8, 0x8), Mask: net.IPMask{0xff, 0xff, 0xff, 0xff}}}, updateResponse.Rule.IPRange)
testhelpers.Equals(t, (*uint32)(nil), updateResponse.Rule.DestPortFrom)
testhelpers.Equals(t, (*uint32)(nil), updateResponse.Rule.DestPortTo)
testhelpers.Equals(t, SecurityGroupRuleProtocolTCP, updateResponse.Rule.Protocol)
testhelpers.Equals(t, SecurityGroupRuleDirectionInbound, updateResponse.Rule.Direction)
})
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/server_utils.go 0000664 0000000 0000000 00000024641 14747113137 0030233 0 ustar 00root root 0000000 0000000 package instance
import (
"bytes"
"fmt"
"io"
"net/http"
"time"
"github.com/scaleway/scaleway-sdk-go/api/marketplace/v2"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/scaleway-sdk-go/validation"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// CreateServer creates a server.
func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) {
// If image is not a UUID we try to fetch it from marketplace.
if req.Image != nil && !validation.IsUUID(*req.Image) {
apiMarketplace := marketplace.NewAPI(s.client)
image, err := apiMarketplace.GetLocalImageByLabel(&marketplace.GetLocalImageByLabelRequest{
ImageLabel: *req.Image,
Zone: req.Zone,
CommercialType: req.CommercialType,
})
if err != nil {
return nil, err
}
req.Image = scw.StringPtr(image.ID)
}
return s.createServer(req, opts...)
}
// UpdateServer updates a server.
//
// Note: Implementation is thread-safe.
func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) {
defer lockServer(req.Zone, req.ServerID).Unlock()
return s.updateServer(req, opts...)
}
// WaitForServerRequest is used by WaitForServer method.
type WaitForServerRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServer wait for the server to be in a "terminal state" before returning.
// This function can be used to wait for a server to be started for example.
func (s *API) WaitForServer(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerState]struct{}{
ServerStateStopped: {},
ServerStateStoppedInPlace: {},
ServerStateLocked: {},
ServerStateRunning: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Server.State]
return res.Server, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
// ServerActionAndWaitRequest is used by ServerActionAndWait method.
type ServerActionAndWaitRequest struct {
ServerID string
Zone scw.Zone
Action ServerAction
// Timeout: maximum time to wait before (default: 5 minutes)
Timeout *time.Duration
RetryInterval *time.Duration
}
// ServerActionAndWait start an action and wait for the server to be in the correct "terminal state"
// expected by this action.
func (s *API) ServerActionAndWait(req *ServerActionAndWaitRequest, opts ...scw.RequestOption) error {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
_, err := s.ServerAction(&ServerActionRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Action: req.Action,
}, opts...)
if err != nil {
return err
}
finalServer, err := s.WaitForServer(&WaitForServerRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Timeout: &timeout,
RetryInterval: &retryInterval,
}, opts...)
if err != nil {
return err
}
// check the action was properly executed
expectedState := ServerState("unknown")
switch req.Action {
case ServerActionPoweron, ServerActionReboot:
expectedState = ServerStateRunning
case ServerActionPoweroff:
expectedState = ServerStateStopped
case ServerActionStopInPlace:
expectedState = ServerStateStoppedInPlace
}
// backup can be performed from any state
if expectedState != ServerState("unknown") && finalServer.State != expectedState {
return errors.New("expected state %s but found %s: %s", expectedState, finalServer.State, finalServer.StateDetail)
}
return nil
}
// GetServerTypeRequest is used by GetServerType.
type GetServerTypeRequest struct {
Zone scw.Zone
Name string
}
// GetServerType get server type info by it's name.
func (s *API) GetServerType(req *GetServerTypeRequest) (*ServerType, error) {
res, err := s.ListServersTypes(&ListServersTypesRequest{
Zone: req.Zone,
}, scw.WithAllPages())
if err != nil {
return nil, err
}
if serverType, exist := res.Servers[req.Name]; exist {
return serverType, nil
}
return nil, errors.New("could not find server type %q", req.Name)
}
// GetServerUserDataRequest is used by GetServerUserData method.
type GetServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// Key defines the user data key to get.
Key string `json:"-"`
}
// GetServerUserData gets the content of a user data on a server for the given key.
func (s *API) GetServerUserData(req *GetServerUserDataRequest, opts ...scw.RequestOption) (io.Reader, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Zone == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if req.ServerID == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if req.Key == "" {
return nil, errors.New("field Key cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + req.ServerID + "/user_data/" + req.Key,
Headers: http.Header{},
}
res := &bytes.Buffer{}
err = s.client.Do(scwReq, res, opts...)
if err != nil {
return nil, err
}
return res, nil
}
// SetServerUserDataRequest is used by SetServerUserData method.
type SetServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// Key defines the user data key to set.
Key string `json:"-"`
// Content defines the data to set.
Content io.Reader
}
// SetServerUserData sets the content of a user data on a server for the given key.
func (s *API) SetServerUserData(req *SetServerUserDataRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Zone == "" {
return errors.New("field Zone cannot be empty in request")
}
if req.ServerID == "" {
return errors.New("field ServerID cannot be empty in request")
}
if req.Key == "" {
return errors.New("field Key cannot be empty in request")
}
if req.Content == nil {
return errors.New("field Content cannot be nil in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + req.ServerID + "/user_data/" + req.Key,
Headers: http.Header{},
}
err = scwReq.SetBody(req.Content)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetAllServerUserDataRequest is used by GetAllServerUserData method.
type GetAllServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
}
// GetAllServerUserDataResponse is used by GetAllServerUserData method.
type GetAllServerUserDataResponse struct {
UserData map[string]io.Reader `json:"-"`
}
// GetAllServerUserData gets all user data on a server.
func (s *API) GetAllServerUserData(req *GetAllServerUserDataRequest, opts ...scw.RequestOption) (*GetAllServerUserDataResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if req.ServerID == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
// get all user data keys
allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
}, opts...)
if err != nil {
return nil, err
}
res := &GetAllServerUserDataResponse{
UserData: make(map[string]io.Reader, len(allUserDataRes.UserData)),
}
// build a map with all user data
for _, key := range allUserDataRes.UserData {
value, err := s.GetServerUserData(&GetServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
}, opts...)
if err != nil {
return nil, err
}
res.UserData[key] = value
}
return res, nil
}
// SetAllServerUserDataRequest is used by SetAllServerUserData method.
type SetAllServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// UserData defines all user data that will be set to the server.
// This map is idempotent, it means that all the current data will be overwritten and
// all keys not present in this map will be deleted.. All data will be removed if this map is nil.
UserData map[string]io.Reader `json:"-"`
}
// SetAllServerUserData sets all user data on a server, it deletes every keys previously set.
func (s *API) SetAllServerUserData(req *SetAllServerUserDataRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Zone == "" {
return errors.New("field Zone cannot be empty in request")
}
if req.ServerID == "" {
return errors.New("field ServerID cannot be empty in request")
}
// get all current user data keys
allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
}, opts...)
if err != nil {
return err
}
// delete all current user data
for _, key := range allUserDataRes.UserData {
_, exist := req.UserData[key]
if exist {
continue
}
err := s.DeleteServerUserData(&DeleteServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
}, opts...)
if err != nil {
return err
}
}
// set all new user data
for key, value := range req.UserData {
err := s.SetServerUserData(&SetServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
Content: value,
}, opts...)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/server_utils_test.go 0000664 0000000 0000000 00000011530 14747113137 0031263 0 ustar 00root root 0000000 0000000 package instance
import (
"bytes"
"io"
"strings"
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestAPI_GetServerType(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("get-server-type")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
serverType, err := instanceAPI.GetServerType(&GetServerTypeRequest{
Zone: scw.ZoneFrPar1,
Name: "GP1-XS",
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, 1*scw.GB, serverType.PerVolumeConstraint.LSSD.MinSize)
testhelpers.Equals(t, 800*scw.GB, serverType.PerVolumeConstraint.LSSD.MaxSize)
}
func TestAPI_ServerUserData(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("server-user-data")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
key := "hello"
contentStr := "world"
serverRes, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "DEV1-S",
Name: namegenerator.GetRandomName("srv"),
Image: scw.StringPtr("f974feac-abae-4365-b988-8ec7d1cec10d"),
Project: scw.StringPtr("14d2f7ae-9775-414c-9bed-6810e060d500"),
})
testhelpers.AssertNoError(t, err)
content := strings.NewReader(contentStr)
err = instanceAPI.SetServerUserData(&SetServerUserDataRequest{
Zone: scw.ZoneFrPar1,
ServerID: serverRes.Server.ID,
Key: key,
Content: content,
})
testhelpers.AssertNoError(t, err)
data, err := instanceAPI.GetServerUserData(&GetServerUserDataRequest{
Zone: scw.ZoneFrPar1,
ServerID: serverRes.Server.ID,
Key: key,
})
testhelpers.AssertNoError(t, err)
resUserData, err := io.ReadAll(data)
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, contentStr, string(resUserData))
}
func TestAPI_AllServerUserData(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("all-server-user-data")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
serverRes, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "DEV1-S",
Name: namegenerator.GetRandomName("srv"),
Image: scw.StringPtr("f974feac-abae-4365-b988-8ec7d1cec10d"),
Project: scw.StringPtr("14d2f7ae-9775-414c-9bed-6810e060d500"),
})
testhelpers.AssertNoError(t, err)
steps := []map[string]string{
{
"hello": "world",
"scale": "way",
"tic": "tac",
"cloud-init": "on",
},
{
"scale": "way",
"steve": "wozniak",
"cloud-init": "off",
},
{},
}
for _, data := range steps {
// create user data
userData := make(map[string]io.Reader, len(data))
for k, v := range data {
userData[k] = bytes.NewBufferString(v)
}
// set all user data
err := instanceAPI.SetAllServerUserData(&SetAllServerUserDataRequest{
Zone: scw.ZoneFrPar1,
ServerID: serverRes.Server.ID,
UserData: userData,
})
testhelpers.AssertNoError(t, err)
// get all user data
allData, err := instanceAPI.GetAllServerUserData(&GetAllServerUserDataRequest{
Zone: scw.ZoneFrPar1,
ServerID: serverRes.Server.ID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, len(data), len(allData.UserData))
for expectedKey, expectedValue := range data {
currentReader, exists := allData.UserData[expectedKey]
testhelpers.Assert(t, exists, "%s key not found in result", expectedKey)
currentValue, err := io.ReadAll(currentReader)
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, expectedValue, string(currentValue))
}
}
}
func TestAPI_CreateServer(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("create-server")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
res, err := instanceAPI.CreateServer(&CreateServerRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "GP1-XS",
Image: scw.StringPtr("ubuntu_focal"),
})
testhelpers.AssertNoError(t, err)
// this UUID might change when running the cassette later when the image "ubuntu_focal" got a new version
testhelpers.Equals(t, "9c41e95b-add2-4ef8-b1b1-af8899748eda", res.Server.Image.ID)
err = instanceAPI.DeleteServer(&DeleteServerRequest{
Zone: scw.ZoneFrPar1,
ServerID: res.Server.ID,
})
testhelpers.AssertNoError(t, err)
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/snapshot_utils.go 0000664 0000000 0000000 00000002675 14747113137 0030567 0 ustar 00root root 0000000 0000000 package instance
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForImageRequest is used by WaitForImage method.
type WaitForSnapshotRequest struct {
SnapshotID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForSnapshot wait for the snapshot to be in a "terminal state" before returning.
func (s *API) WaitForSnapshot(req *WaitForSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[SnapshotState]struct{}{
SnapshotStateAvailable: {},
SnapshotStateError: {},
}
snapshot, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetSnapshot(&GetSnapshotRequest{
SnapshotID: req.SnapshotID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Snapshot.State]
return res.Snapshot, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for snapshot failed")
}
return snapshot.(*Snapshot), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/snapshot_utils_test.go 0000664 0000000 0000000 00000006604 14747113137 0031622 0 ustar 00root root 0000000 0000000 package instance
import (
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestWaitForSnapshot(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("snapshot-wait-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
snapshotName := "backup"
snapshot, cleanup := createSnapshot(t, instanceAPI, snapshotName)
defer cleanup()
res, err := instanceAPI.WaitForSnapshot(&WaitForSnapshotRequest{
SnapshotID: snapshot.ID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, snapshot.ID, res.ID)
testhelpers.Equals(t, SnapshotStateAvailable, res.State)
testhelpers.Equals(t, snapshotName, res.Name)
}
// createSnapshot is a helper that create an snapshot.
// It returns the newly created snapshot and a cleanup function
func createSnapshot(t *testing.T, instanceAPI *API, snapshotName string) (*Snapshot, func()) {
t.Helper()
serverRes, err := instanceAPI.CreateServer(&CreateServerRequest{
CommercialType: "DEV1-M",
Image: scw.StringPtr("ubuntu_focal"),
})
testhelpers.AssertNoError(t, err)
// Backup will create a snapshot for each volume + an image base on all snapshots.
snapshot, err := instanceAPI.CreateSnapshot(&CreateSnapshotRequest{
Name: snapshotName,
VolumeID: &serverRes.Server.Volumes["0"].ID,
})
testhelpers.AssertNoError(t, err)
snapshotRes, err := instanceAPI.GetSnapshot(&GetSnapshotRequest{
SnapshotID: snapshot.Snapshot.ID,
})
testhelpers.AssertNoError(t, err)
return snapshotRes.Snapshot, func() {
// Delete all created resources
err := instanceAPI.DeleteServer(&DeleteServerRequest{
ServerID: serverRes.Server.ID,
})
testhelpers.AssertNoError(t, err)
err = instanceAPI.DeleteSnapshot(&DeleteSnapshotRequest{
SnapshotID: snapshotRes.Snapshot.ID,
})
testhelpers.AssertNoError(t, err)
}
}
func TestAPI_UpdateSnapshot(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("snapshot-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
volumeSize := 1 * scw.GB
createVolume, err := instanceAPI.CreateVolume(&CreateVolumeRequest{
Name: "volume_name",
VolumeType: VolumeVolumeTypeBSSD,
Size: &volumeSize,
})
testhelpers.AssertNoError(t, err)
createResponse, err := instanceAPI.CreateSnapshot(&CreateSnapshotRequest{
Name: "name",
VolumeID: &createVolume.Volume.ID,
})
testhelpers.AssertNoError(t, err)
updateResponse, err := instanceAPI.UpdateSnapshot(&UpdateSnapshotRequest{
SnapshotID: createResponse.Snapshot.ID,
Name: scw.StringPtr("new_name"),
Tags: scw.StringsPtr([]string{"foo", "bar"}),
})
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, "new_name", updateResponse.Snapshot.Name)
testhelpers.Equals(t, []string{"foo", "bar"}, updateResponse.Snapshot.Tags)
_, err = instanceAPI.WaitForSnapshot(&WaitForSnapshotRequest{
SnapshotID: createResponse.Snapshot.ID,
})
testhelpers.AssertNoError(t, err)
err = instanceAPI.DeleteSnapshot(&DeleteSnapshotRequest{
SnapshotID: createResponse.Snapshot.ID,
})
testhelpers.AssertNoError(t, err)
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027004 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000013723 14747113137 0031176 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/instance/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepVolumes(scwClient *scw.Client, zone scw.Zone) error {
instanceAPI := instance.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the volumes in (%s)", zone)
listVolumesResponse, err := instanceAPI.ListVolumes(&instance.ListVolumesRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing volumes in sweeper: %s", err)
}
for _, volume := range listVolumesResponse.Volumes {
if volume.Server == nil {
err := instanceAPI.DeleteVolume(&instance.DeleteVolumeRequest{
Zone: zone,
VolumeID: volume.ID,
})
if err != nil {
return fmt.Errorf("error deleting volume in sweeper: %s", err)
}
}
}
return nil
}
func SweepSnapshots(scwClient *scw.Client, zone scw.Zone) error {
api := instance.NewAPI(scwClient)
logger.Warningf("sweeper: destroying instance snapshots in (%+v)", zone)
listSnapshotsResponse, err := api.ListSnapshots(&instance.ListSnapshotsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing instance snapshots in sweeper: %w", err)
}
for _, snapshot := range listSnapshotsResponse.Snapshots {
err := api.DeleteSnapshot(&instance.DeleteSnapshotRequest{
Zone: zone,
SnapshotID: snapshot.ID,
})
if err != nil {
return fmt.Errorf("error deleting instance snapshot in sweeper: %w", err)
}
}
return nil
}
func SweepServers(scwClient *scw.Client, zone scw.Zone) error {
instanceAPI := instance.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the instance server in (%s)", zone)
listServers, err := instanceAPI.ListServers(&instance.ListServersRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
logger.Warningf("error listing servers in (%s) in sweeper: %s", zone, err)
return nil
}
for _, srv := range listServers.Servers {
if srv.State == instance.ServerStateStopped || srv.State == instance.ServerStateStoppedInPlace {
err := instanceAPI.DeleteServer(&instance.DeleteServerRequest{
Zone: zone,
ServerID: srv.ID,
})
if err != nil {
return fmt.Errorf("error deleting server in sweeper: %s", err)
}
} else if srv.State == instance.ServerStateRunning {
_, err := instanceAPI.ServerAction(&instance.ServerActionRequest{
Zone: zone,
ServerID: srv.ID,
Action: instance.ServerActionTerminate,
})
if err != nil {
return fmt.Errorf("error terminating server in sweeper: %s", err)
}
}
}
return nil
}
func SweepSecurityGroups(scwClient *scw.Client, zone scw.Zone) error {
instanceAPI := instance.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the security groups in (%s)", zone)
listResp, err := instanceAPI.ListSecurityGroups(&instance.ListSecurityGroupsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
logger.Warningf("error listing security groups in sweeper: %s", err)
return nil
}
for _, securityGroup := range listResp.SecurityGroups {
// Can't delete default security group.
if securityGroup.ProjectDefault {
continue
}
err = instanceAPI.DeleteSecurityGroup(&instance.DeleteSecurityGroupRequest{
Zone: zone,
SecurityGroupID: securityGroup.ID,
})
if err != nil {
return fmt.Errorf("error deleting security groups in sweeper: %s", err)
}
}
return nil
}
func SweepPlacementGroup(scwClient *scw.Client, zone scw.Zone) error {
instanceAPI := instance.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the instance placement group in (%s)", zone)
listPlacementGroups, err := instanceAPI.ListPlacementGroups(&instance.ListPlacementGroupsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
logger.Warningf("error listing placement groups in (%s) in sweeper: %s", zone, err)
return nil
}
for _, pg := range listPlacementGroups.PlacementGroups {
err := instanceAPI.DeletePlacementGroup(&instance.DeletePlacementGroupRequest{
Zone: zone,
PlacementGroupID: pg.ID,
})
if err != nil {
return fmt.Errorf("error deleting placement group in sweeper: %s", err)
}
}
return nil
}
func SweepIP(scwClient *scw.Client, zone scw.Zone) error {
instanceAPI := instance.NewAPI(scwClient)
listIPs, err := instanceAPI.ListIPs(&instance.ListIPsRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
logger.Warningf("error listing ips in (%s) in sweeper: %s", zone, err)
return nil
}
for _, ip := range listIPs.IPs {
err := instanceAPI.DeleteIP(&instance.DeleteIPRequest{
IP: ip.ID,
Zone: zone,
})
if err != nil {
return fmt.Errorf("error deleting ip in sweeper: %s", err)
}
}
return nil
}
func SweepImages(scwClient *scw.Client, zone scw.Zone) error {
api := instance.NewAPI(scwClient)
logger.Debugf("sweeper: destroying instance images in (%+v)", zone)
listImagesResponse, err := api.ListImages(&instance.ListImagesRequest{
Zone: zone,
Public: scw.BoolPtr(false),
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing instance images in sweeper: %w", err)
}
for _, image := range listImagesResponse.Images {
err := api.DeleteImage(&instance.DeleteImageRequest{
Zone: zone,
ImageID: image.ID,
})
if err != nil {
return fmt.Errorf("error deleting instance image in sweeper: %w", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&instance.API{}).Zones() {
err := SweepVolumes(scwClient, zone)
if err != nil {
return err
}
err = SweepSnapshots(scwClient, zone)
if err != nil {
return err
}
err = SweepServers(scwClient, zone)
if err != nil {
return err
}
err = SweepSecurityGroups(scwClient, zone)
if err != nil {
return err
}
err = SweepPlacementGroup(scwClient, zone)
if err != nil {
return err
}
err = SweepIP(scwClient, zone)
if err != nil {
return err
}
err = SweepImages(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/ 0000775 0000000 0000000 00000000000 14747113137 0026760 5 ustar 00root root 0000000 0000000 all-server-user-data.yaml 0000664 0000000 0000000 00000060605 14747113137 0033533 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata ---
version: 1
interactions:
- request:
body: '{"name":"srv-hardcore-raman","commercial_type":"DEV1-S","image":"f974feac-abae-4365-b988-8ec7d1cec10d","organization":"14d2f7ae-9775-414c-9bed-6810e060d500"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"allowed_actions": ["poweron", "backup"], "maintenances": [],
"state_detail": "", "image": {"creation_date": "2019-03-05T10:13:15.974944+00:00",
"default_bootscript": {"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz", "default":
false, "bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "architecture":
"x86_64", "title": "x86_64 mainline 4.9.93 rev1", "dtb": "", "organization":
"11111111-1111-4111-8111-111111111111", "id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false}, "from_server": null, "arch": "x86_64", "id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"root_volume": {"size": 10000000000, "id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"volume_type": "l_ssd", "name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13"},
"name": "Ubuntu Bionic Beaver", "modification_date": "2019-03-05T13:32:29.274319+00:00",
"state": "available", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"extra_volumes": {}, "public": true}, "creation_date": "2019-06-24T17:26:47.674533+00:00",
"public_ip": null, "private_ip": null, "id": "b2266f9f-d089-41be-84b7-0bd9690fc505",
"dynamic_ip_required": true, "modification_date": "2019-06-24T17:26:47.987175+00:00",
"enable_ipv6": false, "hostname": "srv-hardcore-raman", "state": "stopped",
"bootscript": {"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz", "default":
false, "bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "architecture":
"x86_64", "title": "x86_64 mainline 4.9.93 rev1", "dtb": "", "organization":
"11111111-1111-4111-8111-111111111111", "id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false}, "location": null, "boot_type": "local", "ipv6": null, "commercial_type":
"DEV1-S", "tags": [], "arch": "x86_64", "extra_networks": [], "compute_cluster":
null, "name": "srv-hardcore-raman", "protected": false, "volumes": {"0": {"size":
20000000000, "state": "available", "name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13",
"modification_date": "2019-06-24T17:26:47.901572+00:00", "organization": "14d2f7ae-9775-414c-9bed-6810e060d500",
"export_uri": null, "creation_date": "2019-06-24T17:26:47.674533+00:00", "id":
"29d7d72b-f566-4282-bb60-ab604028e3f6", "volume_type": "l_ssd", "server": {"id":
"b2266f9f-d089-41be-84b7-0bd9690fc505", "name": "srv-hardcore-raman"}}}, "security_group":
{"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af", "name": "Default security group"},
"organization": "14d2f7ae-9775-414c-9bed-6810e060d500"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "2706"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:47 GMT
Location:
- https://cp-par1.scaleway.com/servers/b2266f9f-d089-41be-84b7-0bd9690fc505
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 201 Created
code: 201
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": []}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "17"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:47 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: way
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: tac
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/tic
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: "on"
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: world
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/hello
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": ["cloud-init", "hello", "scale", "tic"]}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "64"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: GET
response:
body: "on"
headers:
Cache-Control:
- no-cache
Content-Length:
- "2"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/hello
method: GET
response:
body: world
headers:
Cache-Control:
- no-cache
Content-Length:
- "5"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: GET
response:
body: way
headers:
Cache-Control:
- no-cache
Content-Length:
- "3"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/tic
method: GET
response:
body: tac
headers:
Cache-Control:
- no-cache
Content-Length:
- "3"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": ["cloud-init", "hello", "scale", "tic"]}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "64"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/hello
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:48 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/tic
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: wozniak
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/steve
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: "off"
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: way
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": ["cloud-init", "scale", "steve"]}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "57"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: GET
response:
body: "off"
headers:
Cache-Control:
- no-cache
Content-Length:
- "3"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: GET
response:
body: way
headers:
Cache-Control:
- no-cache
Content-Length:
- "3"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/steve
method: GET
response:
body: wozniak
headers:
Cache-Control:
- no-cache
Content-Length:
- "7"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": ["cloud-init", "scale", "steve"]}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "57"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:49 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/cloud-init
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:50 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/scale
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:50 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data/steve
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:50 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/b2266f9f-d089-41be-84b7-0bd9690fc505/user_data
method: GET
response:
body: '{"user_data": []}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "17"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 24 Jun 2019 17:26:50 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/create-server.yaml 0000664 0000000 0000000 00000017343 14747113137 0032423 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=ubuntu_focal&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"local_images":[{"id":"19f37e3e-d8c4-43cb-a739-7ccefec2a489","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"9c41e95b-add2-4ef8-b1b1-af8899748eda","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"1de03aca-1106-4152-bd36-f057c0cce9f1","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_sbs"},{"id":"60dd2959-89ce-4636-b54d-f1bb2ce9bde8","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_sbs"}],"total_count":4}'
headers:
Content-Length:
- "2328"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:32:10 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 6d100b8a-5b13-4c9e-bc11-9733c577e898
status: 200 OK
code: 200
duration: ""
- request:
body: '{"name":"srv-ecstatic-saha","commercial_type":"GP1-XS","image":"9c41e95b-add2-4ef8-b1b1-af8899748eda","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "973c6deb-c4c4-47e9-b9b9-62fdd812fb42", "name": "srv-ecstatic-saha",
"arch": "x86_64", "commercial_type": "GP1-XS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "srv-ecstatic-saha", "image": {"id": "9c41e95b-add2-4ef8-b1b1-af8899748eda",
"name": "Ubuntu 20.04 Focal Fossa", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "f7bff04a-ee32-4bf5-ae53-2280e11d8977",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2024-07-03T19:59:39.939165+00:00",
"modification_date": "2024-07-03T19:59:39.939165+00:00", "default_bootscript":
null, "from_server": "", "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "36886cc7-3ef4-4cbf-9f33-7dad4a30d987",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "l_ssd", "export_uri": null,
"organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "973c6deb-c4c4-47e9-b9b9-62fdd812fb42", "name": "srv-ecstatic-saha"},
"size": 150000000000, "state": "available", "creation_date": "2024-07-05T09:32:10.284203+00:00",
"modification_date": "2024-07-05T09:32:10.284203+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:5f:9a:41",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-07-05T09:32:10.284203+00:00",
"modification_date": "2024-07-05T09:32:10.284203+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2610"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:32:10 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/973c6deb-c4c4-47e9-b9b9-62fdd812fb42
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 268eec6d-1c3c-4c02-80e4-1466777e1533
status: 201 Created
code: 201
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/973c6deb-c4c4-47e9-b9b9-62fdd812fb42
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:32:10 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b492939b-85ad-43ba-b34a-7ea96c4e91b5
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/get-server-type.yaml 0000664 0000000 0000000 00000060162 14747113137 0032713 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/products/servers?page=1
method: GET
response:
body: '{"servers": {"VC1S": {"monthly_price": 2.99, "per_volume_constraint": {"l_ssd":
{"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 2, "ram": 2147483648,
"arch": "x86_64", "volumes_constraint": {"min_size": 50000000000, "max_size":
50000000000}, "network": {"interfaces": [{"internal_bandwidth": null, "internet_bandwidth":
209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth": 209715200,
"ipv6_support": true}, "hourly_price": 0.006, "alt_names": ["X64-2GB"], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "GP1-XS": {"monthly_price": 39.0, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 4, "ram":
17179869184, "arch": "x86_64", "volumes_constraint": {"min_size": 150000000000,
"max_size": 150000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 419430400}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
419430400, "ipv6_support": true}, "hourly_price": 0.078, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "DEV1-M": {"monthly_price": 7.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 3, "ram":
4294967296, "arch": "x86_64", "volumes_constraint": {"min_size": 40000000000,
"max_size": 40000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.016, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "DEV1-L": {"monthly_price": 15.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}},
"ncpus": 4, "ram": 8589934592, "arch": "x86_64", "volumes_constraint": {"min_size":
80000000000, "max_size": 80000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 314572800}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
314572800, "ipv6_support": true}, "hourly_price": 0.032, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "START1-XS": {"monthly_price": 1.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 1, "ram": 1073741824, "arch": "x86_64", "volumes_constraint": {"min_size":
25000000000, "max_size": 25000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 104857600}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
104857600, "ipv6_support": true}, "hourly_price": 0.004, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "ARM64-8GB": {"monthly_price": 11.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 8, "ram": 8589934592, "arch": "arm64", "volumes_constraint": {"min_size":
200000000000, "max_size": 200000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.024, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "DEV1-S": {"monthly_price": 2.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 2, "ram":
2147483648, "arch": "x86_64", "volumes_constraint": {"min_size": 20000000000,
"max_size": 20000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 104857600}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
104857600, "ipv6_support": true}, "hourly_price": 0.006, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "RENDER-S": {"monthly_price": 499.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}},
"ncpus": 10, "ram": 48318382080, "arch": "x86_64", "volumes_constraint": {"min_size":
400000000000, "max_size": 400000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1048576000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1048576000, "ipv6_support": true}, "hourly_price": 1.0, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["local",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": 1}, "GP1-XL": {"monthly_price": 569.0, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 48,
"ram": 274877906944, "arch": "x86_64", "volumes_constraint": {"min_size": 600000000000,
"max_size": 600000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 2147483648}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
2147483648, "ipv6_support": true}, "hourly_price": 1.138, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "C2S": {"monthly_price": 11.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 4, "ram":
8589934592, "arch": "x86_64", "volumes_constraint": {"min_size": 50000000000,
"max_size": 1000000000000}, "network": {"interfaces": [{"internal_bandwidth":
2684354560, "internet_bandwidth": 314572800}], "sum_internal_bandwidth": 2684354560,
"sum_internet_bandwidth": 314572800, "ipv6_support": true}, "hourly_price":
0.024, "alt_names": [], "capabilities": {"block_storage": false, "default_boot_type":
"bootscript", "boot_types": ["bootscript", "rescue"], "hot_snapshots_local_volume":
false, "compute_clusters": false}, "baremetal": true, "gpu": null}, "X64-15GB":
{"monthly_price": 24.99, "per_volume_constraint": {"l_ssd": {"min_size": 1000000000,
"max_size": 200000000000}}, "ncpus": 6, "ram": 16106127360, "arch": "x86_64",
"volumes_constraint": {"min_size": 200000000000, "max_size": 200000000000},
"network": {"interfaces": [{"internal_bandwidth": null, "internet_bandwidth":
262144000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth": 262144000,
"ipv6_support": true}, "hourly_price": 0.05, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "ARM64-2GB": {"monthly_price": 2.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 4, "ram": 2147483648, "arch": "arm64", "volumes_constraint": {"min_size":
50000000000, "max_size": 50000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.006, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "DEV1-XL": {"monthly_price": 23.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 4, "ram":
12884901888, "arch": "x86_64", "volumes_constraint": {"min_size": 120000000000,
"max_size": 120000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 419430400}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
419430400, "ipv6_support": true}, "hourly_price": 0.048, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "C1": {"monthly_price": 2.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 4, "ram":
2147483648, "arch": "arm", "volumes_constraint": {"min_size": 50000000000, "max_size":
1000000000000}, "network": {"interfaces": [{"internal_bandwidth": 1073741824,
"internet_bandwidth": 209715200}], "sum_internal_bandwidth": 1073741824, "sum_internet_bandwidth":
209715200, "ipv6_support": false}, "hourly_price": 0.006, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": false, "compute_clusters": false},
"baremetal": true, "gpu": null}, "VC1M": {"monthly_price": 5.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 4, "ram":
4294967296, "arch": "x86_64", "volumes_constraint": {"min_size": 100000000000,
"max_size": 100000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.012, "alt_names": ["X64-4GB"],
"capabilities": {"block_storage": false, "default_boot_type": "bootscript",
"boot_types": ["bootscript", "rescue", "local"], "hot_snapshots_local_volume":
true, "compute_clusters": true}, "baremetal": false, "gpu": null}, "C2L": {"monthly_price":
23.99, "per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size":
200000000000}}, "ncpus": 8, "ram": 34359738368, "arch": "x86_64", "volumes_constraint":
{"min_size": 50000000000, "max_size": 1000000000000}, "network": {"interfaces":
[{"internal_bandwidth": 2684354560, "internet_bandwidth": 629145600}, {"internal_bandwidth":
2684354560, "internet_bandwidth": null}], "sum_internal_bandwidth": 5368709120,
"sum_internet_bandwidth": 629145600, "ipv6_support": true}, "hourly_price":
0.048, "alt_names": [], "capabilities": {"block_storage": false, "default_boot_type":
"bootscript", "boot_types": ["bootscript", "rescue"], "hot_snapshots_local_volume":
false, "compute_clusters": false}, "baremetal": true, "gpu": null}, "C2M": {"monthly_price":
17.99, "per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size":
200000000000}}, "ncpus": 8, "ram": 17179869184, "arch": "x86_64", "volumes_constraint":
{"min_size": 50000000000, "max_size": 1000000000000}, "network": {"interfaces":
[{"internal_bandwidth": 2684354560, "internet_bandwidth": 524288000}, {"internal_bandwidth":
2684354560, "internet_bandwidth": null}], "sum_internal_bandwidth": 5368709120,
"sum_internet_bandwidth": 524288000, "ipv6_support": true}, "hourly_price":
0.036, "alt_names": [], "capabilities": {"block_storage": false, "default_boot_type":
"bootscript", "boot_types": ["bootscript", "rescue"], "hot_snapshots_local_volume":
false, "compute_clusters": false}, "baremetal": true, "gpu": null}, "ARM64-4GB":
{"monthly_price": 5.99, "per_volume_constraint": {"l_ssd": {"min_size": 1000000000,
"max_size": 200000000000}}, "ncpus": 6, "ram": 4294967296, "arch": "arm64",
"volumes_constraint": {"min_size": 100000000000, "max_size": 100000000000},
"network": {"interfaces": [{"internal_bandwidth": null, "internet_bandwidth":
209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth": 209715200,
"ipv6_support": true}, "hourly_price": 0.012, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "ARM64-128GB": {"monthly_price": 279.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 64,
"ram": 137438953472, "arch": "arm64", "volumes_constraint": {"min_size": 500000000000,
"max_size": 1000000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1073741824}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1073741824, "ipv6_support": true}, "hourly_price": 0.56, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "START1-S": {"monthly_price": 3.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 2, "ram":
2147483648, "arch": "x86_64", "volumes_constraint": {"min_size": 50000000000,
"max_size": 50000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.008, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "X64-30GB": {"monthly_price": 49.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 8, "ram": 32212254720, "arch": "x86_64", "volumes_constraint": {"min_size":
300000000000, "max_size": 400000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 524288000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
524288000, "ipv6_support": true}, "hourly_price": 0.1, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "GP1-L": {"monthly_price": 299.0, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 32,
"ram": 137438953472, "arch": "x86_64", "volumes_constraint": {"min_size": 600000000000,
"max_size": 600000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1073741824}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1073741824, "ipv6_support": true}, "hourly_price": 0.598, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "GP1-M": {"monthly_price": 159.0, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 16,
"ram": 68719476736, "arch": "x86_64", "volumes_constraint": {"min_size": 600000000000,
"max_size": 600000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 629145600}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
629145600, "ipv6_support": true}, "hourly_price": 0.318, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "ARM64-64GB": {"monthly_price": 139.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 48, "ram": 68719476736, "arch": "arm64", "volumes_constraint": {"min_size":
400000000000, "max_size": 800000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1073741824}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1073741824, "ipv6_support": true}, "hourly_price": 0.28, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "GP1-S": {"monthly_price": 79.0, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 800000000000}}, "ncpus": 8, "ram":
34359738368, "arch": "x86_64", "volumes_constraint": {"min_size": 300000000000,
"max_size": 300000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 524288000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
524288000, "ipv6_support": true}, "hourly_price": 0.158, "alt_names": [], "capabilities":
{"block_storage": true, "default_boot_type": "local", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "START1-L": {"monthly_price": 15.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 8, "ram": 8589934592, "arch": "x86_64", "volumes_constraint": {"min_size":
200000000000, "max_size": 200000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 419430400}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
419430400, "ipv6_support": true}, "hourly_price": 0.032, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "START1-M": {"monthly_price": 7.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 4, "ram": 4294967296, "arch": "x86_64", "volumes_constraint": {"min_size":
100000000000, "max_size": 100000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 314572800}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
314572800, "ipv6_support": true}, "hourly_price": 0.016, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "VC1L": {"monthly_price": 9.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 6, "ram":
8589934592, "arch": "x86_64", "volumes_constraint": {"min_size": 200000000000,
"max_size": 200000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 209715200}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
209715200, "ipv6_support": true}, "hourly_price": 0.02, "alt_names": ["X64-8GB"],
"capabilities": {"block_storage": false, "default_boot_type": "bootscript",
"boot_types": ["bootscript", "rescue", "local"], "hot_snapshots_local_volume":
true, "compute_clusters": true}, "baremetal": false, "gpu": null}, "ARM64-32GB":
{"monthly_price": 69.99, "per_volume_constraint": {"l_ssd": {"min_size": 1000000000,
"max_size": 200000000000}}, "ncpus": 32, "ram": 34359738368, "arch": "arm64",
"volumes_constraint": {"min_size": 300000000000, "max_size": 600000000000},
"network": {"interfaces": [{"internal_bandwidth": null, "internet_bandwidth":
524288000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth": 524288000,
"ipv6_support": true}, "hourly_price": 0.14, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "X64-120GB": {"monthly_price": 179.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 12,
"ram": 128849018880, "arch": "x86_64", "volumes_constraint": {"min_size": 500000000000,
"max_size": 1000000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1073741824}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1073741824, "ipv6_support": true}, "hourly_price": 0.36, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}, "ARM64-16GB": {"monthly_price": 34.99,
"per_volume_constraint": {"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}},
"ncpus": 16, "ram": 17179869184, "arch": "arm64", "volumes_constraint": {"min_size":
200000000000, "max_size": 400000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 524288000}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
524288000, "ipv6_support": true}, "hourly_price": 0.07, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue"], "hot_snapshots_local_volume": true, "compute_clusters": true}, "baremetal":
false, "gpu": null}, "X64-60GB": {"monthly_price": 89.99, "per_volume_constraint":
{"l_ssd": {"min_size": 1000000000, "max_size": 200000000000}}, "ncpus": 10,
"ram": 64424509440, "arch": "x86_64", "volumes_constraint": {"min_size": 400000000000,
"max_size": 700000000000}, "network": {"interfaces": [{"internal_bandwidth":
null, "internet_bandwidth": 1073741824}], "sum_internal_bandwidth": null, "sum_internet_bandwidth":
1073741824, "ipv6_support": true}, "hourly_price": 0.18, "alt_names": [], "capabilities":
{"block_storage": false, "default_boot_type": "bootscript", "boot_types": ["bootscript",
"rescue", "local"], "hot_snapshots_local_volume": true, "compute_clusters":
true}, "baremetal": false, "gpu": null}}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "22248"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Tue, 18 Jun 2019 13:56:00 GMT
Link:
- ; rel="last"
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Total-Count:
- "32"
status: 200 OK
code: 200
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/image-wait-test.yaml 0000664 0000000 0000000 00000036614 14747113137 0032657 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=ubuntu_focal&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"local_images":[{"id":"19f37e3e-d8c4-43cb-a739-7ccefec2a489","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"9c41e95b-add2-4ef8-b1b1-af8899748eda","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"1de03aca-1106-4152-bd36-f057c0cce9f1","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_sbs"},{"id":"60dd2959-89ce-4636-b54d-f1bb2ce9bde8","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_sbs"}],"total_count":4}'
headers:
Content-Length:
- "2328"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:07 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- cffd7dda-2c89-41cc-bc25-04dd411a214f
status: 200 OK
code: 200
duration: ""
- request:
body: '{"name":"srv-competent-benz","commercial_type":"DEV1-M","image":"9c41e95b-add2-4ef8-b1b1-af8899748eda","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "9e9c098b-8d80-4afc-bbb7-1e27fddf0702", "name": "srv-competent-benz",
"arch": "x86_64", "commercial_type": "DEV1-M", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "srv-competent-benz", "image": {"id": "9c41e95b-add2-4ef8-b1b1-af8899748eda",
"name": "Ubuntu 20.04 Focal Fossa", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "f7bff04a-ee32-4bf5-ae53-2280e11d8977",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2024-07-03T19:59:39.939165+00:00",
"modification_date": "2024-07-03T19:59:39.939165+00:00", "default_bootscript":
null, "from_server": "", "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "e3fc3664-2f32-4946-b3b1-710b607e6f8e",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "l_ssd", "export_uri": null,
"organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "9e9c098b-8d80-4afc-bbb7-1e27fddf0702", "name": "srv-competent-benz"},
"size": 40000000000, "state": "available", "creation_date": "2024-07-05T09:33:07.592750+00:00",
"modification_date": "2024-07-05T09:33:07.592750+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:5f:9a:4f",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-07-05T09:33:07.592750+00:00",
"modification_date": "2024-07-05T09:33:07.592750+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2612"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:07 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/9e9c098b-8d80-4afc-bbb7-1e27fddf0702
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 8cb58097-3dcc-47ce-b148-3aec9e5b45ca
status: 201 Created
code: 201
duration: ""
- request:
body: '{"action":"backup","name":"backup"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/9e9c098b-8d80-4afc-bbb7-1e27fddf0702/action
method: POST
response:
body: '{"task": {"id": "efa1a9e5-9401-4d41-ae3a-757ec3bc133c", "description":
"server_backup", "status": "pending", "href_from": "/servers/9e9c098b-8d80-4afc-bbb7-1e27fddf0702/action",
"href_result": "/images/e173c28d-aec1-42fc-b62d-e5fab00a00eb", "started_at":
"2024-07-05T09:33:08.468008+00:00", "terminated_at": null, "progress": 0, "zone":
"par1"}}'
headers:
Content-Length:
- "345"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/tasks/efa1a9e5-9401-4d41-ae3a-757ec3bc133c
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- efa60d84-af94-4e1c-9cce-c45d10b82d1a
status: 202 Accepted
code: 202
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/images/e173c28d-aec1-42fc-b62d-e5fab00a00eb
method: GET
response:
body: '{"image": {"id": "e173c28d-aec1-42fc-b62d-e5fab00a00eb", "name": "backup",
"organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"root_volume": {"id": "034bbb0d-ee3f-40ac-ac12-1c5aab7f6eb5", "name": "backup_snap_0",
"volume_type": "l_ssd", "size": 40000000000}, "extra_volumes": {}, "public":
false, "arch": "x86_64", "creation_date": "2024-07-05T09:33:07.973802+00:00",
"modification_date": "2024-07-05T09:33:07.973802+00:00", "default_bootscript":
{"id": "fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64
mainline 4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "from_server": "9e9c098b-8d80-4afc-bbb7-1e27fddf0702",
"state": "available", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "1125"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f62af5ef-9c4c-41a9-905e-9c030c7174f7
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/images/e173c28d-aec1-42fc-b62d-e5fab00a00eb
method: GET
response:
body: '{"image": {"id": "e173c28d-aec1-42fc-b62d-e5fab00a00eb", "name": "backup",
"organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"root_volume": {"id": "034bbb0d-ee3f-40ac-ac12-1c5aab7f6eb5", "name": "backup_snap_0",
"volume_type": "l_ssd", "size": 40000000000}, "extra_volumes": {}, "public":
false, "arch": "x86_64", "creation_date": "2024-07-05T09:33:07.973802+00:00",
"modification_date": "2024-07-05T09:33:07.973802+00:00", "default_bootscript":
{"id": "fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64
mainline 4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "from_server": "9e9c098b-8d80-4afc-bbb7-1e27fddf0702",
"state": "available", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "1125"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 41582a6d-5393-48a7-9ac3-120d02a1a6a2
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/9e9c098b-8d80-4afc-bbb7-1e27fddf0702
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 8428d86b-c728-4f4c-8a6a-b14248fda287
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/e3fc3664-2f32-4946-b3b1-710b607e6f8e
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 977a13f9-a575-4cac-b4c3-109fed067231
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/images/e173c28d-aec1-42fc-b62d-e5fab00a00eb
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:08 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- fc52484b-c312-44e2-8174-cf9f3d57cdf6
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/034bbb0d-ee3f-40ac-ac12-1c5aab7f6eb5
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:09 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- a18d0bbe-95a3-4a7c-8ceb-c049f05790a6
status: 204 No Content
code: 204
duration: ""
security-group-rule-test.yaml 0000664 0000000 0000000 00000050542 14747113137 0034516 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata ---
version: 1
interactions:
- request:
body: '{"name":"name","description":"description","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","stateful":true,"inbound_default_policy":"accept","outbound_default_policy":"drop"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups
method: POST
response:
body: '{"security_group": {"id": "4c3665d1-686b-4e00-8227-01008a3e311f", "creation_date":
"2023-12-04T09:54:26.090979+00:00", "modification_date": "2023-12-04T09:54:26.090979+00:00",
"name": "name", "description": "description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
true, "inbound_default_policy": "accept", "outbound_default_policy": "drop",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "575"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:26 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/4c3665d1-686b-4e00-8227-01008a3e311f
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 424222bc-813c-4a07-9922-55e91c94738a
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"TCP","direction":"inbound","action":"accept","ip_range":"8.8.8.8/32","dest_port_from":1,"dest_port_to":1024,"position":1}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/4c3665d1-686b-4e00-8227-01008a3e311f/rules
method: POST
response:
body: '{"rule": {"id": "978fa298-455e-420c-9f6f-7adf41e50b22", "protocol": "TCP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
1, "dest_port_to": 1024, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "261"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:26 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/4c3665d1-686b-4e00-8227-01008a3e311f/rules/978fa298-455e-420c-9f6f-7adf41e50b22
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- a19442e9-1d1b-4c1e-848c-56585e787d21
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"UDP","direction":"outbound","action":"drop","ip_range":"1.1.1.1/32","dest_port_from":1,"dest_port_to":2048}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/4c3665d1-686b-4e00-8227-01008a3e311f/rules/978fa298-455e-420c-9f6f-7adf41e50b22
method: PATCH
response:
body: '{"rule": {"id": "978fa298-455e-420c-9f6f-7adf41e50b22", "protocol": "UDP",
"direction": "outbound", "ip_range": "1.1.1.1", "dest_ip_range": null, "dest_port_from":
1, "dest_port_to": 2048, "position": 1, "editable": true, "action": "drop",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "260"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:26 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 3604c2f3-68be-4bc4-ad42-bb6fa63ca9fa
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/4c3665d1-686b-4e00-8227-01008a3e311f
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 04 Dec 2023 09:54:26 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f5ba5034-24a2-48d8-bafd-6a19ed86b7bb
status: 204 No Content
code: 204
duration: ""
- request:
body: '{"name":"name","description":"description","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","stateful":true,"inbound_default_policy":"accept","outbound_default_policy":"drop"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups
method: POST
response:
body: '{"security_group": {"id": "107d6e04-9382-49eb-998c-73d965393940", "creation_date":
"2023-12-04T09:54:26.920293+00:00", "modification_date": "2023-12-04T09:54:26.920293+00:00",
"name": "name", "description": "description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
true, "inbound_default_policy": "accept", "outbound_default_policy": "drop",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "575"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:26 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/107d6e04-9382-49eb-998c-73d965393940
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 9dca7f70-e36c-4738-843e-e2e04bbf41e8
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"TCP","direction":"inbound","action":"accept","ip_range":"8.8.8.8/32","dest_port_from":1,"dest_port_to":1024,"position":1}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/107d6e04-9382-49eb-998c-73d965393940/rules
method: POST
response:
body: '{"rule": {"id": "a8a7dbc6-ed53-41e0-97ef-69b552c445d0", "protocol": "TCP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
1, "dest_port_to": 1024, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "261"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:27 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/107d6e04-9382-49eb-998c-73d965393940/rules/a8a7dbc6-ed53-41e0-97ef-69b552c445d0
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 7c144588-2ffb-49d5-af8f-f03b5403f066
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"UDP","direction":"outbound","action":"drop","ip_range":"1.1.1.1/32","dest_port_from":22,"dest_port_to":22}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/107d6e04-9382-49eb-998c-73d965393940/rules/a8a7dbc6-ed53-41e0-97ef-69b552c445d0
method: PATCH
response:
body: '{"rule": {"id": "a8a7dbc6-ed53-41e0-97ef-69b552c445d0", "protocol": "UDP",
"direction": "outbound", "ip_range": "1.1.1.1", "dest_ip_range": null, "dest_port_from":
22, "dest_port_to": null, "position": 1, "editable": true, "action": "drop",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "261"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:27 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 77e019e5-af04-4203-b7a9-e9836acf0838
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/107d6e04-9382-49eb-998c-73d965393940
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 04 Dec 2023 09:54:27 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 998c1bda-c845-424b-970e-134e8ce859b0
status: 204 No Content
code: 204
duration: ""
- request:
body: '{"name":"name","description":"description","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","stateful":true,"inbound_default_policy":"accept","outbound_default_policy":"drop"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups
method: POST
response:
body: '{"security_group": {"id": "b7790067-7efe-414e-b936-b6ea53ef42c0", "creation_date":
"2023-12-04T09:54:27.804840+00:00", "modification_date": "2023-12-04T09:54:27.804840+00:00",
"name": "name", "description": "description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
true, "inbound_default_policy": "accept", "outbound_default_policy": "drop",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "575"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:27 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/b7790067-7efe-414e-b936-b6ea53ef42c0
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 024df3a3-d7d3-45b8-b503-87d59edb5237
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"TCP","direction":"inbound","action":"accept","ip_range":"8.8.8.8/32","dest_port_from":1,"dest_port_to":1024,"position":1}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/b7790067-7efe-414e-b936-b6ea53ef42c0/rules
method: POST
response:
body: '{"rule": {"id": "78137458-81c6-4cd0-855b-85ac5b5d0ac6", "protocol": "TCP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
1, "dest_port_to": 1024, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "261"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:28 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/b7790067-7efe-414e-b936-b6ea53ef42c0/rules/78137458-81c6-4cd0-855b-85ac5b5d0ac6
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 0ea907af-640f-470e-ac51-4dcb6f84ffe6
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"ICMP"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/b7790067-7efe-414e-b936-b6ea53ef42c0/rules/78137458-81c6-4cd0-855b-85ac5b5d0ac6
method: PATCH
response:
body: '{"rule": {"id": "78137458-81c6-4cd0-855b-85ac5b5d0ac6", "protocol": "ICMP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
null, "dest_port_to": null, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "265"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:28 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- bc059bec-471a-48f2-abb3-269f2a8f1826
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/b7790067-7efe-414e-b936-b6ea53ef42c0
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 04 Dec 2023 09:54:28 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 8e1cfd8d-063d-4b5c-80c7-be8e142ca46b
status: 204 No Content
code: 204
duration: ""
- request:
body: '{"name":"name","description":"description","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","stateful":true,"inbound_default_policy":"accept","outbound_default_policy":"drop"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups
method: POST
response:
body: '{"security_group": {"id": "1ef8d388-748d-4662-a18d-d99827fe9f9d", "creation_date":
"2023-12-04T09:54:28.598656+00:00", "modification_date": "2023-12-04T09:54:28.598656+00:00",
"name": "name", "description": "description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
true, "inbound_default_policy": "accept", "outbound_default_policy": "drop",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "575"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:28 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/1ef8d388-748d-4662-a18d-d99827fe9f9d
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b19d7176-7d1d-401c-91ae-9f10a3c64092
status: 201 Created
code: 201
duration: ""
- request:
body: '{"protocol":"TCP","direction":"inbound","action":"accept","ip_range":"8.8.8.8/32","dest_port_from":1,"dest_port_to":1024,"position":1}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/1ef8d388-748d-4662-a18d-d99827fe9f9d/rules
method: POST
response:
body: '{"rule": {"id": "fc99eefd-00c8-445f-881f-2dc097825271", "protocol": "TCP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
1, "dest_port_to": 1024, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "261"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:28 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/1ef8d388-748d-4662-a18d-d99827fe9f9d/rules/fc99eefd-00c8-445f-881f-2dc097825271
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 76673ac9-433b-4d4f-900e-fce8af518127
status: 201 Created
code: 201
duration: ""
- request:
body: '{"dest_port_from":0,"dest_port_to":0}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/1ef8d388-748d-4662-a18d-d99827fe9f9d/rules/fc99eefd-00c8-445f-881f-2dc097825271
method: PATCH
response:
body: '{"rule": {"id": "fc99eefd-00c8-445f-881f-2dc097825271", "protocol": "TCP",
"direction": "inbound", "ip_range": "8.8.8.8", "dest_ip_range": null, "dest_port_from":
null, "dest_port_to": null, "position": 1, "editable": true, "action": "accept",
"zone": "fr-par-1"}}'
headers:
Content-Length:
- "264"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 09:54:29 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 464cbddf-1055-4894-ac1b-8ec6afd0e448
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/1ef8d388-748d-4662-a18d-d99827fe9f9d
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 04 Dec 2023 09:54:29 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e1498644-a6ac-4aab-8cc3-c27a26b404f2
status: 204 No Content
code: 204
duration: ""
security-group-test.yaml 0000664 0000000 0000000 00000010135 14747113137 0033543 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata ---
version: 1
interactions:
- request:
body: '{"name":"name","description":"description","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","stateful":true,"inbound_default_policy":"accept","outbound_default_policy":"drop"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups
method: POST
response:
body: '{"security_group": {"id": "47b2363e-f0a1-4f75-a45a-0c0375ed4eef", "creation_date":
"2023-11-20T13:06:00.758750+00:00", "modification_date": "2023-11-20T13:06:00.758750+00:00",
"name": "name", "description": "description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
true, "inbound_default_policy": "accept", "outbound_default_policy": "drop",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "575"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 Nov 2023 13:06:00 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/47b2363e-f0a1-4f75-a45a-0c0375ed4eef
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e40b56b4-b73e-4d46-8db7-deaed04cba16
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"new_name","description":"new_description","inbound_default_policy":"drop","tags":["foo","bar"],"project_default":false,"outbound_default_policy":"accept","stateful":false}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/47b2363e-f0a1-4f75-a45a-0c0375ed4eef
method: PATCH
response:
body: '{"security_group": {"id": "47b2363e-f0a1-4f75-a45a-0c0375ed4eef", "creation_date":
"2023-11-20T13:06:00.758750+00:00", "modification_date": "2023-11-20T13:06:00.811016+00:00",
"name": "new_name", "description": "new_description", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "servers": [], "stateful":
false, "inbound_default_policy": "drop", "outbound_default_policy": "accept",
"organization_default": false, "project_default": false, "enable_default_security":
true, "state": "syncing", "tags": ["foo", "bar"], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "596"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 Nov 2023 13:06:00 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 65cf0b31-1f47-4ddc-9957-923b45a809ec
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/security_groups/47b2363e-f0a1-4f75-a45a-0c0375ed4eef
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 20 Nov 2023 13:06:01 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 7812b2f7-bb6c-4bf2-b489-2ed2868fc981
status: 204 No Content
code: 204
duration: ""
server-incorrect-body.yaml 0000664 0000000 0000000 00000001751 14747113137 0034020 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata ---
version: 1
interactions:
- request:
body: '{}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/0.0.0
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"fields": {"organization": ["required key not provided"], "image": ["required
key not provided"], "name": ["required key not provided"], "volumes": ["required
key not provided"]}, "message": "Validation Error", "type": "invalid_request_error"}'
headers:
Content-Length:
- "244"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 23 May 2019 15:49:33 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 400 Bad Request
code: 400
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/server-list-zones.yaml 0000664 0000000 0000000 00000043650 14747113137 0033267 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-2/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- c7d9ed67-007c-4502-a69f-977594053229
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/nl-ams-1/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 8ef1c9e8-5ac6-41c8-a256-52b6d7750490
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/pl-waw-1/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 80326066-8b59-4a88-914f-1a872608ee26
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/nl-ams-3/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b9a9b487-fc34-4390-bc20-75493ea0ea27
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/nl-ams-2/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4f9412cb-247f-43d7-9154-4d0a5ba859cd
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/pl-waw-3/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 586a7119-be00-49c9-af4b-ec9d1efa61f8
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/pl-waw-2/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": []}'
headers:
Content-Length:
- "15"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e4f2410c-cef3-432b-b5d0-4148f4b6e616
X-Total-Count:
- "0"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": [{"id": "c66fe648-06c8-4cab-83d4-d963bf0ef8df", "name": "kubetest-runner",
"arch": "x86_64", "commercial_type": "PRO2-S", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "kubetest-runner", "image": {"id": "ce453858-557c-4f1c-a7a9-70026e67d054",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "30e9c843-1cdb-4bd4-96f7-cac26051eeaf",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-04-13T12:13:29.892843+00:00",
"modification_date": "2023-04-13T12:13:29.892843+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "df0026ac-7c59-4ecd-80b0-265281e2477e",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri":
null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "c66fe648-06c8-4cab-83d4-d963bf0ef8df", "name": "kubetest-runner"},
"size": 100000000000, "state": "available", "creation_date": "2023-05-03T12:12:04.671813+00:00",
"modification_date": "2023-05-03T12:12:04.671813+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": ["kube", "cli"], "state": "stopped", "protected": false,
"state_detail": "", "public_ip": {"id": "58542407-77e1-444b-9fa3-30c4a0d9d7fb",
"address": "163.172.170.102", "dynamic": false, "gateway": null, "netmask":
"32", "family": "inet", "provisioning_mode": "dhcp"}, "public_ips": [{"id":
"58542407-77e1-444b-9fa3-30c4a0d9d7fb", "address": "163.172.170.102", "dynamic":
false, "gateway": null, "netmask": "32", "family": "inet", "provisioning_mode":
"dhcp"}], "mac_address": "de:00:00:13:02:db", "routed_ip_enabled": false, "ipv6":
null, "extra_networks": [], "dynamic_ip_required": true, "enable_ipv6": false,
"private_ip": null, "creation_date": "2023-05-03T12:12:04.671813+00:00", "modification_date":
"2023-06-22T08:44:57.189402+00:00", "bootscript": {"id": "fdfe150f-a870-4ce4-b432-9f56b5b995c1",
"public": true, "title": "x86_64 mainline 4.4.230 rev1", "architecture": "x86_64",
"organization": "11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}]}'
headers:
Content-Length:
- "2981"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 04bca493-3731-46bd-af59-529a9ae3d216
X-Total-Count:
- "1"
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-3/servers?order=creation_date_desc
method: GET
response:
body: '{"servers": [{"id": "38486156-25dc-4d55-aa7d-b234b05d9071", "name": "cli-srv-elated-edison",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "cli-srv-elated-edison", "image": {"id": "670ac22a-8f62-4c60-99b7-f59ad838a34a",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "9a95c3a7-5f40-4dd8-963a-ddf48598da1b",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-07-24T07:51:14.827507+00:00",
"modification_date": "2023-07-24T07:51:14.827507+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-3"},
"volumes": {"0": {"boot": false, "id": "9ed0a26d-f208-47d9-b3b9-d7383f77360d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri":
null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "38486156-25dc-4d55-aa7d-b234b05d9071", "name": "cli-srv-elated-edison"},
"size": 10000000000, "state": "available", "creation_date": "2023-08-02T11:30:08.321084+00:00",
"modification_date": "2023-08-02T11:30:08.321084+00:00", "tags": [], "zone":
"fr-par-3"}}, "tags": [], "state": "running", "protected": false, "state_detail":
"booted", "public_ip": {"id": "73d1232c-d785-4206-97e2-a5763c059fdf", "address":
"2001:bc8:a10:10:dc00:ff:fe04:ebad", "dynamic": false, "gateway": "fe80::dc00:ff:fe04:ebae",
"netmask": "64", "family": "inet6", "provisioning_mode": "slaac"}, "public_ips":
[{"id": "73d1232c-d785-4206-97e2-a5763c059fdf", "address": "2001:bc8:a10:10:dc00:ff:fe04:ebad",
"dynamic": false, "gateway": "fe80::dc00:ff:fe04:ebae", "netmask": "64", "family":
"inet6", "provisioning_mode": "slaac"}], "mac_address": "de:00:00:04:eb:ad",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
false, "enable_ipv6": false, "private_ip": null, "creation_date": "2023-08-02T11:30:08.321084+00:00",
"modification_date": "2023-08-02T11:40:36.316437+00:00", "bootscript": {"id":
"346edd9d-a17a-45f5-b2ac-bbf282c3ce3c", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-3"}, "security_group": {"id": "2da7f6cb-2774-4873-aff8-bc03dae3a32e",
"name": "Default security group"}, "location": {"zone_id": "fr-par-3", "platform_id":
"60", "cluster_id": "6", "hypervisor_id": "201", "node_id": "4"}, "maintenances":
[], "allowed_actions": ["poweroff", "terminate", "reboot", "stop_in_place",
"backup"], "placement_group": null, "private_nics": [], "zone": "fr-par-3"},
{"id": "eb4460c2-b7cc-4c7a-acb7-69ea3fb57e77", "name": "cli-srv-awesome-greider",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "cli-srv-awesome-greider", "image": {"id": "670ac22a-8f62-4c60-99b7-f59ad838a34a",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "9a95c3a7-5f40-4dd8-963a-ddf48598da1b",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-07-24T07:51:14.827507+00:00",
"modification_date": "2023-07-24T07:51:14.827507+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-3"},
"volumes": {"0": {"boot": false, "id": "ec18850b-b6e2-4890-bd23-2a09f38279c7",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri":
null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "eb4460c2-b7cc-4c7a-acb7-69ea3fb57e77", "name": "cli-srv-awesome-greider"},
"size": 10000000000, "state": "available", "creation_date": "2023-08-02T09:10:04.365308+00:00",
"modification_date": "2023-08-02T09:10:04.365308+00:00", "tags": [], "zone":
"fr-par-3"}}, "tags": [], "state": "running", "protected": false, "state_detail":
"booted", "public_ip": {"id": "e0e2f5fb-9f6a-4875-8a20-0d97e61ccee8", "address":
"51.159.82.173", "dynamic": false, "gateway": null, "netmask": "32", "family":
"inet", "provisioning_mode": "dhcp"}, "public_ips": [{"id": "e0e2f5fb-9f6a-4875-8a20-0d97e61ccee8",
"address": "51.159.82.173", "dynamic": false, "gateway": null, "netmask": "32",
"family": "inet", "provisioning_mode": "dhcp"}], "mac_address": "de:00:00:04:eb:2f",
"routed_ip_enabled": false, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": "10.199.99.5", "creation_date": "2023-08-02T09:10:04.365308+00:00",
"modification_date": "2023-08-02T09:10:08.260056+00:00", "bootscript": {"id":
"346edd9d-a17a-45f5-b2ac-bbf282c3ce3c", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-3"}, "security_group": {"id": "2da7f6cb-2774-4873-aff8-bc03dae3a32e",
"name": "Default security group"}, "location": {"zone_id": "fr-par-3", "platform_id":
"60", "cluster_id": "6", "hypervisor_id": "501", "node_id": "3"}, "maintenances":
[], "allowed_actions": ["poweroff", "terminate", "reboot", "stop_in_place",
"backup", "enable_routed_ip"], "placement_group": null, "private_nics": [],
"zone": "fr-par-3"}]}'
headers:
Content-Length:
- "6378"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 03 Aug 2023 12:13:24 GMT
Link:
- ; rel="last"
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 89d5785c-cb40-42fa-b1e6-45ba9c03dca7
X-Total-Count:
- "2"
status: 200 OK
code: 200
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/server-test.yaml 0000664 0000000 0000000 00000045563 14747113137 0032144 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"instance_sdk_server_test","dynamic_ip_required":true,"commercial_type":"START1-S","image":"f974feac-abae-4365-b988-8ec7d1cec10d","enable_ipv6":true,"boot_type":"local","project":"14d2f7ae-9775-414c-9bed-6810e060d500","tags":["foo","bar"]}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "6a3d62f7-8852-4dd2-b16a-905b695cd199", "name": "instance_sdk_server_test",
"arch": "x86_64", "commercial_type": "START1-S", "boot_type": "local", "organization":
"14d2f7ae-9775-414c-9bed-6810e060d500", "project": "14d2f7ae-9775-414c-9bed-6810e060d500",
"hostname": "instance-sdk-server-test", "image": {"id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"name": "Ubuntu Bionic Beaver", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "size": 10000000000}, "extra_volumes": {}, "public": true, "arch":
"x86_64", "creation_date": "2019-03-05T10:13:15.974944+00:00", "modification_date":
"2019-03-05T13:32:29.274319+00:00", "default_bootscript": {"id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false, "title": "x86_64 mainline 4.9.93 rev1", "architecture": "x86_64",
"organization": "11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "from_server": null, "state": "available", "zone":
"fr-par-1"}, "volumes": {"0": {"id": "c6b29ca6-8895-42fb-a498-a89011c29ff7",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "export_uri": null, "organization": "14d2f7ae-9775-414c-9bed-6810e060d500",
"project": "14d2f7ae-9775-414c-9bed-6810e060d500", "server": {"id": "6a3d62f7-8852-4dd2-b16a-905b695cd199",
"name": "instance_sdk_server_test"}, "size": 50000000000, "state": "available",
"creation_date": "2020-08-14T13:02:02.652219+00:00", "modification_date": "2020-08-14T13:02:02.990859+00:00",
"zone": "fr-par-1"}}, "tags": ["foo", "bar"], "state": "stopped", "protected":
false, "state_detail": "", "public_ip": null, "ipv6": null, "extra_networks":
[], "dynamic_ip_required": true, "enable_ipv6": true, "private_ip": null, "creation_date":
"2020-08-14T13:02:02.652219+00:00", "modification_date": "2020-08-14T13:02:03.095139+00:00",
"bootscript": {"id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8", "public": false,
"title": "x86_64 mainline 4.9.93 rev1", "architecture": "x86_64", "organization":
"11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "security_group": {"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "3112"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:02 GMT
Location:
- https://cp-par1.scaleway.com/servers/6a3d62f7-8852-4dd2-b16a-905b695cd199
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- ec8ac5f5-cbda-4d28-92b7-76365f6dcc97
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"instance_sdk_server_test","image":"f974feac-abae-4365-b988-8ec7d1cec10d","organization":"14d2f7ae-9775-414c-9bed-6810e060d500"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "12be8295-263f-4f71-9c7d-a33ef31f3887", "name": "instance_sdk_server_test",
"arch": "x86_64", "commercial_type": "START1-S", "boot_type": "bootscript",
"organization": "14d2f7ae-9775-414c-9bed-6810e060d500", "project": "14d2f7ae-9775-414c-9bed-6810e060d500",
"hostname": "instance-sdk-server-test", "image": {"id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"name": "Ubuntu Bionic Beaver", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "size": 10000000000}, "extra_volumes": {}, "public": true, "arch":
"x86_64", "creation_date": "2019-03-05T10:13:15.974944+00:00", "modification_date":
"2019-03-05T13:32:29.274319+00:00", "default_bootscript": {"id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false, "title": "x86_64 mainline 4.9.93 rev1", "architecture": "x86_64",
"organization": "11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "from_server": null, "state": "available", "zone":
"fr-par-1"}, "volumes": {"0": {"id": "a7f56913-ba01-42b7-9d88-f12d42ea309b",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "export_uri": null, "organization": "14d2f7ae-9775-414c-9bed-6810e060d500",
"project": "14d2f7ae-9775-414c-9bed-6810e060d500", "server": {"id": "12be8295-263f-4f71-9c7d-a33ef31f3887",
"name": "instance_sdk_server_test"}, "size": 50000000000, "state": "available",
"creation_date": "2020-08-14T13:02:03.527628+00:00", "modification_date": "2020-08-14T13:02:03.845180+00:00",
"zone": "fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2020-08-14T13:02:03.527628+00:00",
"modification_date": "2020-08-14T13:02:03.928001+00:00", "bootscript": {"id":
"15fbd2f7-a0f9-412b-8502-6a44da8d98b8", "public": false, "title": "x86_64 mainline
4.9.93 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "security_group": {"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "3106"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:03 GMT
Location:
- https://cp-par1.scaleway.com/servers/12be8295-263f-4f71-9c7d-a33ef31f3887
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f12de65b-8e0e-402d-bdfe-8c76b7837d8d
status: 201 Created
code: 201
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/12be8295-263f-4f71-9c7d-a33ef31f3887
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:04 GMT
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f0a5c1f4-25a5-4273-8df5-2bf73062bea1
status: 204 No Content
code: 204
duration: ""
- request:
body: '{"name":"some_new_name_for_server","tags":[]}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/6a3d62f7-8852-4dd2-b16a-905b695cd199
method: PATCH
response:
body: '{"server": {"id": "6a3d62f7-8852-4dd2-b16a-905b695cd199", "name": "some_new_name_for_server",
"arch": "x86_64", "commercial_type": "START1-S", "boot_type": "local", "organization":
"14d2f7ae-9775-414c-9bed-6810e060d500", "project": "14d2f7ae-9775-414c-9bed-6810e060d500",
"hostname": "some-new-name-for-server", "image": {"id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"name": "Ubuntu Bionic Beaver", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "size": 10000000000}, "extra_volumes": {}, "public": true, "arch":
"x86_64", "creation_date": "2019-03-05T10:13:15.974944+00:00", "modification_date":
"2019-03-05T13:32:29.274319+00:00", "default_bootscript": {"id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false, "title": "x86_64 mainline 4.9.93 rev1", "architecture": "x86_64",
"organization": "11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "from_server": null, "state": "available", "zone":
"fr-par-1"}, "volumes": {"0": {"id": "c6b29ca6-8895-42fb-a498-a89011c29ff7",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "export_uri": null, "organization": "14d2f7ae-9775-414c-9bed-6810e060d500",
"project": "14d2f7ae-9775-414c-9bed-6810e060d500", "server": {"id": "6a3d62f7-8852-4dd2-b16a-905b695cd199",
"name": "some_new_name_for_server"}, "size": 50000000000, "state": "available",
"creation_date": "2020-08-14T13:02:02.652219+00:00", "modification_date": "2020-08-14T13:02:02.990859+00:00",
"zone": "fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": true, "private_ip": null, "creation_date": "2020-08-14T13:02:02.652219+00:00",
"modification_date": "2020-08-14T13:02:04.847138+00:00", "bootscript": {"id":
"15fbd2f7-a0f9-412b-8502-6a44da8d98b8", "public": false, "title": "x86_64 mainline
4.9.93 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "security_group": {"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "3100"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:04 GMT
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 10bdaf49-c624-42a6-8523-2fa6ecdf9409
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volumes":{}}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/6a3d62f7-8852-4dd2-b16a-905b695cd199
method: PATCH
response:
body: '{"server": {"id": "6a3d62f7-8852-4dd2-b16a-905b695cd199", "name": "some_new_name_for_server",
"arch": "x86_64", "commercial_type": "START1-S", "boot_type": "local", "organization":
"14d2f7ae-9775-414c-9bed-6810e060d500", "project": "14d2f7ae-9775-414c-9bed-6810e060d500",
"hostname": "some-new-name-for-server", "image": {"id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"name": "Ubuntu Bionic Beaver", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13", "volume_type":
"l_ssd", "size": 10000000000}, "extra_volumes": {}, "public": true, "arch":
"x86_64", "creation_date": "2019-03-05T10:13:15.974944+00:00", "modification_date":
"2019-03-05T13:32:29.274319+00:00", "default_bootscript": {"id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false, "title": "x86_64 mainline 4.9.93 rev1", "architecture": "x86_64",
"organization": "11111111-1111-4111-8111-111111111111", "project": "11111111-1111-4111-8111-111111111111",
"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "from_server": null, "state": "available", "zone":
"fr-par-1"}, "volumes": {}, "tags": [], "state": "stopped", "protected": false,
"state_detail": "", "public_ip": null, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": true, "private_ip": null, "creation_date": "2020-08-14T13:02:02.652219+00:00",
"modification_date": "2020-08-14T13:02:04.847138+00:00", "bootscript": {"id":
"15fbd2f7-a0f9-412b-8502-6a44da8d98b8", "public": false, "title": "x86_64 mainline
4.9.93 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"dtb": "", "initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
false, "zone": "fr-par-1"}, "security_group": {"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "2557"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:04 GMT
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b5c48b57-5bd7-419a-ace2-a5f4348a6691
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/6a3d62f7-8852-4dd2-b16a-905b695cd199
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:05 GMT
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 45a4d549-f633-4d1c-a08c-d7a0039fdfe5
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.13.6; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/c6b29ca6-8895-42fb-a498-a89011c29ff7
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 14 Aug 2020 13:02:05 GMT
Server:
- agw_listener_public_vip
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- caf7c95e-21e8-4e6e-8679-e632096c6cac
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/server-user-data.yaml 0000664 0000000 0000000 00000012616 14747113137 0033043 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"srv-wonderful-goldberg","commercial_type":"DEV1-S","image":"f974feac-abae-4365-b988-8ec7d1cec10d","organization":"14d2f7ae-9775-414c-9bed-6810e060d500"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"allowed_actions": ["poweron", "backup"], "maintenances": [],
"state_detail": "", "image": {"creation_date": "2019-03-05T10:13:15.974944+00:00",
"default_bootscript": {"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz", "default":
false, "bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "architecture":
"x86_64", "title": "x86_64 mainline 4.9.93 rev1", "dtb": "", "organization":
"11111111-1111-4111-8111-111111111111", "id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false}, "from_server": null, "arch": "x86_64", "id": "f974feac-abae-4365-b988-8ec7d1cec10d",
"root_volume": {"size": 10000000000, "id": "dd5f5c10-23b1-4c9c-8445-eb6740957c84",
"volume_type": "l_ssd", "name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13"},
"name": "Ubuntu Bionic Beaver", "modification_date": "2019-03-05T13:32:29.274319+00:00",
"state": "available", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"extra_volumes": {}, "public": true}, "creation_date": "2019-06-20T17:59:31.822202+00:00",
"public_ip": null, "private_ip": null, "id": "d7b6fd2a-32f9-446f-ba49-6a67be590a07",
"dynamic_ip_required": true, "modification_date": "2019-06-20T17:59:32.192591+00:00",
"enable_ipv6": false, "hostname": "srv-wonderful-goldberg", "state": "stopped",
"bootscript": {"kernel": "http://169.254.42.24/kernel/x86_64-mainline-lts-4.9-4.9.93-rev1/vmlinuz-4.9.93",
"initrd": "http://169.254.42.24/initrd/initrd-Linux-x86_64-v3.14.6.gz", "default":
false, "bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "architecture":
"x86_64", "title": "x86_64 mainline 4.9.93 rev1", "dtb": "", "organization":
"11111111-1111-4111-8111-111111111111", "id": "15fbd2f7-a0f9-412b-8502-6a44da8d98b8",
"public": false}, "location": null, "boot_type": "local", "ipv6": null, "commercial_type":
"DEV1-S", "tags": [], "arch": "x86_64", "extra_networks": [], "compute_cluster":
null, "name": "srv-wonderful-goldberg", "protected": false, "volumes": {"0":
{"size": 20000000000, "state": "available", "name": "snapshot-de728daa-0bf6-4c64-abf5-a9477e791c83-2019-03-05_10:13",
"modification_date": "2019-06-20T17:59:32.094121+00:00", "organization": "14d2f7ae-9775-414c-9bed-6810e060d500",
"export_uri": null, "creation_date": "2019-06-20T17:59:31.822202+00:00", "id":
"fe034b14-2c3f-4f30-96f8-d695f24aa6de", "volume_type": "l_ssd", "server": {"id":
"d7b6fd2a-32f9-446f-ba49-6a67be590a07", "name": "srv-wonderful-goldberg"}}},
"security_group": {"id": "e5bf4522-94b4-4933-bebb-9b21f786b4af", "name": "Default
security group"}, "organization": "14d2f7ae-9775-414c-9bed-6810e060d500"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "2718"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Thu, 20 Jun 2019 17:59:32 GMT
Location:
- https://cp-par1.scaleway.com/servers/d7b6fd2a-32f9-446f-ba49-6a67be590a07
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 201 Created
code: 201
duration: ""
- request:
body: world
form: {}
headers:
Content-Type:
- text/plain
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/d7b6fd2a-32f9-446f-ba49-6a67be590a07/user_data/hello
method: PATCH
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Thu, 20 Jun 2019 17:59:32 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/0.0.0 (go1.12.5; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/d7b6fd2a-32f9-446f-ba49-6a67be590a07/user_data/hello
method: GET
response:
body: world
headers:
Cache-Control:
- no-cache
Content-Length:
- "5"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- text/plain
Date:
- Thu, 20 Jun 2019 17:59:32 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status: 200 OK
code: 200
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/snapshot-test.yaml 0000664 0000000 0000000 00000020062 14747113137 0032460 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"volume_name","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","volume_type":"b_ssd","size":1000000000}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes
method: POST
response:
body: '{"volume": {"id": "6c73aee5-1c22-4207-a6f8-3fdc16c88183", "name": "volume_name",
"volume_type": "b_ssd", "export_uri": null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "server": null, "size": 1000000000,
"state": "available", "creation_date": "2023-12-04T10:02:02.557422+00:00", "modification_date":
"2023-12-04T10:02:02.557422+00:00", "tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "432"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 10:02:02 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/6c73aee5-1c22-4207-a6f8-3fdc16c88183
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- c118842c-92e2-4d20-b986-d22fcffb403b
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"name","volume_id":"6c73aee5-1c22-4207-a6f8-3fdc16c88183","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots
method: POST
response:
body: '{"snapshot": {"id": "7015526e-cd90-4f2a-bb37-fa9106cf313f", "name": "name",
"volume_type": "b_ssd", "creation_date": "2023-12-04T10:02:02.713296+00:00",
"modification_date": "2023-12-04T10:02:02.713296+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 1000000000, "state":
"snapshotting", "base_volume": {"id": "6c73aee5-1c22-4207-a6f8-3fdc16c88183",
"name": "volume_name"}, "tags": [], "zone": "fr-par-1", "error_details": null},
"task": {"id": "1a6f272b-3d1a-4181-9f7f-e104a8fedf44", "description": "snapshot_7015526e-cd90-4f2a-bb37-fa9106cf313f",
"status": "pending", "href_from": "/snapshots", "href_result": "snapshots/7015526e-cd90-4f2a-bb37-fa9106cf313f",
"started_at": "2023-12-04T10:02:03.121513+00:00", "terminated_at": null}}'
headers:
Content-Length:
- "809"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 10:02:03 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 9c8a8504-af61-45a7-a4d3-f24bfbddc1ca
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"new_name","tags":["foo","bar"]}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/7015526e-cd90-4f2a-bb37-fa9106cf313f
method: PATCH
response:
body: '{"snapshot": {"id": "7015526e-cd90-4f2a-bb37-fa9106cf313f", "name": "new_name",
"volume_type": "b_ssd", "creation_date": "2023-12-04T10:02:02.713296+00:00",
"modification_date": "2023-12-04T10:02:03.482505+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 1000000000, "state":
"snapshotting", "base_volume": {"id": "6c73aee5-1c22-4207-a6f8-3fdc16c88183",
"name": "volume_name"}, "tags": ["foo", "bar"], "zone": "fr-par-1", "error_details":
null}}'
headers:
Content-Length:
- "519"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 10:02:03 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- fcd34fb2-ab59-4b04-b35b-fc190a58878c
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/7015526e-cd90-4f2a-bb37-fa9106cf313f
method: GET
response:
body: '{"snapshot": {"id": "7015526e-cd90-4f2a-bb37-fa9106cf313f", "name": "new_name",
"volume_type": "b_ssd", "creation_date": "2023-12-04T10:02:02.713296+00:00",
"modification_date": "2023-12-04T10:02:03.482505+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 1000000000, "state":
"snapshotting", "base_volume": {"id": "6c73aee5-1c22-4207-a6f8-3fdc16c88183",
"name": "volume_name"}, "tags": ["foo", "bar"], "zone": "fr-par-1", "error_details":
null}}'
headers:
Content-Length:
- "519"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 10:02:03 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- cd1194dc-b398-43f4-987e-fd9918ad61a7
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/7015526e-cd90-4f2a-bb37-fa9106cf313f
method: GET
response:
body: '{"snapshot": {"id": "7015526e-cd90-4f2a-bb37-fa9106cf313f", "name": "new_name",
"volume_type": "b_ssd", "creation_date": "2023-12-04T10:02:02.713296+00:00",
"modification_date": "2023-12-04T10:02:08.092862+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 1000000000, "state":
"available", "base_volume": {"id": "6c73aee5-1c22-4207-a6f8-3fdc16c88183", "name":
"volume_name"}, "tags": ["foo", "bar"], "zone": "fr-par-1", "error_details":
null}}'
headers:
Content-Length:
- "516"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 04 Dec 2023 10:02:08 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 33f3bd9e-43cc-4236-813c-7ca7a228bb81
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/7015526e-cd90-4f2a-bb37-fa9106cf313f
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Date:
- Mon, 04 Dec 2023 10:02:09 GMT
Server:
- Scaleway API-Gateway
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 5ade24b0-f382-4dcb-82c5-09ef41540b22
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/snapshot-wait-test.yaml0000664 0000000 0000000 00000032010 14747113137 0033416 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=ubuntu_focal&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"local_images":[{"id":"19f37e3e-d8c4-43cb-a739-7ccefec2a489","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"9c41e95b-add2-4ef8-b1b1-af8899748eda","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"1de03aca-1106-4152-bd36-f057c0cce9f1","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_sbs"},{"id":"60dd2959-89ce-4636-b54d-f1bb2ce9bde8","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_sbs"}],"total_count":4}'
headers:
Content-Length:
- "2328"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:13 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4727e0d7-4267-4acd-abc4-136d95ad9667
status: 200 OK
code: 200
duration: ""
- request:
body: '{"name":"srv-infallible-joliot","commercial_type":"DEV1-M","image":"9c41e95b-add2-4ef8-b1b1-af8899748eda","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "f8b691c4-1e71-4144-9eb5-aa3c8092ef0e", "name": "srv-infallible-joliot",
"arch": "x86_64", "commercial_type": "DEV1-M", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "srv-infallible-joliot", "image": {"id": "9c41e95b-add2-4ef8-b1b1-af8899748eda",
"name": "Ubuntu 20.04 Focal Fossa", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "f7bff04a-ee32-4bf5-ae53-2280e11d8977",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2024-07-03T19:59:39.939165+00:00",
"modification_date": "2024-07-03T19:59:39.939165+00:00", "default_bootscript":
null, "from_server": "", "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "bc8ca225-0f0d-48af-8aa3-ef6a5cd4392a",
"name": "Ubuntu 20.04 Focal Fossa", "volume_type": "l_ssd", "export_uri": null,
"organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "f8b691c4-1e71-4144-9eb5-aa3c8092ef0e", "name": "srv-infallible-joliot"},
"size": 40000000000, "state": "available", "creation_date": "2024-07-05T09:33:13.654985+00:00",
"modification_date": "2024-07-05T09:33:13.654985+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:5f:9a:55",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-07-05T09:33:13.654985+00:00",
"modification_date": "2024-07-05T09:33:13.654985+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2621"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:13 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/f8b691c4-1e71-4144-9eb5-aa3c8092ef0e
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 74160d89-5c0a-4b55-b44a-2bc945f56a48
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"backup","volume_id":"bc8ca225-0f0d-48af-8aa3-ef6a5cd4392a","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots
method: POST
response:
body: '{"snapshot": {"id": "0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299", "name": "backup",
"volume_type": "l_ssd", "creation_date": "2024-07-05T09:33:14.277625+00:00",
"modification_date": "2024-07-05T09:33:14.277625+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 40000000000, "state":
"available", "base_volume": {"id": "bc8ca225-0f0d-48af-8aa3-ef6a5cd4392a", "name":
"Ubuntu 20.04 Focal Fossa"}, "tags": [], "zone": "fr-par-1", "error_details":
null}, "task": {"id": "debc7e1f-5ed3-499d-b24a-689def64f4d9", "description":
"volume_cold_snapshot", "status": "success", "href_from": "/snapshots", "href_result":
"snapshots/0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299", "started_at": "2024-07-05T09:33:14.562021+00:00",
"terminated_at": null, "progress": 100, "zone": "par1"}}'
headers:
Content-Length:
- "830"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:14 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 48b4f67d-c8e2-4513-9439-fe15831bec92
status: 201 Created
code: 201
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299
method: GET
response:
body: '{"snapshot": {"id": "0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299", "name": "backup",
"volume_type": "l_ssd", "creation_date": "2024-07-05T09:33:14.277625+00:00",
"modification_date": "2024-07-05T09:33:14.277625+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 40000000000, "state":
"available", "base_volume": {"id": "bc8ca225-0f0d-48af-8aa3-ef6a5cd4392a", "name":
"Ubuntu 20.04 Focal Fossa"}, "tags": [], "zone": "fr-par-1", "error_details":
null}}'
headers:
Content-Length:
- "516"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:14 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e1f732b5-df54-4c54-b470-eb867ae42dc9
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299
method: GET
response:
body: '{"snapshot": {"id": "0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299", "name": "backup",
"volume_type": "l_ssd", "creation_date": "2024-07-05T09:33:14.277625+00:00",
"modification_date": "2024-07-05T09:33:14.277625+00:00", "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "size": 40000000000, "state":
"available", "base_volume": {"id": "bc8ca225-0f0d-48af-8aa3-ef6a5cd4392a", "name":
"Ubuntu 20.04 Focal Fossa"}, "tags": [], "zone": "fr-par-1", "error_details":
null}}'
headers:
Content-Length:
- "516"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:14 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 2f2d0ed5-d47e-4d65-a421-7380ba01406d
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/f8b691c4-1e71-4144-9eb5-aa3c8092ef0e
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:15 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b83a4804-f98a-45eb-be2c-197356dca1a9
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/snapshots/0d4bf5bd-8bb0-4d8e-b652-c34b4d3ad299
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:33:14 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- bcc50102-4db7-407c-aa9d-dde76dbe740e
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/utils-test-block.yaml 0000664 0000000 0000000 00000074461 14747113137 0033065 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"instance_utils_test","project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","from_empty":{"size":20000000000},"tags":null}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes
method: POST
response:
body: '{"id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","name":"instance_utils_test","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.682388Z","updated_at":"2024-05-20T13:50:54.682388Z","references":[],"parent_snapshot_id":null,"status":"creating","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "402"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:54 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 83b2f155-5d59-413f-aa41-ae06a9c2c631
status: 200 OK
code: 200
duration: ""
- request:
body: '{"name":"instance_utils_test2","project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","from_empty":{"size":20000000000},"tags":null}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes
method: POST
response:
body: '{"id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","name":"instance_utils_test2","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.796749Z","updated_at":"2024-05-20T13:50:54.796749Z","references":[],"parent_snapshot_id":null,"status":"creating","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "403"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:54 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 11e3f867-fe23-4a78-b971-19e9735678c3
status: 200 OK
code: 200
duration: ""
- request:
body: '{"name":"instance_utils_test","commercial_type":"PRO2-XXS","image":"81b9475d-e1b5-43c2-ac48-4c1a3b640686","volumes":{"0":{"id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","volume_type":"sbs_volume"}},"project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "a96556aa-8a7e-4068-9914-a37729cccf05", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "volume_type": "sbs_volume", "id": "f760dfca-f930-4a33-aceb-3a024ccf3ff1"}},
"tags": [], "state": "stopped", "protected": false, "state_detail": "", "public_ip":
null, "public_ips": [], "mac_address": "de:00:00:53:3f:51", "routed_ip_enabled":
true, "ipv6": null, "extra_networks": [], "dynamic_ip_required": true, "enable_ipv6":
false, "private_ip": null, "creation_date": "2024-05-20T13:50:54.998615+00:00",
"modification_date": "2024-05-20T13:50:54.998615+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2195"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:54 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/a96556aa-8a7e-4068-9914-a37729cccf05
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 26dc6702-4561-464d-b09b-c8ed5967727d
status: 201 Created
code: 201
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: GET
response:
body: '{"type": "not_found", "message": "resource is not found", "resource": "instance_volume",
"resource_id": "f760dfca-f930-4a33-aceb-3a024ccf3ff1"}'
headers:
Content-Length:
- "143"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:55 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 35f88759-36ab-47f8-8902-9b2c6c582bbd
status: 404 Not Found
code: 404
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: GET
response:
body: '{"id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","name":"instance_utils_test","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.682388Z","updated_at":"2024-05-20T13:50:55.079596Z","references":[{"id":"415ef80b-72c0-4eb1-b210-77037fe85eae","product_resource_type":"instance_server","product_resource_id":"a96556aa-8a7e-4068-9914-a37729cccf05","created_at":"2024-05-20T13:50:55.079596Z","type":"exclusive","status":"attached"}],"parent_snapshot_id":null,"status":"in_use","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "630"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:55 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 32cfcb9b-0608-46d7-aac4-7cd8c4c2c083
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volume_id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/a96556aa-8a7e-4068-9914-a37729cccf05/detach-volume
method: POST
response:
body: '{"server": {"id": "a96556aa-8a7e-4068-9914-a37729cccf05", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:53:3f:51",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-05-20T13:50:54.998615+00:00",
"modification_date": "2024-05-20T13:50:54.998615+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2100"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:55 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 1b830dde-ccdd-47f6-8fe3-a16a1f65d0ba
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: GET
response:
body: '{"type": "not_found", "message": "resource is not found", "resource": "instance_volume",
"resource_id": "f760dfca-f930-4a33-aceb-3a024ccf3ff1"}'
headers:
Content-Length:
- "143"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:55 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4f0d5506-5015-4c4a-b870-c7be0a552cbb
status: 404 Not Found
code: 404
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: GET
response:
body: '{"id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","name":"instance_utils_test","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.682388Z","updated_at":"2024-05-20T13:50:55.079596Z","references":[{"id":"415ef80b-72c0-4eb1-b210-77037fe85eae","product_resource_type":"instance_server","product_resource_id":"a96556aa-8a7e-4068-9914-a37729cccf05","created_at":"2024-05-20T13:50:55.079596Z","type":"exclusive","status":"detaching"}],"parent_snapshot_id":null,"status":"in_use","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "631"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:55 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 6face2c6-8e40-4fe8-ad75-da9699e1a3d4
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volume_id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","volume_type":"sbs_volume"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/a96556aa-8a7e-4068-9914-a37729cccf05/attach-volume
method: POST
response:
body: '{"server": {"id": "a96556aa-8a7e-4068-9914-a37729cccf05", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "volume_type": "sbs_volume", "id": "f760dfca-f930-4a33-aceb-3a024ccf3ff1"}},
"tags": [], "state": "stopped", "protected": false, "state_detail": "", "public_ip":
null, "public_ips": [], "mac_address": "de:00:00:53:3f:51", "routed_ip_enabled":
true, "ipv6": null, "extra_networks": [], "dynamic_ip_required": true, "enable_ipv6":
false, "private_ip": null, "creation_date": "2024-05-20T13:50:54.998615+00:00",
"modification_date": "2024-05-20T13:50:54.998615+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
[], "placement_group": null, "private_nics": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "2176"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:56 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 8a2dc4b5-64a0-407d-a173-cf73a50185cc
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: GET
response:
body: '{"type": "not_found", "message": "resource is not found", "resource": "instance_volume",
"resource_id": "097113f9-76d0-4fe7-97f1-ceaa848b3198"}'
headers:
Content-Length:
- "143"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:56 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4342691c-bace-4090-84c4-980756fe7dca
status: 404 Not Found
code: 404
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: GET
response:
body: '{"id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","name":"instance_utils_test2","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.796749Z","updated_at":"2024-05-20T13:50:54.796749Z","references":[],"parent_snapshot_id":null,"status":"available","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "404"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:56 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- bebf4d82-75a5-4580-af97-aa7e02e36c51
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volume_id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","volume_type":"sbs_volume"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/a96556aa-8a7e-4068-9914-a37729cccf05/attach-volume
method: POST
response:
body: '{"server": {"id": "a96556aa-8a7e-4068-9914-a37729cccf05", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "volume_type": "sbs_volume", "id": "f760dfca-f930-4a33-aceb-3a024ccf3ff1"},
"1": {"boot": false, "volume_type": "sbs_volume", "id": "097113f9-76d0-4fe7-97f1-ceaa848b3198"}},
"tags": [], "state": "stopped", "protected": false, "state_detail": "", "public_ip":
null, "public_ips": [], "mac_address": "de:00:00:53:3f:51", "routed_ip_enabled":
true, "ipv6": null, "extra_networks": [], "dynamic_ip_required": true, "enable_ipv6":
false, "private_ip": null, "creation_date": "2024-05-20T13:50:54.998615+00:00",
"modification_date": "2024-05-20T13:50:54.998615+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
[], "placement_group": null, "private_nics": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "2273"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:56 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 099a1978-19d9-4efe-8ee9-75b9975b4e98
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/a96556aa-8a7e-4068-9914-a37729cccf05
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:57 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 3d9bafce-b232-44d1-b5f5-2262ebca9a60
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: GET
response:
body: '{"id":"f760dfca-f930-4a33-aceb-3a024ccf3ff1","name":"instance_utils_test","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.682388Z","updated_at":"2024-05-20T13:50:57.235383Z","references":[],"parent_snapshot_id":null,"status":"available","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":"2024-05-20T13:50:57.235383Z","zone":"fr-par-1"}'
headers:
Content-Length:
- "428"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:57 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- cbe6b158-3fa2-456d-b550-9685f7dc030e
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/f760dfca-f930-4a33-aceb-3a024ccf3ff1
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:57 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e76e2541-239c-4cee-b710-25906015fe75
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: GET
response:
body: '{"id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","name":"instance_utils_test2","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.796749Z","updated_at":"2024-05-20T13:50:56.734090Z","references":[{"id":"35f81667-0d38-492c-ae26-e05e0e8cccb5","product_resource_type":"instance_server","product_resource_id":"a96556aa-8a7e-4068-9914-a37729cccf05","created_at":"2024-05-20T13:50:56.734090Z","type":"exclusive","status":"error"}],"parent_snapshot_id":null,"status":"in_use","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "628"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:50:57 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4b3ffa29-8a07-4b7d-96de-ef3f2fcb0d40
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: GET
response:
body: '{"id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","name":"instance_utils_test2","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.796749Z","updated_at":"2024-05-20T13:50:56.734090Z","references":[{"id":"35f81667-0d38-492c-ae26-e05e0e8cccb5","product_resource_type":"instance_server","product_resource_id":"a96556aa-8a7e-4068-9914-a37729cccf05","created_at":"2024-05-20T13:50:56.734090Z","type":"exclusive","status":"error"}],"parent_snapshot_id":null,"status":"in_use","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "628"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:51:02 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 109a352f-f46c-4cf2-8ec7-8f1486a49b5d
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: GET
response:
body: '{"id":"097113f9-76d0-4fe7-97f1-ceaa848b3198","name":"instance_utils_test2","type":"sbs_5k","size":20000000000,"project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","created_at":"2024-05-20T13:50:54.796749Z","updated_at":"2024-05-20T13:51:06.441387Z","references":[],"parent_snapshot_id":null,"status":"available","tags":[],"specs":{"perf_iops":5000,"class":"sbs"},"last_detached_at":null,"zone":"fr-par-1"}'
headers:
Content-Length:
- "404"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:51:07 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b3a64147-b7ca-4f80-b96d-7a8d5ef1de85
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/block/v1alpha1/zones/fr-par-1/volumes/097113f9-76d0-4fe7-97f1-ceaa848b3198
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:51:07 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f4ce92e5-35ea-4772-9103-b2e8bded11d5
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/utils-test.yaml 0000664 0000000 0000000 00000047036 14747113137 0031773 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"instance_utils_test","commercial_type":"PRO2-XXS","image":"81b9475d-e1b5-43c2-ac48-4c1a3b640686","project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers
method: POST
response:
body: '{"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "1ab1d52a-d5eb-4a92-9491-a016ebaae320",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri":
null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test"},
"size": 10000000000, "state": "available", "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:01.233344+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:53:3d:e5",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:01.233344+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2631"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:01 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 066d573a-dfae-4735-85e7-31fb7f635dd5
status: 201 Created
code: 201
duration: ""
- request:
body: '{"project":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/ips
method: POST
response:
body: '{"ip": {"id": "eed4575b-90e5-4102-b956-df874c911e2b", "address": "212.47.248.223",
"prefix": null, "reverse": null, "server": null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "zone": "fr-par-1", "type":
"routed_ipv4", "state": "detached", "tags": [], "ipam_id": "ec78889e-5491-45e1-9ad0-5b2b14e6cdd2"}}'
headers:
Content-Length:
- "366"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:02 GMT
Location:
- https://api.scaleway.com/instance/v1/zones/fr-par-1/ips/eed4575b-90e5-4102-b956-df874c911e2b
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e171a4b0-8534-4ef8-b25c-fea1b39deafa
status: 201 Created
code: 201
duration: ""
- request:
body: '{"server":"42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/ips/eed4575b-90e5-4102-b956-df874c911e2b
method: PATCH
response:
body: '{"ip": {"id": "eed4575b-90e5-4102-b956-df874c911e2b", "address": "212.47.248.223",
"prefix": null, "reverse": null, "server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd",
"name": "instance_utils_test"}, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "zone": "fr-par-1", "type":
"routed_ipv4", "state": "attached", "tags": [], "ipam_id": "ec78889e-5491-45e1-9ad0-5b2b14e6cdd2"}}'
headers:
Content-Length:
- "439"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:05 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 0b7fa0b4-0c33-451a-99ee-5be15289dd02
status: 200 OK
code: 200
duration: ""
- request:
body: '{"server":null}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/ips/eed4575b-90e5-4102-b956-df874c911e2b
method: PATCH
response:
body: '{"ip": {"id": "eed4575b-90e5-4102-b956-df874c911e2b", "address": "212.47.248.223",
"prefix": null, "reverse": null, "server": null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "zone": "fr-par-1", "type":
"routed_ipv4", "state": "detached", "tags": [], "ipam_id": "ec78889e-5491-45e1-9ad0-5b2b14e6cdd2"}}'
headers:
Content-Length:
- "366"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:05 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 44b30676-5443-4c85-9b68-92da0c2ecae1
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/ips/eed4575b-90e5-4102-b956-df874c911e2b
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:06 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- b5186162-33e0-4447-93ec-18a2ce176518
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/1ab1d52a-d5eb-4a92-9491-a016ebaae320
method: GET
response:
body: '{"volume": {"id": "1ab1d52a-d5eb-4a92-9491-a016ebaae320", "name": "Ubuntu
22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri": null, "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test"},
"size": 10000000000, "state": "available", "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:01.233344+00:00", "tags": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "523"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:06 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 0fbd2ca1-97cf-4878-83fb-7f872fd3a77a
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volume_id":"1ab1d52a-d5eb-4a92-9491-a016ebaae320"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd/detach-volume
method: POST
response:
body: '{"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:53:3d:e5",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:01.233344+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2100"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:06 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 14ccb460-2668-4957-a840-f08877f3aaed
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/1ab1d52a-d5eb-4a92-9491-a016ebaae320
method: GET
response:
body: '{"volume": {"id": "1ab1d52a-d5eb-4a92-9491-a016ebaae320", "name": "Ubuntu
22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri": null, "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": null, "size": 10000000000, "state": "available", "creation_date":
"2024-05-20T13:10:01.233344+00:00", "modification_date": "2024-05-20T13:10:06.345862+00:00",
"tags": [], "zone": "fr-par-1"}}'
headers:
Content-Length:
- "450"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:06 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- ff611adb-c71b-42e1-86bc-531775c8c36b
status: 200 OK
code: 200
duration: ""
- request:
body: '{"volume_id":"1ab1d52a-d5eb-4a92-9491-a016ebaae320","volume_type":"b_ssd"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd/attach-volume
method: POST
response:
body: '{"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test",
"arch": "x86_64", "commercial_type": "PRO2-XXS", "boot_type": "local", "organization":
"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"hostname": "instance-utils-test", "image": {"id": "81b9475d-e1b5-43c2-ac48-4c1a3b640686",
"name": "Ubuntu 22.04 Jammy Jellyfish", "organization": "51b656e3-4865-41e8-adbc-0c45bdd780db",
"project": "51b656e3-4865-41e8-adbc-0c45bdd780db", "root_volume": {"id": "235f1b04-c3f6-4245-9530-43fb642ff96d",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "unified", "size": 10000000000},
"extra_volumes": {}, "public": true, "arch": "x86_64", "creation_date": "2023-08-08T13:35:09.293489+00:00",
"modification_date": "2023-08-08T13:35:09.293489+00:00", "default_bootscript":
null, "from_server": null, "state": "available", "tags": [], "zone": "fr-par-1"},
"volumes": {"0": {"boot": false, "id": "1ab1d52a-d5eb-4a92-9491-a016ebaae320",
"name": "Ubuntu 22.04 Jammy Jellyfish", "volume_type": "b_ssd", "export_uri":
null, "organization": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b", "project": "ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b",
"server": {"id": "42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd", "name": "instance_utils_test"},
"size": 10000000000, "state": "available", "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:06.856634+00:00", "tags": [], "zone":
"fr-par-1"}}, "tags": [], "state": "stopped", "protected": false, "state_detail":
"", "public_ip": null, "public_ips": [], "mac_address": "de:00:00:53:3d:e5",
"routed_ip_enabled": true, "ipv6": null, "extra_networks": [], "dynamic_ip_required":
true, "enable_ipv6": false, "private_ip": null, "creation_date": "2024-05-20T13:10:01.233344+00:00",
"modification_date": "2024-05-20T13:10:01.233344+00:00", "bootscript": {"id":
"fdfe150f-a870-4ce4-b432-9f56b5b995c1", "public": true, "title": "x86_64 mainline
4.4.230 rev1", "architecture": "x86_64", "organization": "11111111-1111-4111-8111-111111111111",
"project": "11111111-1111-4111-8111-111111111111", "kernel": "http://10.194.3.9/kernel/x86_64-mainline-lts-4.4-4.4.230-rev1/vmlinuz-4.4.230",
"dtb": "", "initrd": "http://10.194.3.9/initrd/initrd-Linux-x86_64-v3.14.6.gz",
"bootcmdargs": "LINUX_COMMON scaleway boot=local nbd.max_part=16", "default":
true, "zone": "fr-par-1"}, "security_group": {"id": "0fe819c3-274d-472a-b3f5-ddb258d2d8bb",
"name": "Default security group"}, "location": null, "maintenances": [], "allowed_actions":
["poweron", "backup"], "placement_group": null, "private_nics": [], "zone":
"fr-par-1"}}'
headers:
Content-Length:
- "2631"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:07 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 56b248d7-5014-4a67-a038-55942644b77b
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/servers/42faf3a8-03b8-4d1c-a5c3-d241f39b5fbd
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:07 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- d4c2cc33-90ee-4f3b-a2a8-09cfbd830190
status: 204 No Content
code: 204
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/1ab1d52a-d5eb-4a92-9491-a016ebaae320
method: DELETE
response:
body: ""
headers:
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Mon, 20 May 2024 13:10:07 GMT
Server:
- Scaleway API Gateway (fr-par-1;edge02)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- d304b9e4-ebb4-4d3c-aad8-7f1989ac068e
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/testdata/volume-utils-test.yaml 0000664 0000000 0000000 00000007043 14747113137 0033272 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: '{"name":"test volume","organization":"951df375-e094-4d26-97c1-ba548eeb9c42","volume_type":"l_ssd","size":20000000000}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.14.3; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes
method: POST
response:
body: '{"volume": {"id": "fd5ad3da-3123-4726-9a2b-c7647bc89b04", "name": "test
volume", "volume_type": "l_ssd", "export_uri": null, "organization": "951df375-e094-4d26-97c1-ba548eeb9c42",
"server": null, "size": 20000000000, "state": "available", "creation_date":
"2020-05-20T12:39:42.548392+00:00", "modification_date": "2020-05-20T12:39:42.548392+00:00",
"zone": "fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "370"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Wed, 20 May 2020 12:39:42 GMT
Location:
- https://cp-par1.scaleway.com/volumes/fd5ad3da-3123-4726-9a2b-c7647bc89b04
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 6fb1b944-1ad1-417e-8568-ad7dbeb80dde
status: 201 Created
code: 201
duration: ""
- request:
body: '{"name":"some new volume name"}'
form: {}
headers:
Content-Type:
- application/json
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.14.3; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/fd5ad3da-3123-4726-9a2b-c7647bc89b04
method: PATCH
response:
body: '{"volume": {"id": "fd5ad3da-3123-4726-9a2b-c7647bc89b04", "name": "some
new volume name", "volume_type": "l_ssd", "export_uri": null, "organization":
"951df375-e094-4d26-97c1-ba548eeb9c42", "server": null, "size": 20000000000,
"state": "available", "creation_date": "2020-05-20T12:39:42.548392+00:00", "modification_date":
"2020-05-20T12:39:42.548392+00:00", "zone": "fr-par-1"}}'
headers:
Cache-Control:
- no-cache
Content-Length:
- "379"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Wed, 20 May 2020 12:39:42 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- aa94c984-91fe-4d9e-a504-725b6c87ede0
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.6+dev (go1.14.3; darwin; amd64)
url: https://api.scaleway.com/instance/v1/zones/fr-par-1/volumes/fd5ad3da-3123-4726-9a2b-c7647bc89b04
method: DELETE
response:
body: ""
headers:
Cache-Control:
- no-cache
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Wed, 20 May 2020 12:39:42 GMT
Server:
- scaleway_api
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f031e794-2e6c-4ac9-ade2-01e3d13c3a36
status: 204 No Content
code: 204
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/volume_utils.go 0000664 0000000 0000000 00000005745 14747113137 0030240 0 ustar 00root root 0000000 0000000 package instance
import (
goerrors "errors"
"time"
block "github.com/scaleway/scaleway-sdk-go/api/block/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForImageRequest is used by WaitForImage method.
type WaitForVolumeRequest struct {
VolumeID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForSnapshot wait for the snapshot to be in a "terminal state" before returning.
func (s *API) WaitForVolume(req *WaitForVolumeRequest, opts ...scw.RequestOption) (*Volume, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[VolumeState]struct{}{
VolumeStateAvailable: {},
VolumeStateError: {},
}
volume, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetVolume(&GetVolumeRequest{
VolumeID: req.VolumeID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Volume.State]
return res.Volume, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for volume failed")
}
return volume.(*Volume), nil
}
type unknownVolume struct {
ID string
ServerID *string
Type VolumeVolumeType
}
type getUnknownVolumeRequest struct {
Zone scw.Zone
VolumeID string
IsBlockVolume *bool
}
// getUnknownVolume is used to get a volume that can be either from instance or block API
func (s *API) getUnknownVolume(req *getUnknownVolumeRequest, opts ...scw.RequestOption) (*unknownVolume, error) {
volume := &unknownVolume{
ID: req.VolumeID,
}
// Try instance API
if req.IsBlockVolume == nil || !*req.IsBlockVolume {
getVolumeResponse, err := s.GetVolume(&GetVolumeRequest{
Zone: req.Zone,
VolumeID: req.VolumeID,
}, opts...)
notFoundErr := &scw.ResourceNotFoundError{}
if err != nil && !goerrors.As(err, ¬FoundErr) {
return nil, err
}
if getVolumeResponse != nil {
if getVolumeResponse.Volume != nil && getVolumeResponse.Volume.Server != nil {
volume.ServerID = &getVolumeResponse.Volume.Server.ID
}
volume.Type = getVolumeResponse.Volume.VolumeType
}
}
if volume.Type == "" && (req.IsBlockVolume == nil || *req.IsBlockVolume) {
getVolumeResponse, err := block.NewAPI(s.client).GetVolume(&block.GetVolumeRequest{
Zone: req.Zone,
VolumeID: req.VolumeID,
}, opts...)
if err != nil {
return nil, err
}
for _, reference := range getVolumeResponse.References {
if reference.ProductResourceType == "instance_server" {
volume.ServerID = &reference.ProductResourceID
}
}
volume.Type = VolumeVolumeTypeSbsVolume
}
return volume, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/instance/v1/volume_utils_test.go 0000664 0000000 0000000 00000003320 14747113137 0031262 0 ustar 00root root 0000000 0000000 package instance
import (
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestUpdateVolume(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("volume-utils-test")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
instanceAPI := NewAPI(client)
var (
zone = scw.ZoneFrPar1
project = "951df375-e094-4d26-97c1-ba548eeb9c42"
volumeName = "test volume"
volumeSize = 20 * scw.GB
volumeType = VolumeVolumeTypeLSSD
newVolumeName = "some new volume name"
volumeID string
)
// Create volume
createVolumeResponse, err := instanceAPI.CreateVolume(&CreateVolumeRequest{
Zone: zone,
Name: volumeName,
Project: &project,
Size: &volumeSize,
VolumeType: volumeType,
})
testhelpers.AssertNoError(t, err)
volumeID = createVolumeResponse.Volume.ID
// Update volume and test whether successfully updated
updateVolumeResponse, err := instanceAPI.UpdateVolume(&UpdateVolumeRequest{
Zone: zone,
Name: &newVolumeName,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
testhelpers.Assert(t, updateVolumeResponse.Volume != nil, "Should have volume in response")
testhelpers.Equals(t, newVolumeName, updateVolumeResponse.Volume.Name)
testhelpers.Equals(t, volumeSize, updateVolumeResponse.Volume.Size) // check that server is not changed
// Delete Volume
err = instanceAPI.DeleteVolume(&DeleteVolumeRequest{
Zone: zone,
VolumeID: volumeID,
})
testhelpers.AssertNoError(t, err)
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/interlink/ 0000775 0000000 0000000 00000000000 14747113137 0025014 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/interlink/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0026257 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/interlink/v1beta1/interlink_sdk.go 0000664 0000000 0000000 00000136124 14747113137 0031455 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package interlink provides methods and message types of the interlink v1beta1 API.
package interlink
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type BgpStatus string
const (
BgpStatusUnknownBgpStatus = BgpStatus("unknown_bgp_status")
BgpStatusUp = BgpStatus("up")
BgpStatusDown = BgpStatus("down")
)
func (enum BgpStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_bgp_status"
}
return string(enum)
}
func (enum BgpStatus) Values() []BgpStatus {
return []BgpStatus{
"unknown_bgp_status",
"up",
"down",
}
}
func (enum BgpStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BgpStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BgpStatus(BgpStatus(tmp).String())
return nil
}
type LinkStatus string
const (
LinkStatusUnknownLinkStatus = LinkStatus("unknown_link_status")
LinkStatusConfiguring = LinkStatus("configuring")
LinkStatusFailed = LinkStatus("failed")
LinkStatusRequested = LinkStatus("requested")
LinkStatusRefused = LinkStatus("refused")
LinkStatusExpired = LinkStatus("expired")
LinkStatusProvisioning = LinkStatus("provisioning")
LinkStatusActive = LinkStatus("active")
LinkStatusLimitedConnectivity = LinkStatus("limited_connectivity")
LinkStatusAllDown = LinkStatus("all_down")
LinkStatusDeprovisioning = LinkStatus("deprovisioning")
LinkStatusDeleted = LinkStatus("deleted")
LinkStatusLocked = LinkStatus("locked")
)
func (enum LinkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_link_status"
}
return string(enum)
}
func (enum LinkStatus) Values() []LinkStatus {
return []LinkStatus{
"unknown_link_status",
"configuring",
"failed",
"requested",
"refused",
"expired",
"provisioning",
"active",
"limited_connectivity",
"all_down",
"deprovisioning",
"deleted",
"locked",
}
}
func (enum LinkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LinkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LinkStatus(LinkStatus(tmp).String())
return nil
}
type ListLinksRequestOrderBy string
const (
ListLinksRequestOrderByCreatedAtAsc = ListLinksRequestOrderBy("created_at_asc")
ListLinksRequestOrderByCreatedAtDesc = ListLinksRequestOrderBy("created_at_desc")
ListLinksRequestOrderByNameAsc = ListLinksRequestOrderBy("name_asc")
ListLinksRequestOrderByNameDesc = ListLinksRequestOrderBy("name_desc")
ListLinksRequestOrderByStatusAsc = ListLinksRequestOrderBy("status_asc")
ListLinksRequestOrderByStatusDesc = ListLinksRequestOrderBy("status_desc")
)
func (enum ListLinksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListLinksRequestOrderBy) Values() []ListLinksRequestOrderBy {
return []ListLinksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
}
}
func (enum ListLinksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListLinksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListLinksRequestOrderBy(ListLinksRequestOrderBy(tmp).String())
return nil
}
type ListPartnersRequestOrderBy string
const (
ListPartnersRequestOrderByNameAsc = ListPartnersRequestOrderBy("name_asc")
ListPartnersRequestOrderByNameDesc = ListPartnersRequestOrderBy("name_desc")
)
func (enum ListPartnersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListPartnersRequestOrderBy) Values() []ListPartnersRequestOrderBy {
return []ListPartnersRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListPartnersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPartnersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPartnersRequestOrderBy(ListPartnersRequestOrderBy(tmp).String())
return nil
}
type ListPopsRequestOrderBy string
const (
ListPopsRequestOrderByNameAsc = ListPopsRequestOrderBy("name_asc")
ListPopsRequestOrderByNameDesc = ListPopsRequestOrderBy("name_desc")
)
func (enum ListPopsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListPopsRequestOrderBy) Values() []ListPopsRequestOrderBy {
return []ListPopsRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListPopsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPopsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPopsRequestOrderBy(ListPopsRequestOrderBy(tmp).String())
return nil
}
type ListRoutingPoliciesRequestOrderBy string
const (
ListRoutingPoliciesRequestOrderByCreatedAtAsc = ListRoutingPoliciesRequestOrderBy("created_at_asc")
ListRoutingPoliciesRequestOrderByCreatedAtDesc = ListRoutingPoliciesRequestOrderBy("created_at_desc")
ListRoutingPoliciesRequestOrderByNameAsc = ListRoutingPoliciesRequestOrderBy("name_asc")
ListRoutingPoliciesRequestOrderByNameDesc = ListRoutingPoliciesRequestOrderBy("name_desc")
)
func (enum ListRoutingPoliciesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRoutingPoliciesRequestOrderBy) Values() []ListRoutingPoliciesRequestOrderBy {
return []ListRoutingPoliciesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListRoutingPoliciesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRoutingPoliciesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRoutingPoliciesRequestOrderBy(ListRoutingPoliciesRequestOrderBy(tmp).String())
return nil
}
// Link: link.
type Link struct {
// ID: unique identifier of the link.
ID string `json:"id"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// OrganizationID: organization ID.
OrganizationID string `json:"organization_id"`
// Name: name of the link.
Name string `json:"name"`
// Tags: list of tags associated with the link.
Tags []string `json:"tags"`
// PopID: ID of the PoP where the link's corresponding port is located.
PopID string `json:"pop_id"`
// PartnerID: ID of the partner facilitating this link.
PartnerID *string `json:"partner_id"`
// BandwidthMbps: rate limited bandwidth of the link.
BandwidthMbps uint64 `json:"bandwidth_mbps"`
// Status: status of the link.
// Default value: unknown_link_status
Status LinkStatus `json:"status"`
// BgpV4Status: status of the link's BGP IPv4 session.
// Default value: unknown_bgp_status
BgpV4Status BgpStatus `json:"bgp_v4_status"`
// BgpV6Status: status of the link's BGP IPv6 session.
// Default value: unknown_bgp_status
BgpV6Status BgpStatus `json:"bgp_v6_status"`
// VpcID: ID of the Scaleway VPC attached to the link.
VpcID *string `json:"vpc_id"`
// RoutingPolicyID: ID of the routing policy attached to the link.
RoutingPolicyID *string `json:"routing_policy_id"`
// EnableRoutePropagation: defines whether route propagation is enabled or not. To enable or disable route propagation, use the dedicated endpoint.
EnableRoutePropagation bool `json:"enable_route_propagation"`
// CreatedAt: creation date of the link.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the link.
UpdatedAt *time.Time `json:"updated_at"`
// PairingKey: used to identify a link from a user or partner's point of view.
PairingKey string `json:"pairing_key"`
// DisapprovedReason: reason given by partner to explain why they did not approve the request for a hosted link.
DisapprovedReason *string `json:"disapproved_reason"`
// Region: region of the link.
Region scw.Region `json:"region"`
}
// Partner: partner.
type Partner struct {
// ID: unique identifier of the partner.
ID string `json:"id"`
// Name: name of the partner.
Name string `json:"name"`
// ContactEmail: contact email address of partner.
ContactEmail string `json:"contact_email"`
// LogoURL: image URL of the partner's logo.
LogoURL string `json:"logo_url"`
// PortalURL: URL of the partner's portal.
PortalURL string `json:"portal_url"`
// CreatedAt: creation date of the partner.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the partner.
UpdatedAt *time.Time `json:"updated_at"`
}
// Pop: pop.
type Pop struct {
// ID: unique identifier of the PoP.
ID string `json:"id"`
// Name: name of the PoP. It is the common reference of Hosting DC (ex: TH2).
Name string `json:"name"`
// HostingProviderName: name of the PoP's hosting provider, e.g. Telehouse for TH2 or OpCore for DC3.
HostingProviderName string `json:"hosting_provider_name"`
// Address: physical address of the PoP.
Address string `json:"address"`
// City: city where PoP is located.
City string `json:"city"`
// LogoURL: image URL of the PoP's logo.
LogoURL string `json:"logo_url"`
// AvailableLinkBandwidthsMbps: available bandwidth in Mbits/s for future hosted_links from available ports in this PoP.
AvailableLinkBandwidthsMbps []uint64 `json:"available_link_bandwidths_mbps"`
// Region: region of the PoP.
Region scw.Region `json:"region"`
}
// RoutingPolicy: routing policy.
type RoutingPolicy struct {
// ID: unique identifier of the routing policy.
ID string `json:"id"`
// ProjectID: project ID.
ProjectID string `json:"project_id"`
// OrganizationID: organization ID.
OrganizationID string `json:"organization_id"`
// Name: name of the routing policy.
Name string `json:"name"`
// Tags: list of tags associated with the routing policy.
Tags []string `json:"tags"`
// PrefixFilterIn: IP prefixes to accept from the peer (ranges of route announcements to accept).
PrefixFilterIn []scw.IPNet `json:"prefix_filter_in"`
// PrefixFilterOut: IP prefix filters to advertise to the peer (ranges of routes to advertise).
PrefixFilterOut []scw.IPNet `json:"prefix_filter_out"`
// CreatedAt: creation date of the routing policy.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last modification date of the routing policy.
UpdatedAt *time.Time `json:"updated_at"`
// Region: region of the routing policy.
Region scw.Region `json:"region"`
}
// AttachRoutingPolicyRequest: attach routing policy request.
type AttachRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to attach a routing policy to.
LinkID string `json:"-"`
// RoutingPolicyID: ID of the routing policy to be attached.
RoutingPolicyID string `json:"routing_policy_id"`
}
// AttachVpcRequest: attach vpc request.
type AttachVpcRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to attach VPC to.
LinkID string `json:"-"`
// VpcID: ID of the VPC to attach.
VpcID string `json:"vpc_id"`
}
// CreateLinkRequest: create link request.
type CreateLinkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to create the link in.
ProjectID string `json:"project_id"`
// Name: name of the link.
Name string `json:"name"`
// Tags: list of tags to apply to the link.
Tags []string `json:"tags"`
// PopID: poP (location) where the link will be created.
PopID string `json:"pop_id"`
// BandwidthMbps: desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the port.
BandwidthMbps uint64 `json:"bandwidth_mbps"`
// Dedicated: if true, a dedicated link (1 link per port, dedicated to one customer) will be crated. It is not necessary to specify a `port_id` or `partner_id`. A new port will created and assigned to the link. Note that Scaleway has not yet enabled the creation of dedicated links, this field is reserved for future use.
// Precisely one of Dedicated, PortID, PartnerID must be set.
Dedicated *bool `json:"dedicated,omitempty"`
// PortID: if set, a shared link (N links per port, one of which is this customer's port) will be created. As the customer, specify the ID of the port you already have for this link. Note that shared links are not currently available. Note that Scaleway has not yet enabled the creation of shared links, this field is reserved for future use.
// Precisely one of Dedicated, PortID, PartnerID must be set.
PortID *string `json:"port_id,omitempty"`
// PartnerID: if set, a hosted link (N links per port on a partner port) will be created. Specify the ID of the chosen partner, who already has a shareable port with available bandwidth. Note that this is currently the only type of link offered by Scaleway, and therefore this field must be set when creating a link.
// Precisely one of Dedicated, PortID, PartnerID must be set.
PartnerID *string `json:"partner_id,omitempty"`
}
// CreateRoutingPolicyRequest: create routing policy request.
type CreateRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to create the routing policy in.
ProjectID string `json:"project_id"`
// Name: name of the routing policy.
Name string `json:"name"`
// Tags: list of tags to apply to the routing policy.
Tags []string `json:"tags"`
// PrefixFilterIn: IP prefixes to accept from the peer (ranges of route announcements to accept).
PrefixFilterIn []scw.IPNet `json:"prefix_filter_in"`
// PrefixFilterOut: IP prefix filters to advertise to the peer (ranges of routes to advertise).
PrefixFilterOut []scw.IPNet `json:"prefix_filter_out"`
}
// DeleteLinkRequest: delete link request.
type DeleteLinkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to delete.
LinkID string `json:"-"`
}
// DeleteRoutingPolicyRequest: delete routing policy request.
type DeleteRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RoutingPolicyID: ID of the routing policy to delete.
RoutingPolicyID string `json:"-"`
}
// DetachRoutingPolicyRequest: detach routing policy request.
type DetachRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to detach a routing policy from.
LinkID string `json:"-"`
}
// DetachVpcRequest: detach vpc request.
type DetachVpcRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to detach the VPC from.
LinkID string `json:"-"`
}
// DisableRoutePropagationRequest: disable route propagation request.
type DisableRoutePropagationRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link on which to disable route propagation.
LinkID string `json:"-"`
}
// EnableRoutePropagationRequest: enable route propagation request.
type EnableRoutePropagationRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link on which to enable route propagation.
LinkID string `json:"-"`
}
// GetLinkRequest: get link request.
type GetLinkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to get.
LinkID string `json:"-"`
}
// GetPartnerRequest: get partner request.
type GetPartnerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PartnerID: ID of partner to get.
PartnerID string `json:"-"`
}
// GetPopRequest: get pop request.
type GetPopRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PopID: ID of PoP to get.
PopID string `json:"-"`
}
// GetRoutingPolicyRequest: get routing policy request.
type GetRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RoutingPolicyID: ID of the routing policy to get.
RoutingPolicyID string `json:"-"`
}
// ListLinksRequest: list links request.
type ListLinksRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListLinksRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of links to return per page.
PageSize *uint32 `json:"-"`
// ProjectID: project ID to filter for.
ProjectID *string `json:"-"`
// OrganizationID: organization ID to filter for.
OrganizationID *string `json:"-"`
// Name: link name to filter for.
Name *string `json:"-"`
// Tags: tags to filter for.
Tags []string `json:"-"`
// Status: link status to filter for.
// Default value: unknown_link_status
Status LinkStatus `json:"-"`
// BgpV4Status: bGP IPv4 status to filter for.
// Default value: unknown_bgp_status
BgpV4Status BgpStatus `json:"-"`
// BgpV6Status: bGP IPv6 status to filter for.
// Default value: unknown_bgp_status
BgpV6Status BgpStatus `json:"-"`
// PopID: filter for links attached to this PoP (via ports).
PopID *string `json:"-"`
// BandwidthMbps: filter for link bandwidth (in Mbps).
BandwidthMbps *uint64 `json:"-"`
// PartnerID: filter for links hosted by this partner.
PartnerID *string `json:"-"`
// VpcID: filter for links attached to this VPC.
VpcID *string `json:"-"`
// RoutingPolicyID: filter for links using this routing policy.
RoutingPolicyID *string `json:"-"`
// PairingKey: filter for the link with this pairing_key.
PairingKey *string `json:"-"`
}
// ListLinksResponse: list links response.
type ListLinksResponse struct {
// Links: list of links on the current page.
Links []*Link `json:"links"`
// TotalCount: total number of links.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLinksResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLinksResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListLinksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Links = append(r.Links, results.Links...)
r.TotalCount += uint64(len(results.Links))
return uint64(len(results.Links)), nil
}
// ListPartnersRequest: list partners request.
type ListPartnersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: order in which to return results.
// Default value: name_asc
OrderBy ListPartnersRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of partners to return per page.
PageSize *uint32 `json:"-"`
// PopIDs: filter for partners present (offering a port) in one of these PoPs.
PopIDs []string `json:"-"`
}
// ListPartnersResponse: list partners response.
type ListPartnersResponse struct {
// Partners: list of partners on current page.
Partners []*Partner `json:"partners"`
// TotalCount: total number of partners returned.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPartnersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPartnersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPartnersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Partners = append(r.Partners, results.Partners...)
r.TotalCount += uint64(len(results.Partners))
return uint64(len(results.Partners)), nil
}
// ListPopsRequest: list pops request.
type ListPopsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: order in which to return results.
// Default value: name_asc
OrderBy ListPopsRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of PoPs to return per page.
PageSize *uint32 `json:"-"`
// Name: poP name to filter for.
Name *string `json:"-"`
// HostingProviderName: hosting provider name to filter for.
HostingProviderName *string `json:"-"`
// PartnerID: filter for PoPs hosting an available shared port from this partner.
PartnerID *string `json:"-"`
// LinkBandwidthMbps: filter for PoPs with a shared port allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity.
LinkBandwidthMbps *uint64 `json:"-"`
}
// ListPopsResponse: list pops response.
type ListPopsResponse struct {
// Pops: list of PoPs on the current page.
Pops []*Pop `json:"pops"`
// TotalCount: total number of PoPs.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPopsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPopsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPopsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Pops = append(r.Pops, results.Pops...)
r.TotalCount += uint64(len(results.Pops))
return uint64(len(results.Pops)), nil
}
// ListRoutingPoliciesRequest: list routing policies request.
type ListRoutingPoliciesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListRoutingPoliciesRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of routing policies to return per page.
PageSize *uint32 `json:"-"`
// ProjectID: project ID to filter for.
ProjectID *string `json:"-"`
// OrganizationID: organization ID to filter for.
OrganizationID *string `json:"-"`
// Name: routing policy name to filter for.
Name *string `json:"-"`
// Tags: tags to filter for.
Tags []string `json:"-"`
}
// ListRoutingPoliciesResponse: list routing policies response.
type ListRoutingPoliciesResponse struct {
RoutingPolicies []*RoutingPolicy `json:"routing_policies"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRoutingPoliciesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRoutingPoliciesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListRoutingPoliciesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.RoutingPolicies = append(r.RoutingPolicies, results.RoutingPolicies...)
r.TotalCount += uint64(len(results.RoutingPolicies))
return uint64(len(results.RoutingPolicies)), nil
}
// UpdateLinkRequest: update link request.
type UpdateLinkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LinkID: ID of the link to update.
LinkID string `json:"-"`
// Name: name of the link.
Name *string `json:"name,omitempty"`
// Tags: list of tags to apply to the link.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateRoutingPolicyRequest: update routing policy request.
type UpdateRoutingPolicyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RoutingPolicyID: ID of the routing policy to update.
RoutingPolicyID string `json:"-"`
// Name: name of the routing policy.
Name *string `json:"name,omitempty"`
// Tags: list of tags to apply to the routing policy.
Tags *[]string `json:"tags,omitempty"`
// PrefixFilterIn: IP prefixes to accept from the peer (ranges of route announcements to accept).
PrefixFilterIn *[]string `json:"prefix_filter_in,omitempty"`
// PrefixFilterOut: IP prefix filters for routes to advertise to the peer (ranges of routes to advertise).
PrefixFilterOut *[]string `json:"prefix_filter_out,omitempty"`
}
// This API allows you to manage your Scaleway InterLink, to connect your on-premises infrastructure with your Scaleway VPC.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListPartners: List all available partners. By default, the partners returned in the list are ordered by name in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListPartners(req *ListPartnersRequest, opts ...scw.RequestOption) (*ListPartnersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "pop_ids", req.PopIDs)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/partners",
Query: query,
}
var resp ListPartnersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPartner: Get a partner for the given partner IP. The response object includes information such as the partner's name, email address and portal URL.
func (s *API) GetPartner(req *GetPartnerRequest, opts ...scw.RequestOption) (*Partner, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PartnerID) == "" {
return nil, errors.New("field PartnerID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/partners/" + fmt.Sprint(req.PartnerID) + "",
}
var resp Partner
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPops: List all available PoPs (locations) for a given region. By default, the results are returned in ascending alphabetical order by name.
func (s *API) ListPops(req *ListPopsRequest, opts ...scw.RequestOption) (*ListPopsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "hosting_provider_name", req.HostingProviderName)
parameter.AddToQuery(query, "partner_id", req.PartnerID)
parameter.AddToQuery(query, "link_bandwidth_mbps", req.LinkBandwidthMbps)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/pops",
Query: query,
}
var resp ListPopsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPop: Get a PoP for the given PoP ID. The response object includes the PoP's name and information about its physical location.
func (s *API) GetPop(req *GetPopRequest, opts ...scw.RequestOption) (*Pop, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PopID) == "" {
return nil, errors.New("field PopID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/pops/" + fmt.Sprint(req.PopID) + "",
}
var resp Pop
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListLinks: List all your links (InterLink connections). A number of filters are available, including Project ID, name, tags and status.
func (s *API) ListLinks(req *ListLinksRequest, opts ...scw.RequestOption) (*ListLinksResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "bgp_v4_status", req.BgpV4Status)
parameter.AddToQuery(query, "bgp_v6_status", req.BgpV6Status)
parameter.AddToQuery(query, "pop_id", req.PopID)
parameter.AddToQuery(query, "bandwidth_mbps", req.BandwidthMbps)
parameter.AddToQuery(query, "partner_id", req.PartnerID)
parameter.AddToQuery(query, "vpc_id", req.VpcID)
parameter.AddToQuery(query, "routing_policy_id", req.RoutingPolicyID)
parameter.AddToQuery(query, "pairing_key", req.PairingKey)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links",
Query: query,
}
var resp ListLinksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetLink: Get a link (InterLink connection) for the given link ID. The response object includes information about the link's various configuration details.
func (s *API) GetLink(req *GetLinkRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "",
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateLink: Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (faciliated by partners) are available, though in the future dedicated and shared links will also be possible.
func (s *API) CreateLink(req *CreateLinkRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateLink: Update an existing link, specified by its link ID. Only its name and tags can be updated.
func (s *API) UpdateLink(req *UpdateLinkRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteLink: Delete an existing link, specified by its link ID. Note that as well as deleting the link here on the Scaleway side, it is also necessary to request deletion from the partner on their side. Only when this action has been carried out on both sides will the resource be completely deleted.
func (s *API) DeleteLink(req *DeleteLinkRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "",
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachVpc: Attach a VPC to an existing link. This facilitates communication between the resources in your Scaleway VPC, and your on-premises infrastructure.
func (s *API) AttachVpc(req *AttachVpcRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/attach-vpc",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachVpc: Detach a VPC from an existing link.
func (s *API) DetachVpc(req *DetachVpcRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/detach-vpc",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachRoutingPolicy: Attach a routing policy to an existing link. As all routes across the link are blocked by default, you must attach a routing policy to set IP prefix filters for allowed routes, facilitating traffic flow.
func (s *API) AttachRoutingPolicy(req *AttachRoutingPolicyRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/attach-routing-policy",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachRoutingPolicy: Detach a routing policy from an existing link. Without a routing policy, all routes across the link are blocked by default.
func (s *API) DetachRoutingPolicy(req *DetachRoutingPolicyRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/detach-routing-policy",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableRoutePropagation: Enable all allowed prefixes (defined in a routing policy) to be announced in the BGP session. This allows traffic to flow between the attached VPC and the on-premises infrastructure along the announced routes. Note that by default, even when route propagation is enabled, all routes are blocked. It is essential to attach a routing policy to define the ranges of routes to announce.
func (s *API) EnableRoutePropagation(req *EnableRoutePropagationRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/enable-route-propagation",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableRoutePropagation: Prevent any prefixes from being announced in the BGP session. Traffic will not be able to flow over the InterLink until route propagation is re-enabled.
func (s *API) DisableRoutePropagation(req *DisableRoutePropagationRequest, opts ...scw.RequestOption) (*Link, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LinkID) == "" {
return nil, errors.New("field LinkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/links/" + fmt.Sprint(req.LinkID) + "/disable-route-propagation",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Link
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRoutingPolicies: List all routing policies in a given region. A routing policy can be attached to one or multiple links (InterLink connections).
func (s *API) ListRoutingPolicies(req *ListRoutingPoliciesRequest, opts ...scw.RequestOption) (*ListRoutingPoliciesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/routing-policies",
Query: query,
}
var resp ListRoutingPoliciesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRoutingPolicy: Get a routing policy for the given routing policy ID. The response object gives information including the policy's name, tags and prefix filters.
func (s *API) GetRoutingPolicy(req *GetRoutingPolicyRequest, opts ...scw.RequestOption) (*RoutingPolicy, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RoutingPolicyID) == "" {
return nil, errors.New("field RoutingPolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/routing-policies/" + fmt.Sprint(req.RoutingPolicyID) + "",
}
var resp RoutingPolicy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRoutingPolicy: Create a routing policy. Routing policies allow you to set IP prefix filters to define the incoming route announcements to accept from the peer, and the outgoing routes to announce to the peer.
func (s *API) CreateRoutingPolicy(req *CreateRoutingPolicyRequest, opts ...scw.RequestOption) (*RoutingPolicy, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/routing-policies",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RoutingPolicy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRoutingPolicy: Update an existing routing policy, specified by its routing policy ID. Its name, tags and incoming/outgoing prefix filters can be updated.
func (s *API) UpdateRoutingPolicy(req *UpdateRoutingPolicyRequest, opts ...scw.RequestOption) (*RoutingPolicy, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RoutingPolicyID) == "" {
return nil, errors.New("field RoutingPolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/routing-policies/" + fmt.Sprint(req.RoutingPolicyID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RoutingPolicy
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRoutingPolicy: Delete an existing routing policy, specified by its routing policy ID.
func (s *API) DeleteRoutingPolicy(req *DeleteRoutingPolicyRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RoutingPolicyID) == "" {
return errors.New("field RoutingPolicyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/interlink/v1beta1/regions/" + fmt.Sprint(req.Region) + "/routing-policies/" + fmt.Sprint(req.RoutingPolicyID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/ 0000775 0000000 0000000 00000000000 14747113137 0023610 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024136 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/v1/iot_helpers.go 0000664 0000000 0000000 00000002724 14747113137 0027007 0 ustar 00root root 0000000 0000000 package iot
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
waitForHubDefaultTimeout = 15 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForHubRequest is used by WaitForHub method.
type WaitForHubRequest struct {
HubID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForHub waits for the hub to be in a ready state before returning.
func (s *API) WaitForHub(req *WaitForHubRequest, opts ...scw.RequestOption) (*Hub, error) {
timeout := waitForHubDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[HubStatus]struct{}{
HubStatusError: {},
HubStatusReady: {},
HubStatusDisabled: {},
}
hub, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
hub, err := s.GetHub(&GetHubRequest{
HubID: req.HubID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[hub.Status]
return hub, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for hub failed")
}
return hub.(*Hub), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/v1/iot_sdk.go 0000664 0000000 0000000 00000245343 14747113137 0026134 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package iot provides methods and message types of the iot v1 API.
package iot
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DeviceMessageFiltersRulePolicy string
const (
DeviceMessageFiltersRulePolicyUnknown = DeviceMessageFiltersRulePolicy("unknown")
DeviceMessageFiltersRulePolicyAccept = DeviceMessageFiltersRulePolicy("accept")
DeviceMessageFiltersRulePolicyReject = DeviceMessageFiltersRulePolicy("reject")
)
func (enum DeviceMessageFiltersRulePolicy) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DeviceMessageFiltersRulePolicy) Values() []DeviceMessageFiltersRulePolicy {
return []DeviceMessageFiltersRulePolicy{
"unknown",
"accept",
"reject",
}
}
func (enum DeviceMessageFiltersRulePolicy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DeviceMessageFiltersRulePolicy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DeviceMessageFiltersRulePolicy(DeviceMessageFiltersRulePolicy(tmp).String())
return nil
}
type DeviceStatus string
const (
DeviceStatusUnknown = DeviceStatus("unknown")
DeviceStatusError = DeviceStatus("error")
DeviceStatusEnabled = DeviceStatus("enabled")
DeviceStatusDisabled = DeviceStatus("disabled")
)
func (enum DeviceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DeviceStatus) Values() []DeviceStatus {
return []DeviceStatus{
"unknown",
"error",
"enabled",
"disabled",
}
}
func (enum DeviceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DeviceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DeviceStatus(DeviceStatus(tmp).String())
return nil
}
type HubProductPlan string
const (
HubProductPlanPlanUnknown = HubProductPlan("plan_unknown")
HubProductPlanPlanShared = HubProductPlan("plan_shared")
HubProductPlanPlanDedicated = HubProductPlan("plan_dedicated")
HubProductPlanPlanHa = HubProductPlan("plan_ha")
)
func (enum HubProductPlan) String() string {
if enum == "" {
// return default value if empty
return "plan_unknown"
}
return string(enum)
}
func (enum HubProductPlan) Values() []HubProductPlan {
return []HubProductPlan{
"plan_unknown",
"plan_shared",
"plan_dedicated",
"plan_ha",
}
}
func (enum HubProductPlan) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HubProductPlan) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HubProductPlan(HubProductPlan(tmp).String())
return nil
}
type HubStatus string
const (
HubStatusUnknown = HubStatus("unknown")
HubStatusError = HubStatus("error")
HubStatusEnabling = HubStatus("enabling")
HubStatusReady = HubStatus("ready")
HubStatusDisabling = HubStatus("disabling")
HubStatusDisabled = HubStatus("disabled")
)
func (enum HubStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum HubStatus) Values() []HubStatus {
return []HubStatus{
"unknown",
"error",
"enabling",
"ready",
"disabling",
"disabled",
}
}
func (enum HubStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HubStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HubStatus(HubStatus(tmp).String())
return nil
}
type ListDevicesRequestOrderBy string
const (
ListDevicesRequestOrderByNameAsc = ListDevicesRequestOrderBy("name_asc")
ListDevicesRequestOrderByNameDesc = ListDevicesRequestOrderBy("name_desc")
ListDevicesRequestOrderByStatusAsc = ListDevicesRequestOrderBy("status_asc")
ListDevicesRequestOrderByStatusDesc = ListDevicesRequestOrderBy("status_desc")
ListDevicesRequestOrderByHubIDAsc = ListDevicesRequestOrderBy("hub_id_asc")
ListDevicesRequestOrderByHubIDDesc = ListDevicesRequestOrderBy("hub_id_desc")
ListDevicesRequestOrderByCreatedAtAsc = ListDevicesRequestOrderBy("created_at_asc")
ListDevicesRequestOrderByCreatedAtDesc = ListDevicesRequestOrderBy("created_at_desc")
ListDevicesRequestOrderByUpdatedAtAsc = ListDevicesRequestOrderBy("updated_at_asc")
ListDevicesRequestOrderByUpdatedAtDesc = ListDevicesRequestOrderBy("updated_at_desc")
ListDevicesRequestOrderByAllowInsecureAsc = ListDevicesRequestOrderBy("allow_insecure_asc")
ListDevicesRequestOrderByAllowInsecureDesc = ListDevicesRequestOrderBy("allow_insecure_desc")
)
func (enum ListDevicesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListDevicesRequestOrderBy) Values() []ListDevicesRequestOrderBy {
return []ListDevicesRequestOrderBy{
"name_asc",
"name_desc",
"status_asc",
"status_desc",
"hub_id_asc",
"hub_id_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"allow_insecure_asc",
"allow_insecure_desc",
}
}
func (enum ListDevicesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDevicesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDevicesRequestOrderBy(ListDevicesRequestOrderBy(tmp).String())
return nil
}
type ListHubsRequestOrderBy string
const (
ListHubsRequestOrderByNameAsc = ListHubsRequestOrderBy("name_asc")
ListHubsRequestOrderByNameDesc = ListHubsRequestOrderBy("name_desc")
ListHubsRequestOrderByStatusAsc = ListHubsRequestOrderBy("status_asc")
ListHubsRequestOrderByStatusDesc = ListHubsRequestOrderBy("status_desc")
ListHubsRequestOrderByProductPlanAsc = ListHubsRequestOrderBy("product_plan_asc")
ListHubsRequestOrderByProductPlanDesc = ListHubsRequestOrderBy("product_plan_desc")
ListHubsRequestOrderByCreatedAtAsc = ListHubsRequestOrderBy("created_at_asc")
ListHubsRequestOrderByCreatedAtDesc = ListHubsRequestOrderBy("created_at_desc")
ListHubsRequestOrderByUpdatedAtAsc = ListHubsRequestOrderBy("updated_at_asc")
ListHubsRequestOrderByUpdatedAtDesc = ListHubsRequestOrderBy("updated_at_desc")
)
func (enum ListHubsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListHubsRequestOrderBy) Values() []ListHubsRequestOrderBy {
return []ListHubsRequestOrderBy{
"name_asc",
"name_desc",
"status_asc",
"status_desc",
"product_plan_asc",
"product_plan_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListHubsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListHubsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListHubsRequestOrderBy(ListHubsRequestOrderBy(tmp).String())
return nil
}
type ListNetworksRequestOrderBy string
const (
ListNetworksRequestOrderByNameAsc = ListNetworksRequestOrderBy("name_asc")
ListNetworksRequestOrderByNameDesc = ListNetworksRequestOrderBy("name_desc")
ListNetworksRequestOrderByTypeAsc = ListNetworksRequestOrderBy("type_asc")
ListNetworksRequestOrderByTypeDesc = ListNetworksRequestOrderBy("type_desc")
ListNetworksRequestOrderByCreatedAtAsc = ListNetworksRequestOrderBy("created_at_asc")
ListNetworksRequestOrderByCreatedAtDesc = ListNetworksRequestOrderBy("created_at_desc")
)
func (enum ListNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListNetworksRequestOrderBy) Values() []ListNetworksRequestOrderBy {
return []ListNetworksRequestOrderBy{
"name_asc",
"name_desc",
"type_asc",
"type_desc",
"created_at_asc",
"created_at_desc",
}
}
func (enum ListNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNetworksRequestOrderBy(ListNetworksRequestOrderBy(tmp).String())
return nil
}
type ListRoutesRequestOrderBy string
const (
ListRoutesRequestOrderByNameAsc = ListRoutesRequestOrderBy("name_asc")
ListRoutesRequestOrderByNameDesc = ListRoutesRequestOrderBy("name_desc")
ListRoutesRequestOrderByHubIDAsc = ListRoutesRequestOrderBy("hub_id_asc")
ListRoutesRequestOrderByHubIDDesc = ListRoutesRequestOrderBy("hub_id_desc")
ListRoutesRequestOrderByTypeAsc = ListRoutesRequestOrderBy("type_asc")
ListRoutesRequestOrderByTypeDesc = ListRoutesRequestOrderBy("type_desc")
ListRoutesRequestOrderByCreatedAtAsc = ListRoutesRequestOrderBy("created_at_asc")
ListRoutesRequestOrderByCreatedAtDesc = ListRoutesRequestOrderBy("created_at_desc")
)
func (enum ListRoutesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListRoutesRequestOrderBy) Values() []ListRoutesRequestOrderBy {
return []ListRoutesRequestOrderBy{
"name_asc",
"name_desc",
"hub_id_asc",
"hub_id_desc",
"type_asc",
"type_desc",
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRoutesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRoutesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRoutesRequestOrderBy(ListRoutesRequestOrderBy(tmp).String())
return nil
}
type NetworkNetworkType string
const (
NetworkNetworkTypeUnknown = NetworkNetworkType("unknown")
NetworkNetworkTypeSigfox = NetworkNetworkType("sigfox")
NetworkNetworkTypeRest = NetworkNetworkType("rest")
)
func (enum NetworkNetworkType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NetworkNetworkType) Values() []NetworkNetworkType {
return []NetworkNetworkType{
"unknown",
"sigfox",
"rest",
}
}
func (enum NetworkNetworkType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NetworkNetworkType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NetworkNetworkType(NetworkNetworkType(tmp).String())
return nil
}
type RouteDatabaseConfigEngine string
const (
RouteDatabaseConfigEngineUnknown = RouteDatabaseConfigEngine("unknown")
RouteDatabaseConfigEnginePostgresql = RouteDatabaseConfigEngine("postgresql")
RouteDatabaseConfigEngineMysql = RouteDatabaseConfigEngine("mysql")
)
func (enum RouteDatabaseConfigEngine) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RouteDatabaseConfigEngine) Values() []RouteDatabaseConfigEngine {
return []RouteDatabaseConfigEngine{
"unknown",
"postgresql",
"mysql",
}
}
func (enum RouteDatabaseConfigEngine) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RouteDatabaseConfigEngine) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RouteDatabaseConfigEngine(RouteDatabaseConfigEngine(tmp).String())
return nil
}
type RouteRestConfigHTTPVerb string
const (
RouteRestConfigHTTPVerbUnknown = RouteRestConfigHTTPVerb("unknown")
RouteRestConfigHTTPVerbGet = RouteRestConfigHTTPVerb("get")
RouteRestConfigHTTPVerbPost = RouteRestConfigHTTPVerb("post")
RouteRestConfigHTTPVerbPut = RouteRestConfigHTTPVerb("put")
RouteRestConfigHTTPVerbPatch = RouteRestConfigHTTPVerb("patch")
RouteRestConfigHTTPVerbDelete = RouteRestConfigHTTPVerb("delete")
)
func (enum RouteRestConfigHTTPVerb) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RouteRestConfigHTTPVerb) Values() []RouteRestConfigHTTPVerb {
return []RouteRestConfigHTTPVerb{
"unknown",
"get",
"post",
"put",
"patch",
"delete",
}
}
func (enum RouteRestConfigHTTPVerb) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RouteRestConfigHTTPVerb) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RouteRestConfigHTTPVerb(RouteRestConfigHTTPVerb(tmp).String())
return nil
}
type RouteRouteType string
const (
RouteRouteTypeUnknown = RouteRouteType("unknown")
RouteRouteTypeS3 = RouteRouteType("s3")
RouteRouteTypeDatabase = RouteRouteType("database")
RouteRouteTypeRest = RouteRouteType("rest")
)
func (enum RouteRouteType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RouteRouteType) Values() []RouteRouteType {
return []RouteRouteType{
"unknown",
"s3",
"database",
"rest",
}
}
func (enum RouteRouteType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RouteRouteType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RouteRouteType(RouteRouteType(tmp).String())
return nil
}
type RouteS3ConfigS3Strategy string
const (
RouteS3ConfigS3StrategyUnknown = RouteS3ConfigS3Strategy("unknown")
RouteS3ConfigS3StrategyPerTopic = RouteS3ConfigS3Strategy("per_topic")
RouteS3ConfigS3StrategyPerMessage = RouteS3ConfigS3Strategy("per_message")
)
func (enum RouteS3ConfigS3Strategy) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum RouteS3ConfigS3Strategy) Values() []RouteS3ConfigS3Strategy {
return []RouteS3ConfigS3Strategy{
"unknown",
"per_topic",
"per_message",
}
}
func (enum RouteS3ConfigS3Strategy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RouteS3ConfigS3Strategy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RouteS3ConfigS3Strategy(RouteS3ConfigS3Strategy(tmp).String())
return nil
}
// DeviceMessageFiltersRule: device message filters rule.
type DeviceMessageFiltersRule struct {
// Policy: if set to `accept`, all topics in the topics list will be allowed, with all other topics being denied.
// If set to `reject`, all topics in the topics list will be denied, with all other topics being allowed.
// Default value: unknown
Policy DeviceMessageFiltersRulePolicy `json:"policy"`
// Topics: list of topics to accept or reject. It must be valid MQTT topics and up to 65535 characters.
Topics *[]string `json:"topics"`
}
// DeviceMessageFilters: device message filters.
type DeviceMessageFilters struct {
// Publish: filtering rule to restrict topics the device can publish to.
Publish *DeviceMessageFiltersRule `json:"publish"`
// Subscribe: filtering rule to restrict topics the device can subscribe to.
Subscribe *DeviceMessageFiltersRule `json:"subscribe"`
}
// HubTwinsGraphiteConfig: hub twins graphite config.
type HubTwinsGraphiteConfig struct {
PushURI string `json:"push_uri"`
}
// Certificate: certificate.
type Certificate struct {
Crt string `json:"crt"`
Key string `json:"key"`
}
// Device: device.
type Device struct {
// ID: device ID, also used as MQTT Client ID or username.
ID string `json:"id"`
// Name: device name.
Name string `json:"name"`
// Description: device description.
Description string `json:"description"`
// Status: device status.
// Default value: unknown
Status DeviceStatus `json:"status"`
// HubID: hub ID.
HubID string `json:"hub_id"`
// LastActivityAt: last connection/activity date of a device.
LastActivityAt *time.Time `json:"last_activity_at"`
// IsConnected: defines whether the device is connected to the Hub.
IsConnected bool `json:"is_connected"`
// AllowInsecure: defines whether to allow the device to connect to the Hub without TLS mutual authentication.
AllowInsecure bool `json:"allow_insecure"`
// AllowMultipleConnections: defines whether to allow multiple physical devices to connect to the Hub with this device's credentials.
AllowMultipleConnections bool `json:"allow_multiple_connections"`
// MessageFilters: filter-sets to restrict the topics the device can publish/subscribe to.
MessageFilters *DeviceMessageFilters `json:"message_filters"`
// HasCustomCertificate: assigning a custom certificate allows a device to authenticate using that specific certificate without checking the Hub's CA certificate.
HasCustomCertificate bool `json:"has_custom_certificate"`
// CreatedAt: date at which the device was added.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date at which the device was last modified.
UpdatedAt *time.Time `json:"updated_at"`
}
// Network: network.
type Network struct {
// ID: network ID.
ID string `json:"id"`
// Name: network name.
Name string `json:"name"`
// Type: type of network to connect with.
// Default value: unknown
Type NetworkNetworkType `json:"type"`
// Endpoint: endpoint to use for interacting with the network.
Endpoint string `json:"endpoint"`
// HubID: hub ID to connect the Network to.
HubID string `json:"hub_id"`
// CreatedAt: date at which the network was created.
CreatedAt *time.Time `json:"created_at"`
// TopicPrefix: this prefix will be prepended to all topics for this Network.
TopicPrefix string `json:"topic_prefix"`
}
// CreateRouteRequestDatabaseConfig: create route request database config.
type CreateRouteRequestDatabaseConfig struct {
Host string `json:"host"`
Port uint32 `json:"port"`
Dbname string `json:"dbname"`
Username string `json:"username"`
Password string `json:"password"`
Query string `json:"query"`
// Engine: default value: unknown
Engine RouteDatabaseConfigEngine `json:"engine"`
}
// CreateRouteRequestRestConfig: create route request rest config.
type CreateRouteRequestRestConfig struct {
// Verb: default value: unknown
Verb RouteRestConfigHTTPVerb `json:"verb"`
URI string `json:"uri"`
Headers map[string]string `json:"headers"`
}
// CreateRouteRequestS3Config: create route request s3 config.
type CreateRouteRequestS3Config struct {
BucketRegion string `json:"bucket_region"`
BucketName string `json:"bucket_name"`
ObjectPrefix string `json:"object_prefix"`
// Strategy: default value: unknown
Strategy RouteS3ConfigS3Strategy `json:"strategy"`
}
// Hub: hub.
type Hub struct {
// ID: hub ID.
ID string `json:"id"`
// Name: hub name.
Name string `json:"name"`
// Status: current status of the Hub.
// Default value: unknown
Status HubStatus `json:"status"`
// ProductPlan: hub feature set.
// Default value: plan_unknown
ProductPlan HubProductPlan `json:"product_plan"`
// Enabled: defines whether the hub has been enabled.
Enabled bool `json:"enabled"`
// DeviceCount: number of registered devices.
DeviceCount uint64 `json:"device_count"`
// ConnectedDeviceCount: number of currently connected devices.
ConnectedDeviceCount uint64 `json:"connected_device_count"`
// Endpoint: devices should be connected to this host. Port may be 1883 (MQTT), 8883 (MQTT over TLS), 80 (MQTT over Websocket) or 443 (MQTT over Websocket over TLS).
Endpoint string `json:"endpoint"`
// DisableEvents: defines whether to disable Hub events.
DisableEvents bool `json:"disable_events"`
// EventsTopicPrefix: hub events topic prefix.
EventsTopicPrefix string `json:"events_topic_prefix"`
// Region: region of the Hub.
Region scw.Region `json:"region"`
// CreatedAt: hub creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: hub last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// ProjectID: project owning the resource.
ProjectID string `json:"project_id"`
// OrganizationID: organization owning the resource.
OrganizationID string `json:"organization_id"`
// EnableDeviceAutoProvisioning: when an unknown device connects to your hub using a valid certificate chain, it will be automatically provisioned inside your Hub. The Hub uses the common name of the device certifcate to find out if a device with the same name already exists. This setting can only be enabled on a hub with a custom certificate authority.
EnableDeviceAutoProvisioning bool `json:"enable_device_auto_provisioning"`
// HasCustomCa: flag is automatically set to `false` after Hub creation, as Hub certificates are managed by Scaleway. Once a custom certificate authority is set, the flag will be set to `true`.
HasCustomCa bool `json:"has_custom_ca"`
// TwinsGraphiteConfig: bETA - not implemented yet.
// Precisely one of TwinsGraphiteConfig must be set.
TwinsGraphiteConfig *HubTwinsGraphiteConfig `json:"twins_graphite_config,omitempty"`
}
// RouteSummary: route summary.
type RouteSummary struct {
// ID: route ID.
ID string `json:"id"`
// Name: route name.
Name string `json:"name"`
// HubID: hub ID of the route.
HubID string `json:"hub_id"`
// Topic: topic the route subscribes to. It must be a valid MQTT topic and up to 65535 characters.
Topic string `json:"topic"`
// Type: route type.
// Default value: unknown
Type RouteRouteType `json:"type"`
// CreatedAt: date at which the route was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date at which the route was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// ListTwinDocumentsResponseDocumentSummary: list twin documents response document summary.
type ListTwinDocumentsResponseDocumentSummary struct {
// DocumentName: name of the document.
DocumentName string `json:"document_name"`
}
// RouteDatabaseConfig: route database config.
type RouteDatabaseConfig struct {
// Engine: database engine the route will connect to. If not specified, the default database will be 'PostgreSQL'.
// Default value: unknown
Engine RouteDatabaseConfigEngine `json:"engine"`
// Host: database host.
Host string `json:"host"`
// Port: database port.
Port uint32 `json:"port"`
// Dbname: database name.
Dbname string `json:"dbname"`
// Username: database username. Make sure this account can execute the provided query.
Username string `json:"username"`
// Password: database password.
Password string `json:"password"`
// Query: SQL query to be executed ($TOPIC and $PAYLOAD variables are available, see documentation).
Query string `json:"query"`
}
// RouteRestConfig: route rest config.
type RouteRestConfig struct {
// Verb: HTTP verb used to call REST URI.
// Default value: unknown
Verb RouteRestConfigHTTPVerb `json:"verb"`
// URI: URI of the REST endpoint.
URI string `json:"uri"`
// Headers: HTTP call extra headers.
Headers map[string]string `json:"headers"`
}
// RouteS3Config: route s3 config.
type RouteS3Config struct {
// BucketRegion: region of the Amazon S3 route's destination bucket (e.g., 'fr-par').
BucketRegion string `json:"bucket_region"`
// BucketName: destination bucket name of the Amazon S3 route.
BucketName string `json:"bucket_name"`
// ObjectPrefix: optional string to prefix object names with.
ObjectPrefix string `json:"object_prefix"`
// Strategy: how the Amazon S3 route's objects will be created: one per topic or one per message.
// Default value: unknown
Strategy RouteS3ConfigS3Strategy `json:"strategy"`
}
// UpdateRouteRequestDatabaseConfig: update route request database config.
type UpdateRouteRequestDatabaseConfig struct {
Host *string `json:"host"`
Port *uint32 `json:"port"`
Dbname *string `json:"dbname"`
Username *string `json:"username"`
Password *string `json:"password"`
Query *string `json:"query"`
// Engine: default value: unknown
Engine RouteDatabaseConfigEngine `json:"engine"`
}
// UpdateRouteRequestRestConfig: update route request rest config.
type UpdateRouteRequestRestConfig struct {
// Verb: default value: unknown
Verb RouteRestConfigHTTPVerb `json:"verb"`
URI *string `json:"uri"`
Headers *map[string]string `json:"headers"`
}
// UpdateRouteRequestS3Config: update route request s3 config.
type UpdateRouteRequestS3Config struct {
BucketRegion *string `json:"bucket_region"`
BucketName *string `json:"bucket_name"`
ObjectPrefix *string `json:"object_prefix"`
// Strategy: default value: unknown
Strategy RouteS3ConfigS3Strategy `json:"strategy"`
}
// CreateDeviceRequest: create device request.
type CreateDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: device name.
Name string `json:"name"`
// HubID: hub ID of the device.
HubID string `json:"hub_id"`
// AllowInsecure: defines whether to allow plain and server-authenticated SSL connections in addition to mutually-authenticated ones.
AllowInsecure bool `json:"allow_insecure"`
// AllowMultipleConnections: defines whether to allow multiple physical devices to connect with this device's credentials.
AllowMultipleConnections bool `json:"allow_multiple_connections"`
// MessageFilters: filter-sets to authorize or deny the device to publish/subscribe to specific topics.
MessageFilters *DeviceMessageFilters `json:"message_filters,omitempty"`
// Description: device description.
Description *string `json:"description,omitempty"`
}
// CreateDeviceResponse: create device response.
type CreateDeviceResponse struct {
// Device: information related to the created device.
Device *Device `json:"device"`
// Certificate: device certificate.
Certificate *Certificate `json:"certificate"`
}
// CreateHubRequest: create hub request.
type CreateHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: hub name (up to 255 characters).
Name string `json:"name"`
// ProjectID: project/Organization ID to filter for, only Hubs from this Project/Organization will be returned.
ProjectID string `json:"project_id"`
// ProductPlan: hub product plan.
// Default value: plan_unknown
ProductPlan HubProductPlan `json:"product_plan"`
// DisableEvents: disable Hub events.
DisableEvents *bool `json:"disable_events,omitempty"`
// EventsTopicPrefix: topic prefix (default '$SCW/events') of Hub events.
EventsTopicPrefix *string `json:"events_topic_prefix,omitempty"`
// TwinsGraphiteConfig: bETA - not implemented yet.
// Precisely one of TwinsGraphiteConfig must be set.
TwinsGraphiteConfig *HubTwinsGraphiteConfig `json:"twins_graphite_config,omitempty"`
}
// CreateNetworkRequest: create network request.
type CreateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: network name.
Name string `json:"name"`
// Type: type of network to connect with.
// Default value: unknown
Type NetworkNetworkType `json:"type"`
// HubID: hub ID to connect the Network to.
HubID string `json:"hub_id"`
// TopicPrefix: topic prefix for the Network.
TopicPrefix string `json:"topic_prefix"`
}
// CreateNetworkResponse: create network response.
type CreateNetworkResponse struct {
// Network: information related to the created network.
Network *Network `json:"network"`
// Secret: endpoint Key to keep secret. This cannot be retrieved later.
Secret string `json:"secret"`
}
// CreateRouteRequest: create route request.
type CreateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: route name.
Name string `json:"name"`
// HubID: hub ID of the route.
HubID string `json:"hub_id"`
// Topic: topic the route subscribes to. It must be a valid MQTT topic and up to 65535 characters.
Topic string `json:"topic"`
// S3Config: if creating Amazon S3 Routes, Amazon S3-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
S3Config *CreateRouteRequestS3Config `json:"s3_config,omitempty"`
// DbConfig: if creating Database Route, DB-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
DbConfig *CreateRouteRequestDatabaseConfig `json:"db_config,omitempty"`
// RestConfig: if creating Rest Route, Rest-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
RestConfig *CreateRouteRequestRestConfig `json:"rest_config,omitempty"`
}
// DeleteDeviceRequest: delete device request.
type DeleteDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// DeleteHubRequest: delete hub request.
type DeleteHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
// DeleteDevices: defines whether to force the deletion of devices added to this Hub or reject the operation.
DeleteDevices *bool `json:"delete_devices,omitempty"`
}
// DeleteNetworkRequest: delete network request.
type DeleteNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NetworkID: network ID.
NetworkID string `json:"-"`
}
// DeleteRouteRequest: delete route request.
type DeleteRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// DeleteTwinDocumentRequest: delete twin document request.
type DeleteTwinDocumentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
// DocumentName: name of the document.
DocumentName string `json:"-"`
}
// DeleteTwinDocumentsRequest: delete twin documents request.
type DeleteTwinDocumentsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
}
// DisableDeviceRequest: disable device request.
type DisableDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// DisableHubRequest: disable hub request.
type DisableHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
}
// EnableDeviceRequest: enable device request.
type EnableDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// EnableHubRequest: enable hub request.
type EnableHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
}
// GetDeviceCertificateRequest: get device certificate request.
type GetDeviceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// GetDeviceCertificateResponse: get device certificate response.
type GetDeviceCertificateResponse struct {
// Device: information related to the created device.
Device *Device `json:"device"`
// CertificatePem: device certificate.
CertificatePem string `json:"certificate_pem"`
}
// GetDeviceMetricsRequest: get device metrics request.
type GetDeviceMetricsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
// StartDate: start date used to compute the best scale for the returned metrics.
StartDate *time.Time `json:"start_date,omitempty"`
}
// GetDeviceMetricsResponse: get device metrics response.
type GetDeviceMetricsResponse struct {
// Metrics: metrics for a device over the requested period.
Metrics []*scw.TimeSeries `json:"metrics"`
}
// GetDeviceRequest: get device request.
type GetDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// GetHubCARequest: get hub ca request.
type GetHubCARequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
HubID string `json:"-"`
}
// GetHubCAResponse: get hub ca response.
type GetHubCAResponse struct {
CaCertPem string `json:"ca_cert_pem"`
}
// GetHubMetricsRequest: get hub metrics request.
type GetHubMetricsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
// StartDate: start date used to compute the best scale for returned metrics.
StartDate *time.Time `json:"start_date,omitempty"`
}
// GetHubMetricsResponse: get hub metrics response.
type GetHubMetricsResponse struct {
// Metrics: metrics for a Hub over the requested period.
Metrics []*scw.TimeSeries `json:"metrics"`
}
// GetHubRequest: get hub request.
type GetHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
}
// GetNetworkRequest: get network request.
type GetNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NetworkID: network ID.
NetworkID string `json:"-"`
}
// GetRouteRequest: get route request.
type GetRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// GetTwinDocumentRequest: get twin document request.
type GetTwinDocumentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
// DocumentName: name of the document.
DocumentName string `json:"-"`
}
// ListDevicesRequest: list devices request.
type ListDevicesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of devices to return within a page. Maximum value is 100.
PageSize *uint32 `json:"-"`
// OrderBy: ordering of requested devices.
// Default value: name_asc
OrderBy ListDevicesRequestOrderBy `json:"-"`
// Name: name to filter for, only devices with this name will be returned.
Name *string `json:"-"`
// HubID: hub ID to filter for, only devices attached to this Hub will be returned.
HubID *string `json:"-"`
// AllowInsecure: defines wheter to filter the allow_insecure flag.
AllowInsecure *bool `json:"-"`
// Status: device status (enabled, disabled, etc.).
// Default value: unknown
Status DeviceStatus `json:"-"`
}
// ListDevicesResponse: list devices response.
type ListDevicesResponse struct {
// TotalCount: total number of devices.
TotalCount uint32 `json:"total_count"`
// Devices: page of devices.
Devices []*Device `json:"devices"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDevicesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDevicesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDevicesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Devices = append(r.Devices, results.Devices...)
r.TotalCount += uint32(len(results.Devices))
return uint32(len(results.Devices)), nil
}
// ListHubsRequest: list hubs request.
type ListHubsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of Hubs to return within a page. Maximum value is 100.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of Hubs in the response.
// Default value: name_asc
OrderBy ListHubsRequestOrderBy `json:"-"`
// ProjectID: only list Hubs of this Project ID.
ProjectID *string `json:"-"`
// OrganizationID: only list Hubs of this Organization ID.
OrganizationID *string `json:"-"`
// Name: hub name.
Name *string `json:"-"`
}
// ListHubsResponse: list hubs response.
type ListHubsResponse struct {
// TotalCount: total number of Hubs.
TotalCount uint32 `json:"total_count"`
// Hubs: a page of hubs.
Hubs []*Hub `json:"hubs"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListHubsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListHubsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListHubsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Hubs = append(r.Hubs, results.Hubs...)
r.TotalCount += uint32(len(results.Hubs))
return uint32(len(results.Hubs)), nil
}
// ListNetworksRequest: list networks request.
type ListNetworksRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of networks to return. The maximum value is 100.
PageSize *uint32 `json:"-"`
// OrderBy: ordering of requested routes.
// Default value: name_asc
OrderBy ListNetworksRequestOrderBy `json:"-"`
// Name: network name to filter for.
Name *string `json:"-"`
// HubID: hub ID to filter for.
HubID *string `json:"-"`
// TopicPrefix: topic prefix to filter for.
TopicPrefix *string `json:"-"`
}
// ListNetworksResponse: list networks response.
type ListNetworksResponse struct {
// TotalCount: total number of Networks.
TotalCount uint32 `json:"total_count"`
// Networks: page of networks.
Networks []*Network `json:"networks"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNetworksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNetworksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Networks = append(r.Networks, results.Networks...)
r.TotalCount += uint32(len(results.Networks))
return uint32(len(results.Networks)), nil
}
// ListRoutesRequest: list routes request.
type ListRoutesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of routes to return within a page. Maximum value is 100.
PageSize *uint32 `json:"-"`
// OrderBy: ordering of requested routes.
// Default value: name_asc
OrderBy ListRoutesRequestOrderBy `json:"-"`
// HubID: hub ID to filter for.
HubID *string `json:"-"`
// Name: route name to filter for.
Name *string `json:"-"`
}
// ListRoutesResponse: list routes response.
type ListRoutesResponse struct {
// TotalCount: total number of routes.
TotalCount uint32 `json:"total_count"`
// Routes: page of routes.
Routes []*RouteSummary `json:"routes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRoutesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRoutesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRoutesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Routes = append(r.Routes, results.Routes...)
r.TotalCount += uint32(len(results.Routes))
return uint32(len(results.Routes)), nil
}
// ListTwinDocumentsRequest: list twin documents request.
type ListTwinDocumentsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
}
// ListTwinDocumentsResponse: list twin documents response.
type ListTwinDocumentsResponse struct {
// Documents: list of the twin document.
Documents []*ListTwinDocumentsResponseDocumentSummary `json:"documents"`
}
// PatchTwinDocumentRequest: patch twin document request.
type PatchTwinDocumentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
// DocumentName: name of the document.
DocumentName string `json:"-"`
// Version: if set, ensures that the current version of the document matches before persisting the update.
Version *uint32 `json:"version,omitempty"`
// Data: a json data that will be applied on the document's current data.
// Patching rules:
// * The patch goes recursively through the patch objects.
// * If the patch object property is null, it is removed from the final object.
// * If the patch object property is a value (number, strings, bool, arrays), it is replaced.
// * If the patch object property is an object, the previous rules will be applied recursively on it.
Data *scw.JSONObject `json:"data,omitempty"`
}
// PutTwinDocumentRequest: put twin document request.
type PutTwinDocumentRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TwinID: twin ID.
TwinID string `json:"-"`
// DocumentName: name of the document.
DocumentName string `json:"-"`
// Version: if set, ensures that the current version of the document matches before persisting the update.
Version *uint32 `json:"version,omitempty"`
// Data: new data that will replace the contents of the document.
Data *scw.JSONObject `json:"data,omitempty"`
}
// RenewDeviceCertificateRequest: renew device certificate request.
type RenewDeviceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
}
// RenewDeviceCertificateResponse: renew device certificate response.
type RenewDeviceCertificateResponse struct {
// Device: information related to the created device.
Device *Device `json:"device"`
// Certificate: device certificate.
Certificate *Certificate `json:"certificate"`
}
// Route: route.
type Route struct {
// ID: route ID.
ID string `json:"id"`
// Name: route name.
Name string `json:"name"`
// HubID: hub ID of the route.
HubID string `json:"hub_id"`
// Topic: topic the route subscribes to. It must be a valid MQTT topic and up to 65535 characters.
Topic string `json:"topic"`
// Type: route type.
// Default value: unknown
Type RouteRouteType `json:"type"`
// CreatedAt: date at which the route was created.
CreatedAt *time.Time `json:"created_at"`
// S3Config: when using Amazon S3 Routes, Amazon S3-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
S3Config *RouteS3Config `json:"s3_config,omitempty"`
// DbConfig: when using Database Route, DB-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
DbConfig *RouteDatabaseConfig `json:"db_config,omitempty"`
// RestConfig: when using Rest Route, Rest-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
RestConfig *RouteRestConfig `json:"rest_config,omitempty"`
// UpdatedAt: date at which the route was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// SetDeviceCertificateRequest: set device certificate request.
type SetDeviceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
// CertificatePem: pEM-encoded custom certificate.
CertificatePem string `json:"certificate_pem"`
}
// SetDeviceCertificateResponse: set device certificate response.
type SetDeviceCertificateResponse struct {
Device *Device `json:"device"`
CertificatePem string `json:"certificate_pem"`
}
// SetHubCARequest: set hub ca request.
type SetHubCARequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: hub ID.
HubID string `json:"-"`
// CaCertPem: cA's PEM-encoded certificate.
CaCertPem string `json:"ca_cert_pem"`
// ChallengeCertPem: challenge is a PEM-encoded certificate that acts as proof of possession of the CA. It must be signed by the CA, and have a Common Name equal to the Hub ID.
ChallengeCertPem string `json:"challenge_cert_pem"`
}
// TwinDocument: twin document.
type TwinDocument struct {
// TwinID: parent twin ID of the document.
TwinID string `json:"twin_id"`
// DocumentName: name of the document.
DocumentName string `json:"document_name"`
// Version: new version of the document.
Version uint32 `json:"version"`
// Data: new data related to the document.
Data *scw.JSONObject `json:"data"`
}
// UpdateDeviceRequest: update device request.
type UpdateDeviceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DeviceID: device ID.
DeviceID string `json:"-"`
// Description: description for the device.
Description *string `json:"description,omitempty"`
// AllowInsecure: defines whether to allow plain and server-authenticated SSL connections in addition to mutually-authenticated ones.
AllowInsecure *bool `json:"allow_insecure,omitempty"`
// AllowMultipleConnections: defines whether to allow multiple physical devices to connect with this device's credentials.
AllowMultipleConnections *bool `json:"allow_multiple_connections,omitempty"`
// MessageFilters: filter-sets to restrict the topics the device can publish/subscribe to.
MessageFilters *DeviceMessageFilters `json:"message_filters,omitempty"`
// HubID: change Hub for this device, additional fees may apply, see IoT Hub pricing.
HubID *string `json:"hub_id,omitempty"`
}
// UpdateHubRequest: update hub request.
type UpdateHubRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HubID: ID of the Hub you want to update.
HubID string `json:"-"`
// Name: hub name (up to 255 characters).
Name *string `json:"name,omitempty"`
// ProductPlan: hub product plan.
// Default value: plan_unknown
ProductPlan HubProductPlan `json:"product_plan"`
// DisableEvents: disable Hub events.
DisableEvents *bool `json:"disable_events,omitempty"`
// EventsTopicPrefix: topic prefix of Hub events.
EventsTopicPrefix *string `json:"events_topic_prefix,omitempty"`
// EnableDeviceAutoProvisioning: enable device auto provisioning.
EnableDeviceAutoProvisioning *bool `json:"enable_device_auto_provisioning,omitempty"`
// TwinsGraphiteConfig: bETA - not implemented yet.
// Precisely one of TwinsGraphiteConfig must be set.
TwinsGraphiteConfig *HubTwinsGraphiteConfig `json:"twins_graphite_config,omitempty"`
}
// UpdateRouteRequest: update route request.
type UpdateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route id.
RouteID string `json:"-"`
// Name: route name.
Name *string `json:"name,omitempty"`
// Topic: topic the route subscribes to. It must be a valid MQTT topic and up to 65535 characters.
Topic *string `json:"topic,omitempty"`
// S3Config: when updating Amazon S3 Route, Amazon S3-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
S3Config *UpdateRouteRequestS3Config `json:"s3_config,omitempty"`
// DbConfig: when updating Database Route, DB-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
DbConfig *UpdateRouteRequestDatabaseConfig `json:"db_config,omitempty"`
// RestConfig: when updating Rest Route, Rest-specific configuration fields.
// Precisely one of S3Config, DbConfig, RestConfig must be set.
RestConfig *UpdateRouteRequestRestConfig `json:"rest_config,omitempty"`
}
// This API allows you to manage your IoT hubs and devices.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar}
}
// ListHubs: List all Hubs in the specified zone. By default, returned Hubs are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListHubs(req *ListHubsRequest, opts ...scw.RequestOption) (*ListHubsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs",
Query: query,
}
var resp ListHubsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateHub: Create a new Hub in the targeted region, specifying its configuration including name and product plan.
func (s *API) CreateHub(req *CreateHubRequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("hub")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetHub: Retrieve information about an existing IoT Hub, specified by its Hub ID. Its full details, including name, status and endpoint, are returned in the response object.
func (s *API) GetHub(req *GetHubRequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "",
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHub: Update the parameters of an existing IoT Hub, specified by its Hub ID.
func (s *API) UpdateHub(req *UpdateHubRequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableHub: Enable an existing IoT Hub, specified by its Hub ID.
func (s *API) EnableHub(req *EnableHubRequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableHub: Disable an existing IoT Hub, specified by its Hub ID.
func (s *API) DisableHub(req *DisableHubRequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteHub: Delete an existing IoT Hub, specified by its Hub ID. Deleting a Hub is permanent, and cannot be undone.
func (s *API) DeleteHub(req *DeleteHubRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "delete_devices", req.DeleteDevices)
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Deprecated: GetHubMetrics: Get the metrics of an existing IoT Hub, specified by its Hub ID.
func (s *API) GetHubMetrics(req *GetHubMetricsRequest, opts ...scw.RequestOption) (*GetHubMetricsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "start_date", req.StartDate)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "/metrics",
Query: query,
}
var resp GetHubMetricsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetHubCA: Set a particular PEM-encoded certificate, specified by the Hub ID.
func (s *API) SetHubCA(req *SetHubCARequest, opts ...scw.RequestOption) (*Hub, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "/ca",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hub
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetHubCA: Get information for a particular PEM-encoded certificate, specified by the Hub ID.
func (s *API) GetHubCA(req *GetHubCARequest, opts ...scw.RequestOption) (*GetHubCAResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HubID) == "" {
return nil, errors.New("field HubID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/hubs/" + fmt.Sprint(req.HubID) + "/ca",
}
var resp GetHubCAResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDevices: List all devices in the specified region. By default, returned devices are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListDevices(req *ListDevicesRequest, opts ...scw.RequestOption) (*ListDevicesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "hub_id", req.HubID)
parameter.AddToQuery(query, "allow_insecure", req.AllowInsecure)
parameter.AddToQuery(query, "status", req.Status)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices",
Query: query,
}
var resp ListDevicesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDevice: Attach a device to a given Hub.
func (s *API) CreateDevice(req *CreateDeviceRequest, opts ...scw.RequestOption) (*CreateDeviceResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("device")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateDeviceResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDevice: Retrieve information about an existing device, specified by its device ID. Its full details, including name, status and ID, are returned in the response object.
func (s *API) GetDevice(req *GetDeviceRequest, opts ...scw.RequestOption) (*Device, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "",
}
var resp Device
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDevice: Update the parameters of an existing device, specified by its device ID.
func (s *API) UpdateDevice(req *UpdateDeviceRequest, opts ...scw.RequestOption) (*Device, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Device
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableDevice: Enable a specific device, specified by its device ID.
func (s *API) EnableDevice(req *EnableDeviceRequest, opts ...scw.RequestOption) (*Device, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Device
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableDevice: Disable an existing device, specified by its device ID.
func (s *API) DisableDevice(req *DisableDeviceRequest, opts ...scw.RequestOption) (*Device, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Device
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RenewDeviceCertificate: Renew the certificate of an existing device, specified by its device ID.
func (s *API) RenewDeviceCertificate(req *RenewDeviceCertificateRequest, opts ...scw.RequestOption) (*RenewDeviceCertificateResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/renew-certificate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RenewDeviceCertificateResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetDeviceCertificate: Switch the existing certificate of a given device with an EM-encoded custom certificate.
func (s *API) SetDeviceCertificate(req *SetDeviceCertificateRequest, opts ...scw.RequestOption) (*SetDeviceCertificateResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/certificate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetDeviceCertificateResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDeviceCertificate: Get information for a particular PEM-encoded certificate, specified by the device ID. The response returns full details of the device, including its type of certificate.
func (s *API) GetDeviceCertificate(req *GetDeviceCertificateRequest, opts ...scw.RequestOption) (*GetDeviceCertificateResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/certificate",
}
var resp GetDeviceCertificateResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDevice: Remove a specific device from the specific Hub it is attached to.
func (s *API) DeleteDevice(req *DeleteDeviceRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Deprecated: GetDeviceMetrics: Get the metrics of an existing device, specified by its device ID.
func (s *API) GetDeviceMetrics(req *GetDeviceMetricsRequest, opts ...scw.RequestOption) (*GetDeviceMetricsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "start_date", req.StartDate)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DeviceID) == "" {
return nil, errors.New("field DeviceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/devices/" + fmt.Sprint(req.DeviceID) + "/metrics",
Query: query,
}
var resp GetDeviceMetricsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListRoutes: List all routes in the specified region. By default, returned routes are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListRoutes(req *ListRoutesRequest, opts ...scw.RequestOption) (*ListRoutesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "hub_id", req.HubID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/routes",
Query: query,
}
var resp ListRoutesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRoute: Multiple kinds of routes can be created, such as:
// - Database Route
// Create a route that will record subscribed MQTT messages into your database.
// You need to manage the database by yourself.
// - REST Route.
// Create a route that will call a REST API on received subscribed MQTT messages.
// - Amazon S3 Routes.
// Create a route that will put subscribed MQTT messages into an Object Storage bucket.
// You need to create the bucket yourself and grant write access.
// Granting can be done with s3cmd (`s3cmd setacl s3:// --acl-grant=write:555c69c3-87d0-4bf8-80f1-99a2f757d031:555c69c3-87d0-4bf8-80f1-99a2f757d031`).
func (s *API) CreateRoute(req *CreateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("route")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/routes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRoute: Update the parameters of an existing route, specified by its route ID.
func (s *API) UpdateRoute(req *UpdateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRoute: Get information for a particular route, specified by the route ID. The response returns full details of the route, including its type, the topic it subscribes to and its configuration.
func (s *API) GetRoute(req *GetRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRoute: Delete an existing route, specified by its route ID. Deleting a route is permanent, and cannot be undone.
func (s *API) DeleteRoute(req *DeleteRouteRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListNetworks: List the networks.
func (s *API) ListNetworks(req *ListNetworksRequest, opts ...scw.RequestOption) (*ListNetworksResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "hub_id", req.HubID)
parameter.AddToQuery(query, "topic_prefix", req.TopicPrefix)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/networks",
Query: query,
}
var resp ListNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateNetwork: Create a new network for an existing hub. Beside the default network, you can add networks for different data providers. Possible network types are Sigfox and REST.
func (s *API) CreateNetwork(req *CreateNetworkRequest, opts ...scw.RequestOption) (*CreateNetworkResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("network")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateNetworkResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNetwork: Retrieve an existing network, specified by its network ID. The response returns full details of the network, including its type, the topic prefix and its endpoint.
func (s *API) GetNetwork(req *GetNetworkRequest, opts ...scw.RequestOption) (*Network, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NetworkID) == "" {
return nil, errors.New("field NetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/networks/" + fmt.Sprint(req.NetworkID) + "",
}
var resp Network
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNetwork: Delete an existing network, specified by its network ID. Deleting a network is permanent, and cannot be undone.
func (s *API) DeleteNetwork(req *DeleteNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NetworkID) == "" {
return errors.New("field NetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/networks/" + fmt.Sprint(req.NetworkID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetTwinDocument: BETA - Get a Cloud Twin Document.
func (s *API) GetTwinDocument(req *GetTwinDocumentRequest, opts ...scw.RequestOption) (*TwinDocument, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return nil, errors.New("field TwinID cannot be empty in request")
}
if fmt.Sprint(req.DocumentName) == "" {
return nil, errors.New("field DocumentName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "/documents/" + fmt.Sprint(req.DocumentName) + "",
}
var resp TwinDocument
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PutTwinDocument: BETA - Update a Cloud Twin Document.
func (s *API) PutTwinDocument(req *PutTwinDocumentRequest, opts ...scw.RequestOption) (*TwinDocument, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return nil, errors.New("field TwinID cannot be empty in request")
}
if fmt.Sprint(req.DocumentName) == "" {
return nil, errors.New("field DocumentName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "/documents/" + fmt.Sprint(req.DocumentName) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp TwinDocument
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PatchTwinDocument: BETA - Patch a Cloud Twin Document.
func (s *API) PatchTwinDocument(req *PatchTwinDocumentRequest, opts ...scw.RequestOption) (*TwinDocument, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return nil, errors.New("field TwinID cannot be empty in request")
}
if fmt.Sprint(req.DocumentName) == "" {
return nil, errors.New("field DocumentName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "/documents/" + fmt.Sprint(req.DocumentName) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp TwinDocument
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTwinDocument: BETA - Delete a Cloud Twin Document.
func (s *API) DeleteTwinDocument(req *DeleteTwinDocumentRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return errors.New("field TwinID cannot be empty in request")
}
if fmt.Sprint(req.DocumentName) == "" {
return errors.New("field DocumentName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "/documents/" + fmt.Sprint(req.DocumentName) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListTwinDocuments: BETA - List the documents of a Cloud Twin.
func (s *API) ListTwinDocuments(req *ListTwinDocumentsRequest, opts ...scw.RequestOption) (*ListTwinDocumentsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return nil, errors.New("field TwinID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "",
}
var resp ListTwinDocumentsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTwinDocuments: BETA - Delete all the documents of a Cloud Twin.
func (s *API) DeleteTwinDocuments(req *DeleteTwinDocumentsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TwinID) == "" {
return errors.New("field TwinID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/iot/v1/regions/" + fmt.Sprint(req.Region) + "/twins/" + fmt.Sprint(req.TwinID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0025773 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/iot/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000002014 14747113137 0030154 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/iot/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepHub(scwClient *scw.Client, region scw.Region) error {
iotAPI := iot.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the iot hub in (%s)", region)
listHubs, err := iotAPI.ListHubs(&iot.ListHubsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing hubs in (%s) in sweeper: %s", region, err)
}
deleteDevices := true
for _, hub := range listHubs.Hubs {
err := iotAPI.DeleteHub(&iot.DeleteHubRequest{
HubID: hub.ID,
Region: hub.Region,
DeleteDevices: &deleteDevices,
})
if err != nil {
return fmt.Errorf("error deleting hub in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&iot.API{}).Regions() {
err := SweepHub(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/ 0000775 0000000 0000000 00000000000 14747113137 0023743 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024271 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1/ipam_sdk.go 0000664 0000000 0000000 00000056117 14747113137 0026421 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package ipam provides methods and message types of the ipam v1 API.
package ipam
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListIPsRequestOrderBy string
const (
ListIPsRequestOrderByCreatedAtDesc = ListIPsRequestOrderBy("created_at_desc")
ListIPsRequestOrderByCreatedAtAsc = ListIPsRequestOrderBy("created_at_asc")
ListIPsRequestOrderByUpdatedAtDesc = ListIPsRequestOrderBy("updated_at_desc")
ListIPsRequestOrderByUpdatedAtAsc = ListIPsRequestOrderBy("updated_at_asc")
ListIPsRequestOrderByAttachedAtDesc = ListIPsRequestOrderBy("attached_at_desc")
ListIPsRequestOrderByAttachedAtAsc = ListIPsRequestOrderBy("attached_at_asc")
)
func (enum ListIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListIPsRequestOrderBy) Values() []ListIPsRequestOrderBy {
return []ListIPsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"updated_at_desc",
"updated_at_asc",
"attached_at_desc",
"attached_at_asc",
}
}
func (enum ListIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListIPsRequestOrderBy(ListIPsRequestOrderBy(tmp).String())
return nil
}
type ResourceType string
const (
ResourceTypeUnknownType = ResourceType("unknown_type")
ResourceTypeCustom = ResourceType("custom")
ResourceTypeInstanceServer = ResourceType("instance_server")
ResourceTypeInstanceIP = ResourceType("instance_ip")
ResourceTypeInstancePrivateNic = ResourceType("instance_private_nic")
ResourceTypeLBServer = ResourceType("lb_server")
ResourceTypeFipIP = ResourceType("fip_ip")
ResourceTypeVpcGateway = ResourceType("vpc_gateway")
ResourceTypeVpcGatewayNetwork = ResourceType("vpc_gateway_network")
ResourceTypeK8sNode = ResourceType("k8s_node")
ResourceTypeK8sCluster = ResourceType("k8s_cluster")
ResourceTypeRdbInstance = ResourceType("rdb_instance")
ResourceTypeRedisCluster = ResourceType("redis_cluster")
ResourceTypeBaremetalServer = ResourceType("baremetal_server")
ResourceTypeBaremetalPrivateNic = ResourceType("baremetal_private_nic")
ResourceTypeLlmDeployment = ResourceType("llm_deployment")
ResourceTypeMgdbInstance = ResourceType("mgdb_instance")
ResourceTypeAppleSiliconServer = ResourceType("apple_silicon_server")
ResourceTypeAppleSiliconPrivateNic = ResourceType("apple_silicon_private_nic")
)
func (enum ResourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ResourceType) Values() []ResourceType {
return []ResourceType{
"unknown_type",
"custom",
"instance_server",
"instance_ip",
"instance_private_nic",
"lb_server",
"fip_ip",
"vpc_gateway",
"vpc_gateway_network",
"k8s_node",
"k8s_cluster",
"rdb_instance",
"redis_cluster",
"baremetal_server",
"baremetal_private_nic",
"llm_deployment",
"mgdb_instance",
"apple_silicon_server",
"apple_silicon_private_nic",
}
}
func (enum ResourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ResourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ResourceType(ResourceType(tmp).String())
return nil
}
// Resource: resource.
type Resource struct {
// Type: type of resource the IP is attached to.
// Default value: unknown_type
Type ResourceType `json:"type"`
// ID: ID of the resource the IP is attached to.
ID string `json:"id"`
// MacAddress: mAC of the resource the IP is attached to.
MacAddress *string `json:"mac_address"`
// Name: when the IP is in a Private Network, then a DNS record is available to resolve the resource name to this IP.
Name *string `json:"name"`
}
// Reverse: reverse.
type Reverse struct {
// Hostname: reverse domain name.
Hostname string `json:"hostname"`
// Address: IP corresponding to the hostname.
Address *net.IP `json:"address"`
}
// Source: source.
type Source struct {
// Zonal: this source is global.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
Zonal *string `json:"zonal,omitempty"`
// PrivateNetworkID: this source is specific.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
PrivateNetworkID *string `json:"private_network_id,omitempty"`
// SubnetID: this source is specific.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
SubnetID *string `json:"subnet_id,omitempty"`
}
// CustomResource: custom resource.
type CustomResource struct {
// MacAddress: mAC address of the custom resource.
MacAddress string `json:"mac_address"`
// Name: when the resource is in a Private Network, a DNS record is available to resolve the resource name.
Name *string `json:"name"`
}
// IP: ip.
type IP struct {
// ID: IP ID.
ID string `json:"id"`
// Address: iPv4 or IPv6 address in CIDR notation.
Address scw.IPNet `json:"address"`
// ProjectID: scaleway Project the IP belongs to.
ProjectID string `json:"project_id"`
// IsIPv6: defines whether the IP is an IPv6 (false = IPv4).
IsIPv6 bool `json:"is_ipv6"`
// CreatedAt: date the IP was reserved.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the IP was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// Source: source pool where the IP was reserved in.
Source *Source `json:"source"`
// Resource: resource which the IP is attached to.
Resource *Resource `json:"resource"`
// Tags: tags for the IP.
Tags []string `json:"tags"`
// Reverses: array of reverses associated with the IP.
Reverses []*Reverse `json:"reverses"`
// Region: region of the IP.
Region scw.Region `json:"region"`
// Zone: zone of the IP, if zonal.
Zone *scw.Zone `json:"zone"`
}
// AttachIPRequest: attach ip request.
type AttachIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
// Resource: custom resource to be attached to the IP.
Resource *CustomResource `json:"resource"`
}
// BookIPRequest: book ip request.
type BookIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: when creating an IP in a Private Network, the Project must match the Private Network's Project.
ProjectID string `json:"project_id"`
// Source: source in which to reserve the IP. Not all sources are available for reservation.
Source *Source `json:"source"`
// IsIPv6: request an IPv6 instead of an IPv4.
IsIPv6 bool `json:"is_ipv6"`
// Address: the requested address should not include the subnet mask (/suffix). Note that only the Private Network source allows you to pick a specific IP. If the requested IP is already reserved, then the call will fail.
Address *net.IP `json:"address,omitempty"`
// Tags: tags for the IP.
Tags []string `json:"tags"`
// Resource: custom resource to attach to the IP being reserved. An example of a custom resource is a virtual machine hosted on an Elastic Metal server. Do not use this for attaching IP addresses to standard Scaleway resources, as it will fail - instead, see the relevant product API for an equivalent method.
Resource *CustomResource `json:"resource,omitempty"`
}
// DetachIPRequest: detach ip request.
type DetachIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
// Resource: custom resource currently attached to the IP.
Resource *CustomResource `json:"resource"`
}
// GetIPRequest: get ip request.
type GetIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of the returned IPs.
// Default value: created_at_desc
OrderBy ListIPsRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of IPs to return per page.
PageSize *uint32 `json:"-"`
// ProjectID: project ID to filter for. Only IPs belonging to this Project will be returned.
ProjectID *string `json:"-"`
// Zonal: zone to filter for. Only IPs that are zonal, and in this zone, will be returned.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
Zonal *string `json:"zonal,omitempty"`
// PrivateNetworkID: only IPs that are private, and in this Private Network, will be returned.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
PrivateNetworkID *string `json:"private_network_id,omitempty"`
// SubnetID: only IPs inside this exact subnet will be returned.
// Precisely one of Zonal, PrivateNetworkID, SubnetID must be set.
SubnetID *string `json:"subnet_id,omitempty"`
// VpcID: only IPs owned by resources in this VPC will be returned.
VpcID *string `json:"-"`
// Attached: defines whether to filter only for IPs which are attached to a resource.
Attached *bool `json:"-"`
// ResourceName: attached resource name to filter for, only IPs attached to a resource with this string within their name will be returned.
ResourceName *string `json:"-"`
// ResourceID: resource ID to filter for. Only IPs attached to this resource will be returned.
ResourceID *string `json:"-"`
// ResourceIDs: resource IDs to filter for. Only IPs attached to at least one of these resources will be returned.
ResourceIDs []string `json:"-"`
// ResourceType: resource type to filter for. Only IPs attached to this type of resource will be returned.
// Default value: unknown_type
ResourceType ResourceType `json:"-"`
// ResourceTypes: resource types to filter for. Only IPs attached to these types of resources will be returned.
ResourceTypes []ResourceType `json:"-"`
// MacAddress: mAC address to filter for. Only IPs attached to a resource with this MAC address will be returned.
MacAddress *string `json:"-"`
// Tags: tags to filter for, only IPs with one or more matching tags will be returned.
Tags []string `json:"-"`
// OrganizationID: organization ID to filter for. Only IPs belonging to this Organization will be returned.
OrganizationID *string `json:"-"`
// IsIPv6: defines whether to filter only for IPv4s or IPv6s.
IsIPv6 *bool `json:"-"`
// IPIDs: IP IDs to filter for. Only IPs with these UUIDs will be returned.
IPIDs []string `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
TotalCount uint64 `json:"total_count"`
IPs []*IP `json:"ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint64(len(results.IPs))
return uint64(len(results.IPs)), nil
}
// MoveIPRequest: move ip request.
type MoveIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
// FromResource: custom resource currently attached to the IP.
FromResource *CustomResource `json:"from_resource"`
// ToResource: custom resource to be attached to the IP.
ToResource *CustomResource `json:"to_resource,omitempty"`
}
// ReleaseIPRequest: release ip request.
type ReleaseIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
}
// ReleaseIPSetRequest: release ip set request.
type ReleaseIPSetRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
IPIDs []string `json:"ip_ids"`
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP ID.
IPID string `json:"-"`
// Tags: tags for the IP.
Tags *[]string `json:"tags,omitempty"`
// Reverses: array of reverse domain names associated with an IP in the subnet of the current IP.
Reverses []*Reverse `json:"reverses"`
}
// This API allows you to manage your Scaleway IP addresses with our IP Address Management tool.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// BookIP: Reserve a new IP from the specified source. Currently IPs can only be reserved from a Private Network.
func (s *API) BookIP(req *BookIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ReleaseIP: Release an IP not currently attached to a resource, and returns it to the available IP pool.
func (s *API) ReleaseIP(req *ReleaseIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ReleaseIPSet:
func (s *API) ReleaseIPSet(req *ReleaseIPSetRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ip-sets/release",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetIP: Retrieve details of an existing IP, specified by its IP ID.
func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateIP: Update parameters including tags of the specified IP.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List existing IPs in the specified region using various filters. For example, you can filter for IPs within a specified Private Network, or for public IPs within a specified Project. By default, the IPs returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "vpc_id", req.VpcID)
parameter.AddToQuery(query, "attached", req.Attached)
parameter.AddToQuery(query, "resource_name", req.ResourceName)
parameter.AddToQuery(query, "resource_id", req.ResourceID)
parameter.AddToQuery(query, "resource_ids", req.ResourceIDs)
parameter.AddToQuery(query, "resource_type", req.ResourceType)
parameter.AddToQuery(query, "resource_types", req.ResourceTypes)
parameter.AddToQuery(query, "mac_address", req.MacAddress)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "is_ipv6", req.IsIPv6)
parameter.AddToQuery(query, "ip_ids", req.IPIDs)
parameter.AddToQuery(query, "zonal", req.Zonal)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "subnet_id", req.SubnetID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachIP: Attach an existing reserved IP from a Private Network subnet to a custom, named resource via its MAC address. An example of a custom resource is a virtual machine hosted on an Elastic Metal server. Do not use this method for attaching IP addresses to standard Scaleway resources as it will fail - see the relevant product API for an equivalent method.
func (s *API) AttachIP(req *AttachIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "/attach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachIP: Detach a private IP from a custom resource. An example of a custom resource is a virtual machine hosted on an Elastic Metal server. Do not use this method for detaching IP addresses from standard Scaleway resources (e.g. Instances, Load Balancers) as it will fail - see the relevant product API for an equivalent method.
func (s *API) DetachIP(req *DetachIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "/detach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// MoveIP: Move an existing reserved private IP from one custom resource (e.g. a virtual machine hosted on an Elastic Metal server) to another custom resource. This will detach it from the first resource, and attach it to the second. Do not use this method for moving IP addresses between standard Scaleway resources (e.g. Instances, Load Balancers) as it will fail - see the relevant product API for an equivalent method.
func (s *API) MoveIP(req *MoveIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/ipam/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "/move",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026126 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000001671 14747113137 0030317 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/ipam/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepIP(scwClient *scw.Client, region scw.Region) error {
ipamAPI := ipam.NewAPI(scwClient)
logger.Warningf("sweeper: deleting the IPs in (%s)", region)
listIPs, err := ipamAPI.ListIPs(&ipam.ListIPsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing ips in (%s) in sweeper: %s", region, err)
}
for _, v := range listIPs.IPs {
err := ipamAPI.ReleaseIP(&ipam.ReleaseIPRequest{
IPID: v.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error releasing IP in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&ipam.API{}).Regions() {
err := SweepIP(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025360 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/ipam/v1alpha1/ipam_sdk.go 0000664 0000000 0000000 00000023443 14747113137 0027504 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package ipam provides methods and message types of the ipam v1alpha1 API.
package ipam
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListIPsRequestOrderBy string
const (
ListIPsRequestOrderByCreatedAtDesc = ListIPsRequestOrderBy("created_at_desc")
ListIPsRequestOrderByCreatedAtAsc = ListIPsRequestOrderBy("created_at_asc")
ListIPsRequestOrderByUpdatedAtDesc = ListIPsRequestOrderBy("updated_at_desc")
ListIPsRequestOrderByUpdatedAtAsc = ListIPsRequestOrderBy("updated_at_asc")
ListIPsRequestOrderByAttachedAtDesc = ListIPsRequestOrderBy("attached_at_desc")
ListIPsRequestOrderByAttachedAtAsc = ListIPsRequestOrderBy("attached_at_asc")
)
func (enum ListIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListIPsRequestOrderBy) Values() []ListIPsRequestOrderBy {
return []ListIPsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"updated_at_desc",
"updated_at_asc",
"attached_at_desc",
"attached_at_asc",
}
}
func (enum ListIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListIPsRequestOrderBy(ListIPsRequestOrderBy(tmp).String())
return nil
}
type ResourceType string
const (
ResourceTypeUnknownType = ResourceType("unknown_type")
ResourceTypeCustom = ResourceType("custom")
ResourceTypeInstanceServer = ResourceType("instance_server")
ResourceTypeInstanceIP = ResourceType("instance_ip")
ResourceTypeInstancePrivateNic = ResourceType("instance_private_nic")
ResourceTypeLBServer = ResourceType("lb_server")
ResourceTypeFipIP = ResourceType("fip_ip")
ResourceTypeVpcGateway = ResourceType("vpc_gateway")
ResourceTypeVpcGatewayNetwork = ResourceType("vpc_gateway_network")
ResourceTypeK8sNode = ResourceType("k8s_node")
ResourceTypeK8sCluster = ResourceType("k8s_cluster")
ResourceTypeRdbInstance = ResourceType("rdb_instance")
ResourceTypeRedisCluster = ResourceType("redis_cluster")
ResourceTypeBaremetalServer = ResourceType("baremetal_server")
ResourceTypeBaremetalPrivateNic = ResourceType("baremetal_private_nic")
ResourceTypeLlmDeployment = ResourceType("llm_deployment")
ResourceTypeMgdbInstance = ResourceType("mgdb_instance")
ResourceTypeAppleSiliconServer = ResourceType("apple_silicon_server")
ResourceTypeAppleSiliconPrivateNic = ResourceType("apple_silicon_private_nic")
)
func (enum ResourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ResourceType) Values() []ResourceType {
return []ResourceType{
"unknown_type",
"custom",
"instance_server",
"instance_ip",
"instance_private_nic",
"lb_server",
"fip_ip",
"vpc_gateway",
"vpc_gateway_network",
"k8s_node",
"k8s_cluster",
"rdb_instance",
"redis_cluster",
"baremetal_server",
"baremetal_private_nic",
"llm_deployment",
"mgdb_instance",
"apple_silicon_server",
"apple_silicon_private_nic",
}
}
func (enum ResourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ResourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ResourceType(ResourceType(tmp).String())
return nil
}
// Resource: resource.
type Resource struct {
// Type: default value: unknown_type
Type ResourceType `json:"type"`
ID string `json:"id"`
MacAddress *string `json:"mac_address"`
Name *string `json:"name"`
}
// Reverse: reverse.
type Reverse struct {
Hostname string `json:"hostname"`
Address *net.IP `json:"address"`
}
// IP: ip.
type IP struct {
ID string `json:"id"`
Address scw.IPNet `json:"address"`
ProjectID string `json:"project_id"`
IsIPv6 bool `json:"is_ipv6"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
// Precisely one of Regional, Zonal, ZonalNat, SubnetID must be set.
Regional *bool `json:"regional,omitempty"`
// Precisely one of Regional, Zonal, ZonalNat, SubnetID must be set.
Zonal *string `json:"zonal,omitempty"`
// Precisely one of Regional, Zonal, ZonalNat, SubnetID must be set.
ZonalNat *string `json:"zonal_nat,omitempty"`
// Precisely one of Regional, Zonal, ZonalNat, SubnetID must be set.
SubnetID *string `json:"subnet_id,omitempty"`
Resource *Resource `json:"resource"`
Tags []string `json:"tags"`
Reverses []*Reverse `json:"reverses"`
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"region"`
// Zone: zone to target. If none is passed will use default zone from the config.
Zone *scw.Zone `json:"zone"`
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_desc
OrderBy ListIPsRequestOrderBy `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
// Precisely one of Zonal, ZonalNat, Regional, PrivateNetworkID, SubnetID must be set.
Zonal *string `json:"zonal,omitempty"`
// Precisely one of Zonal, ZonalNat, Regional, PrivateNetworkID, SubnetID must be set.
ZonalNat *string `json:"zonal_nat,omitempty"`
// Precisely one of Zonal, ZonalNat, Regional, PrivateNetworkID, SubnetID must be set.
Regional *bool `json:"regional,omitempty"`
// Precisely one of Zonal, ZonalNat, Regional, PrivateNetworkID, SubnetID must be set.
PrivateNetworkID *string `json:"private_network_id,omitempty"`
// Precisely one of Zonal, ZonalNat, Regional, PrivateNetworkID, SubnetID must be set.
SubnetID *string `json:"subnet_id,omitempty"`
Attached *bool `json:"-"`
ResourceID *string `json:"-"`
// ResourceType: default value: unknown_type
ResourceType ResourceType `json:"-"`
MacAddress *string `json:"-"`
Tags *[]string `json:"-"`
IsIPv6 *bool `json:"-"`
ResourceName *string `json:"-"`
ResourceIDs []string `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
TotalCount uint64 `json:"total_count"`
IPs []*IP `json:"ips"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint64(len(results.IPs))
return uint64(len(results.IPs)), nil
}
// This API allows you to manage your Scaleway IP addresses with our IP Address Management tool.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListIPs: Find IP addresses.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "attached", req.Attached)
parameter.AddToQuery(query, "resource_id", req.ResourceID)
parameter.AddToQuery(query, "resource_type", req.ResourceType)
parameter.AddToQuery(query, "mac_address", req.MacAddress)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "is_ipv6", req.IsIPv6)
parameter.AddToQuery(query, "resource_name", req.ResourceName)
parameter.AddToQuery(query, "resource_ids", req.ResourceIDs)
parameter.AddToQuery(query, "zonal", req.Zonal)
parameter.AddToQuery(query, "zonal_nat", req.ZonalNat)
parameter.AddToQuery(query, "regional", req.Regional)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "subnet_id", req.SubnetID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/ipam/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/ 0000775 0000000 0000000 00000000000 14747113137 0023752 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025367 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/v1alpha1/custom_job_run.go 0000664 0000000 0000000 00000003025 14747113137 0030746 0 ustar 00root root 0000000 0000000 package jobs
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 15 * time.Minute
)
type WaitForJobRunRequest struct {
JobRunID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForJobRun waits for the job run to be in a "terminal state" before returning.
// This function can be used to wait for a job run to fail for example.
func (s *API) WaitForJobRun(req *WaitForJobRunRequest, opts ...scw.RequestOption) (*JobRun, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[JobRunState]struct{}{
JobRunStateSucceeded: {},
JobRunStateFailed: {},
JobRunStateCanceled: {},
}
jobRun, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetJobRun(&GetJobRunRequest{
JobRunID: req.JobRunID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.State]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for job run failed")
}
return jobRun.(*JobRun), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/v1alpha1/jobs_sdk.go 0000664 0000000 0000000 00000103637 14747113137 0027526 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package jobs provides methods and message types of the jobs v1alpha1 API.
package jobs
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type JobRunState string
const (
JobRunStateUnknownState = JobRunState("unknown_state")
JobRunStateQueued = JobRunState("queued")
JobRunStateScheduled = JobRunState("scheduled")
JobRunStateRunning = JobRunState("running")
JobRunStateSucceeded = JobRunState("succeeded")
JobRunStateFailed = JobRunState("failed")
JobRunStateCanceled = JobRunState("canceled")
JobRunStateInternalError = JobRunState("internal_error")
)
func (enum JobRunState) String() string {
if enum == "" {
// return default value if empty
return "unknown_state"
}
return string(enum)
}
func (enum JobRunState) Values() []JobRunState {
return []JobRunState{
"unknown_state",
"queued",
"scheduled",
"running",
"succeeded",
"failed",
"canceled",
"internal_error",
}
}
func (enum JobRunState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *JobRunState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = JobRunState(JobRunState(tmp).String())
return nil
}
type ListJobDefinitionsRequestOrderBy string
const (
ListJobDefinitionsRequestOrderByCreatedAtAsc = ListJobDefinitionsRequestOrderBy("created_at_asc")
ListJobDefinitionsRequestOrderByCreatedAtDesc = ListJobDefinitionsRequestOrderBy("created_at_desc")
)
func (enum ListJobDefinitionsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListJobDefinitionsRequestOrderBy) Values() []ListJobDefinitionsRequestOrderBy {
return []ListJobDefinitionsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListJobDefinitionsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListJobDefinitionsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListJobDefinitionsRequestOrderBy(ListJobDefinitionsRequestOrderBy(tmp).String())
return nil
}
type ListJobRunsRequestOrderBy string
const (
ListJobRunsRequestOrderByCreatedAtAsc = ListJobRunsRequestOrderBy("created_at_asc")
ListJobRunsRequestOrderByCreatedAtDesc = ListJobRunsRequestOrderBy("created_at_desc")
)
func (enum ListJobRunsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListJobRunsRequestOrderBy) Values() []ListJobRunsRequestOrderBy {
return []ListJobRunsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListJobRunsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListJobRunsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListJobRunsRequestOrderBy(ListJobRunsRequestOrderBy(tmp).String())
return nil
}
// SecretEnvVar: secret env var.
type SecretEnvVar struct {
Name string `json:"name"`
}
// SecretFile: secret file.
type SecretFile struct {
Path string `json:"path"`
}
// CronSchedule: cron schedule.
type CronSchedule struct {
// Schedule: uNIX cron schedule to run job (e.g., '* * * * *').
Schedule string `json:"schedule"`
// Timezone: timezone for the cron schedule, in tz database format (e.g., 'Europe/Paris').
Timezone string `json:"timezone"`
}
// CreateJobDefinitionRequestCronScheduleConfig: create job definition request cron schedule config.
type CreateJobDefinitionRequestCronScheduleConfig struct {
Schedule string `json:"schedule"`
Timezone string `json:"timezone"`
}
// CreateJobDefinitionSecretsRequestSecretConfig: create job definition secrets request secret config.
type CreateJobDefinitionSecretsRequestSecretConfig struct {
SecretManagerID string `json:"secret_manager_id"`
SecretManagerVersion string `json:"secret_manager_version"`
// Precisely one of Path, EnvVarName must be set.
Path *string `json:"path,omitempty"`
// Precisely one of Path, EnvVarName must be set.
EnvVarName *string `json:"env_var_name,omitempty"`
}
// Secret: secret.
type Secret struct {
// SecretID: UUID of the secret reference within the job.
SecretID string `json:"secret_id"`
// SecretManagerID: UUID of the secret in Secret Manager.
SecretManagerID string `json:"secret_manager_id"`
// SecretManagerVersion: version of the secret in Secret Manager.
SecretManagerVersion string `json:"secret_manager_version"`
// File: file secret mounted inside the job.
// Precisely one of File, EnvVar must be set.
File *SecretFile `json:"file,omitempty"`
// EnvVar: environment variable used to expose the secret.
// Precisely one of File, EnvVar must be set.
EnvVar *SecretEnvVar `json:"env_var,omitempty"`
}
// JobDefinition: job definition.
type JobDefinition struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
CPULimit uint32 `json:"cpu_limit"`
MemoryLimit uint32 `json:"memory_limit"`
ImageURI string `json:"image_uri"`
Command string `json:"command"`
ProjectID string `json:"project_id"`
EnvironmentVariables map[string]string `json:"environment_variables"`
Description string `json:"description"`
JobTimeout *scw.Duration `json:"job_timeout"`
CronSchedule *CronSchedule `json:"cron_schedule"`
LocalStorageCapacity uint32 `json:"local_storage_capacity"`
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"region"`
}
// JobRun: job run.
type JobRun struct {
ID string `json:"id"`
JobDefinitionID string `json:"job_definition_id"`
// State: default value: unknown_state
State JobRunState `json:"state"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
TerminatedAt *time.Time `json:"terminated_at"`
ExitCode *int32 `json:"exit_code"`
RunDuration *scw.Duration `json:"run_duration"`
ErrorMessage string `json:"error_message"`
CPULimit uint32 `json:"cpu_limit"`
MemoryLimit uint32 `json:"memory_limit"`
Command string `json:"command"`
EnvironmentVariables map[string]string `json:"environment_variables"`
LocalStorageCapacity uint32 `json:"local_storage_capacity"`
StartedAt *time.Time `json:"started_at"`
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"region"`
}
// Resource: resource.
type Resource struct {
CPULimit uint32 `json:"cpu_limit"`
MemoryLimit uint32 `json:"memory_limit"`
}
// UpdateJobDefinitionRequestCronScheduleConfig: update job definition request cron schedule config.
type UpdateJobDefinitionRequestCronScheduleConfig struct {
Schedule *string `json:"schedule"`
Timezone *string `json:"timezone"`
}
// CreateJobDefinitionRequest: create job definition request.
type CreateJobDefinitionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the job definition.
Name string `json:"name"`
// CPULimit: CPU limit of the job.
CPULimit uint32 `json:"cpu_limit"`
// MemoryLimit: memory limit of the job (in MiB).
MemoryLimit uint32 `json:"memory_limit"`
// LocalStorageCapacity: local storage capacity of the job (in MiB).
LocalStorageCapacity *uint32 `json:"local_storage_capacity,omitempty"`
// ImageURI: image to use for the job.
ImageURI string `json:"image_uri"`
// Command: startup command. If empty or not defined, the image's default command is used.
Command string `json:"command"`
// ProjectID: UUID of the Scaleway Project containing the job.
ProjectID string `json:"project_id"`
// EnvironmentVariables: environment variables of the job.
EnvironmentVariables map[string]string `json:"environment_variables"`
// Description: description of the job.
Description string `json:"description"`
// JobTimeout: timeout of the job in seconds.
JobTimeout *scw.Duration `json:"job_timeout,omitempty"`
// CronSchedule: configure a cron for the job.
CronSchedule *CreateJobDefinitionRequestCronScheduleConfig `json:"cron_schedule,omitempty"`
}
// CreateJobDefinitionSecretsRequest: create job definition secrets request.
type CreateJobDefinitionSecretsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition.
JobDefinitionID string `json:"-"`
// Secrets: list of secrets to inject into the job.
Secrets []*CreateJobDefinitionSecretsRequestSecretConfig `json:"secrets"`
}
// CreateJobDefinitionSecretsResponse: create job definition secrets response.
type CreateJobDefinitionSecretsResponse struct {
// Secrets: list of secrets created.
Secrets []*Secret `json:"secrets"`
}
// DeleteJobDefinitionRequest: delete job definition request.
type DeleteJobDefinitionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition to delete.
JobDefinitionID string `json:"-"`
}
// DeleteJobDefinitionSecretRequest: delete job definition secret request.
type DeleteJobDefinitionSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition.
JobDefinitionID string `json:"-"`
// SecretID: UUID of the secret reference within the job.
SecretID string `json:"-"`
}
// GetJobDefinitionRequest: get job definition request.
type GetJobDefinitionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition to get.
JobDefinitionID string `json:"-"`
}
// GetJobDefinitionSecretRequest: get job definition secret request.
type GetJobDefinitionSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition.
JobDefinitionID string `json:"-"`
// SecretID: UUID of the secret reference within the job.
SecretID string `json:"-"`
}
// GetJobRunRequest: get job run request.
type GetJobRunRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobRunID: UUID of the job run to get.
JobRunID string `json:"-"`
}
// GetJobsLimitsRequest: get jobs limits request.
type GetJobsLimitsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// JobsLimits: jobs limits.
type JobsLimits struct {
SecretsPerJobDefinition uint32 `json:"secrets_per_job_definition"`
}
// ListJobDefinitionSecretsRequest: list job definition secrets request.
type ListJobDefinitionSecretsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition.
JobDefinitionID string `json:"-"`
}
// ListJobDefinitionSecretsResponse: list job definition secrets response.
type ListJobDefinitionSecretsResponse struct {
// Secrets: list of secret references within a job definition.
Secrets []*Secret `json:"secrets"`
// TotalCount: total count of secret references within a job definition.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJobDefinitionSecretsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJobDefinitionSecretsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJobDefinitionSecretsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Secrets = append(r.Secrets, results.Secrets...)
r.TotalCount += uint64(len(results.Secrets))
return uint64(len(results.Secrets)), nil
}
// ListJobDefinitionsRequest: list job definitions request.
type ListJobDefinitionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListJobDefinitionsRequestOrderBy `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
}
// ListJobDefinitionsResponse: list job definitions response.
type ListJobDefinitionsResponse struct {
JobDefinitions []*JobDefinition `json:"job_definitions"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJobDefinitionsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJobDefinitionsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJobDefinitionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.JobDefinitions = append(r.JobDefinitions, results.JobDefinitions...)
r.TotalCount += uint64(len(results.JobDefinitions))
return uint64(len(results.JobDefinitions)), nil
}
// ListJobRunsRequest: list job runs request.
type ListJobRunsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListJobRunsRequestOrderBy `json:"-"`
JobDefinitionID *string `json:"-"`
ProjectID *string `json:"-"`
OrganizationID *string `json:"-"`
// State: default value: unknown_state
State JobRunState `json:"-"`
}
// ListJobRunsResponse: list job runs response.
type ListJobRunsResponse struct {
JobRuns []*JobRun `json:"job_runs"`
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJobRunsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJobRunsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJobRunsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.JobRuns = append(r.JobRuns, results.JobRuns...)
r.TotalCount += uint64(len(results.JobRuns))
return uint64(len(results.JobRuns)), nil
}
// ListJobsResourcesRequest: list jobs resources request.
type ListJobsResourcesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// ListJobsResourcesResponse: list jobs resources response.
type ListJobsResourcesResponse struct {
Resources []*Resource `json:"resources"`
}
// StartJobDefinitionRequest: start job definition request.
type StartJobDefinitionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition to start.
JobDefinitionID string `json:"-"`
// Command: contextual startup command for this specific job run.
Command *string `json:"command,omitempty"`
// EnvironmentVariables: contextual environment variables for this specific job run.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// Replicas: number of jobs to run.
Replicas *uint32 `json:"replicas,omitempty"`
}
// StartJobDefinitionResponse: start job definition response.
type StartJobDefinitionResponse struct {
JobRuns []*JobRun `json:"job_runs"`
}
// StopJobRunRequest: stop job run request.
type StopJobRunRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobRunID: UUID of the job run to stop.
JobRunID string `json:"-"`
}
// UpdateJobDefinitionRequest: update job definition request.
type UpdateJobDefinitionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition to update.
JobDefinitionID string `json:"-"`
// Name: name of the job definition.
Name *string `json:"name,omitempty"`
// CPULimit: CPU limit of the job.
CPULimit *uint32 `json:"cpu_limit,omitempty"`
// MemoryLimit: memory limit of the job (in MiB).
MemoryLimit *uint32 `json:"memory_limit,omitempty"`
// LocalStorageCapacity: local storage capacity of the job (in MiB).
LocalStorageCapacity *uint32 `json:"local_storage_capacity,omitempty"`
// ImageURI: image to use for the job.
ImageURI *string `json:"image_uri,omitempty"`
// Command: startup command.
Command *string `json:"command,omitempty"`
// EnvironmentVariables: environment variables of the job.
EnvironmentVariables *map[string]string `json:"environment_variables,omitempty"`
// Description: description of the job.
Description *string `json:"description,omitempty"`
// JobTimeout: timeout of the job in seconds.
JobTimeout *scw.Duration `json:"job_timeout,omitempty"`
CronSchedule *UpdateJobDefinitionRequestCronScheduleConfig `json:"cron_schedule,omitempty"`
}
// UpdateJobDefinitionSecretRequest: update job definition secret request.
type UpdateJobDefinitionSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// JobDefinitionID: UUID of the job definition.
JobDefinitionID string `json:"-"`
// SecretID: UUID of the secret reference within the job.
SecretID string `json:"-"`
// SecretManagerVersion: version of the secret in Secret Manager.
SecretManagerVersion *string `json:"secret_manager_version,omitempty"`
// Path: path of the secret to mount inside the job (either `path` or `env_var_name` must be set).
// Precisely one of Path, EnvVarName must be set.
Path *string `json:"path,omitempty"`
// EnvVarName: environment variable name used to expose the secret inside the job (either `path` or `env_var_name` must be set).
// Precisely one of Path, EnvVarName must be set.
EnvVarName *string `json:"env_var_name,omitempty"`
}
// This API allows you to manage your Serverless Jobs.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateJobDefinition: Create a new job definition in a specified Project.
func (s *API) CreateJobDefinition(req *CreateJobDefinitionRequest, opts ...scw.RequestOption) (*JobDefinition, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("job")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp JobDefinition
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetJobDefinition: Get a job definition by its unique identifier.
func (s *API) GetJobDefinition(req *GetJobDefinitionRequest, opts ...scw.RequestOption) (*JobDefinition, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "",
}
var resp JobDefinition
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobDefinitions: List all your job definitions with filters.
func (s *API) ListJobDefinitions(req *ListJobDefinitionsRequest, opts ...scw.RequestOption) (*ListJobDefinitionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions",
Query: query,
}
var resp ListJobDefinitionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateJobDefinition: Update an existing job definition associated with the specified unique identifier.
func (s *API) UpdateJobDefinition(req *UpdateJobDefinitionRequest, opts ...scw.RequestOption) (*JobDefinition, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp JobDefinition
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteJobDefinition: Delete an exsisting job definition by its unique identifier.
func (s *API) DeleteJobDefinition(req *DeleteJobDefinitionRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// StartJobDefinition: Run an existing job definition by its unique identifier. This will create a new job run.
func (s *API) StartJobDefinition(req *StartJobDefinitionRequest, opts ...scw.RequestOption) (*StartJobDefinitionResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/start",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp StartJobDefinitionResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateJobDefinitionSecrets: Create a secret reference within a job definition.
func (s *API) CreateJobDefinitionSecrets(req *CreateJobDefinitionSecretsRequest, opts ...scw.RequestOption) (*CreateJobDefinitionSecretsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/secrets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateJobDefinitionSecretsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetJobDefinitionSecret: Get a secret references within a job definition.
func (s *API) GetJobDefinitionSecret(req *GetJobDefinitionSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobDefinitionSecrets: List secrets references within a job definition.
func (s *API) ListJobDefinitionSecrets(req *ListJobDefinitionSecretsRequest, opts ...scw.RequestOption) (*ListJobDefinitionSecretsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/secrets",
}
var resp ListJobDefinitionSecretsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateJobDefinitionSecret: Update a secret reference within a job definition.
func (s *API) UpdateJobDefinitionSecret(req *UpdateJobDefinitionSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return nil, errors.New("field JobDefinitionID cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteJobDefinitionSecret: Delete a secret reference within a job definition.
func (s *API) DeleteJobDefinitionSecret(req *DeleteJobDefinitionSecretRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobDefinitionID) == "" {
return errors.New("field JobDefinitionID cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-definitions/" + fmt.Sprint(req.JobDefinitionID) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetJobRun: Get a job run by its unique identifier.
func (s *API) GetJobRun(req *GetJobRunRequest, opts ...scw.RequestOption) (*JobRun, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobRunID) == "" {
return nil, errors.New("field JobRunID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-runs/" + fmt.Sprint(req.JobRunID) + "",
}
var resp JobRun
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// StopJobRun: Stop a job run by its unique identifier.
func (s *API) StopJobRun(req *StopJobRunRequest, opts ...scw.RequestOption) (*JobRun, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.JobRunID) == "" {
return nil, errors.New("field JobRunID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-runs/" + fmt.Sprint(req.JobRunID) + "/stop",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp JobRun
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobRuns: List all job runs with filters.
func (s *API) ListJobRuns(req *ListJobRunsRequest, opts ...scw.RequestOption) (*ListJobRunsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "job_definition_id", req.JobDefinitionID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "state", req.State)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/job-runs",
Query: query,
}
var resp ListJobRunsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobsResources: List jobs resources for the console.
func (s *API) ListJobsResources(req *ListJobsResourcesRequest, opts ...scw.RequestOption) (*ListJobsResourcesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/jobs-resources",
}
var resp ListJobsResourcesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetJobsLimits: Get jobs limits for the console.
func (s *API) GetJobsLimits(req *GetJobsLimitsRequest, opts ...scw.RequestOption) (*JobsLimits, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-jobs/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/jobs-limits",
}
var resp JobsLimits
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027224 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/jobs/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000002157 14747113137 0031415 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
jobs "github.com/scaleway/scaleway-sdk-go/api/jobs/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepJobDefinition(scwClient *scw.Client, region scw.Region) error {
jobsAPI := jobs.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the jobs definitions in (%s)", region)
listJobDefinitions, err := jobsAPI.ListJobDefinitions(
&jobs.ListJobDefinitionsRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing definition in (%s) in sweeper: %s", region, err)
}
for _, definition := range listJobDefinitions.JobDefinitions {
err := jobsAPI.DeleteJobDefinition(&jobs.DeleteJobDefinitionRequest{
JobDefinitionID: definition.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting definition in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&jobs.API{}).Regions() {
err := SweepJobDefinition(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/ 0000775 0000000 0000000 00000000000 14747113137 0023522 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024050 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/k8s_helpers.go 0000664 0000000 0000000 00000013712 14747113137 0026632 0 ustar 00root root 0000000 0000000 package k8s
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
waitForClusterDefaultTimeout = 15 * time.Minute
waitForPoolDefaultTimeout = 15 * time.Minute
waitForNodeDefaultTimeout = 15 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// WaitForClusterRequest is used by WaitForCluster method.
type WaitForClusterRequest struct {
ClusterID string
Region scw.Region
Status ClusterStatus
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForCluster waits for the cluster to be in a "terminal state" before returning.
func (s *API) WaitForCluster(req *WaitForClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
timeout := waitForClusterDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ClusterStatus]struct{}{
ClusterStatusReady: {},
ClusterStatusLocked: {},
ClusterStatusDeleted: {},
ClusterStatusPoolRequired: {},
}
cluster, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
cluster, err := s.GetCluster(&GetClusterRequest{
ClusterID: req.ClusterID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[cluster.Status]
return cluster, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for cluster failed")
}
return cluster.(*Cluster), nil
}
// WaitForPoolRequest is used by WaitForPool method.
type WaitForPoolRequest struct {
PoolID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForPool waits for a pool to be ready
func (s *API) WaitForPool(req *WaitForPoolRequest, opts ...scw.RequestOption) (*Pool, error) {
timeout := waitForPoolDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[PoolStatus]struct{}{
PoolStatusReady: {},
PoolStatusWarning: {},
}
pool, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetPool(&GetPoolRequest{
PoolID: req.PoolID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for pool failed")
}
return pool.(*Pool), err
}
// WaitForNodeRequest is used by WaitForNode method.
type WaitForNodeRequest struct {
NodeID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForNode waits for a Node to be ready
func (s *API) WaitForNode(req *WaitForNodeRequest, opts ...scw.RequestOption) (*Node, error) {
timeout := waitForNodeDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[NodeStatus]struct{}{
NodeStatusCreationError: {},
NodeStatusReady: {},
}
node, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetNode(&GetNodeRequest{
NodeID: req.NodeID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for node failed")
}
return node.(*Node), err
}
// WaitForClusterPoolRequest is used by WaitForClusterPool method.
type WaitForClusterPoolRequest struct {
ClusterID string
Region scw.Region
Status ClusterStatus
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForClusterPool waits for the pool associated with a cluster to be in a "terminal state" before returning.
func (s *API) WaitForClusterPool(req *WaitForClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
timeout := waitForClusterDefaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalClusterStatus := map[ClusterStatus]struct{}{
ClusterStatusPoolRequired: {},
ClusterStatusReady: {},
}
terminalPoolStatus := map[PoolStatus]struct{}{
PoolStatusReady: {},
PoolStatusWarning: {},
}
optsWithAllPages := append(opts, scw.WithAllPages()) //nolint:gocritic
cluster, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
cluster, err := s.GetCluster(&GetClusterRequest{
ClusterID: req.ClusterID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalClusterStatus[cluster.Status]
if !isTerminal {
return cluster, false, nil
}
pools, err := s.ListPools(&ListPoolsRequest{
Region: req.Region,
ClusterID: req.ClusterID,
}, optsWithAllPages...)
if err != nil {
return nil, false, err
}
for _, pool := range pools.Pools {
_, isTerminal = terminalPoolStatus[pool.Status]
if !isTerminal {
return cluster, false, nil
}
}
return cluster, true, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for cluster failed")
}
return cluster.(*Cluster), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/k8s_sdk.go 0000664 0000000 0000000 00000324232 14747113137 0025753 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package k8s provides methods and message types of the k8s v1 API.
package k8s
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type AutoscalerEstimator string
const (
AutoscalerEstimatorUnknownEstimator = AutoscalerEstimator("unknown_estimator")
AutoscalerEstimatorBinpacking = AutoscalerEstimator("binpacking")
)
func (enum AutoscalerEstimator) String() string {
if enum == "" {
// return default value if empty
return "unknown_estimator"
}
return string(enum)
}
func (enum AutoscalerEstimator) Values() []AutoscalerEstimator {
return []AutoscalerEstimator{
"unknown_estimator",
"binpacking",
}
}
func (enum AutoscalerEstimator) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *AutoscalerEstimator) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = AutoscalerEstimator(AutoscalerEstimator(tmp).String())
return nil
}
// Kubernetes autoscaler strategy to fit pods into cluster nodes (https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#what-are-expanders).
type AutoscalerExpander string
const (
AutoscalerExpanderUnknownExpander = AutoscalerExpander("unknown_expander")
AutoscalerExpanderRandom = AutoscalerExpander("random")
AutoscalerExpanderMostPods = AutoscalerExpander("most_pods")
AutoscalerExpanderLeastWaste = AutoscalerExpander("least_waste")
AutoscalerExpanderPriority = AutoscalerExpander("priority")
AutoscalerExpanderPrice = AutoscalerExpander("price")
)
func (enum AutoscalerExpander) String() string {
if enum == "" {
// return default value if empty
return "unknown_expander"
}
return string(enum)
}
func (enum AutoscalerExpander) Values() []AutoscalerExpander {
return []AutoscalerExpander{
"unknown_expander",
"random",
"most_pods",
"least_waste",
"priority",
"price",
}
}
func (enum AutoscalerExpander) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *AutoscalerExpander) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = AutoscalerExpander(AutoscalerExpander(tmp).String())
return nil
}
type CNI string
const (
CNIUnknownCni = CNI("unknown_cni")
// Cilium CNI will be configured (https://github.com/cilium/cilium).
CNICilium = CNI("cilium")
// Calico CNI will be configured (https://github.com/projectcalico/calico).
CNICalico = CNI("calico")
CNIWeave = CNI("weave")
CNIFlannel = CNI("flannel")
// Kilo CNI will be configured (https://github.com/squat/kilo/). Note that this CNI is only available for Kosmos clusters.
CNIKilo = CNI("kilo")
// Does not install any CNI. This feature is only available through a ticket and is not covered by support.
CNINone = CNI("none")
)
func (enum CNI) String() string {
if enum == "" {
// return default value if empty
return "unknown_cni"
}
return string(enum)
}
func (enum CNI) Values() []CNI {
return []CNI{
"unknown_cni",
"cilium",
"calico",
"weave",
"flannel",
"kilo",
"none",
}
}
func (enum CNI) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *CNI) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = CNI(CNI(tmp).String())
return nil
}
type ClusterStatus string
const (
ClusterStatusUnknown = ClusterStatus("unknown")
// Cluster is provisioning.
ClusterStatusCreating = ClusterStatus("creating")
// Cluster is ready to use.
ClusterStatusReady = ClusterStatus("ready")
// Cluster is waiting to be processed for deletion.
ClusterStatusDeleting = ClusterStatus("deleting")
ClusterStatusDeleted = ClusterStatus("deleted")
// Cluster is updating its own configuration, it can be a version upgrade too.
ClusterStatusUpdating = ClusterStatus("updating")
// Cluster is locked because an abuse has been detected or reported.
ClusterStatusLocked = ClusterStatus("locked")
// Cluster has no associated pool.
ClusterStatusPoolRequired = ClusterStatus("pool_required")
)
func (enum ClusterStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ClusterStatus) Values() []ClusterStatus {
return []ClusterStatus{
"unknown",
"creating",
"ready",
"deleting",
"deleted",
"updating",
"locked",
"pool_required",
}
}
func (enum ClusterStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ClusterStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ClusterStatus(ClusterStatus(tmp).String())
return nil
}
type ClusterTypeAvailability string
const (
// Type is available in quantity.
ClusterTypeAvailabilityAvailable = ClusterTypeAvailability("available")
// Limited availability.
ClusterTypeAvailabilityScarce = ClusterTypeAvailability("scarce")
// Out of stock.
ClusterTypeAvailabilityShortage = ClusterTypeAvailability("shortage")
)
func (enum ClusterTypeAvailability) String() string {
if enum == "" {
// return default value if empty
return "available"
}
return string(enum)
}
func (enum ClusterTypeAvailability) Values() []ClusterTypeAvailability {
return []ClusterTypeAvailability{
"available",
"scarce",
"shortage",
}
}
func (enum ClusterTypeAvailability) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ClusterTypeAvailability) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ClusterTypeAvailability(ClusterTypeAvailability(tmp).String())
return nil
}
type ClusterTypeResiliency string
const (
ClusterTypeResiliencyUnknownResiliency = ClusterTypeResiliency("unknown_resiliency")
// The control plane is rescheduled on other machines in case of failure of a lower layer.
ClusterTypeResiliencyStandard = ClusterTypeResiliency("standard")
// The control plane has replicas to ensure service continuity in case of failure of a lower layer.
ClusterTypeResiliencyHighAvailability = ClusterTypeResiliency("high_availability")
)
func (enum ClusterTypeResiliency) String() string {
if enum == "" {
// return default value if empty
return "unknown_resiliency"
}
return string(enum)
}
func (enum ClusterTypeResiliency) Values() []ClusterTypeResiliency {
return []ClusterTypeResiliency{
"unknown_resiliency",
"standard",
"high_availability",
}
}
func (enum ClusterTypeResiliency) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ClusterTypeResiliency) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ClusterTypeResiliency(ClusterTypeResiliency(tmp).String())
return nil
}
type ListClustersRequestOrderBy string
const (
ListClustersRequestOrderByCreatedAtAsc = ListClustersRequestOrderBy("created_at_asc")
ListClustersRequestOrderByCreatedAtDesc = ListClustersRequestOrderBy("created_at_desc")
ListClustersRequestOrderByUpdatedAtAsc = ListClustersRequestOrderBy("updated_at_asc")
ListClustersRequestOrderByUpdatedAtDesc = ListClustersRequestOrderBy("updated_at_desc")
ListClustersRequestOrderByNameAsc = ListClustersRequestOrderBy("name_asc")
ListClustersRequestOrderByNameDesc = ListClustersRequestOrderBy("name_desc")
ListClustersRequestOrderByStatusAsc = ListClustersRequestOrderBy("status_asc")
ListClustersRequestOrderByStatusDesc = ListClustersRequestOrderBy("status_desc")
ListClustersRequestOrderByVersionAsc = ListClustersRequestOrderBy("version_asc")
ListClustersRequestOrderByVersionDesc = ListClustersRequestOrderBy("version_desc")
)
func (enum ListClustersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListClustersRequestOrderBy) Values() []ListClustersRequestOrderBy {
return []ListClustersRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
"version_asc",
"version_desc",
}
}
func (enum ListClustersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListClustersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListClustersRequestOrderBy(ListClustersRequestOrderBy(tmp).String())
return nil
}
type ListNodesRequestOrderBy string
const (
ListNodesRequestOrderByCreatedAtAsc = ListNodesRequestOrderBy("created_at_asc")
ListNodesRequestOrderByCreatedAtDesc = ListNodesRequestOrderBy("created_at_desc")
ListNodesRequestOrderByUpdatedAtAsc = ListNodesRequestOrderBy("updated_at_asc")
ListNodesRequestOrderByUpdatedAtDesc = ListNodesRequestOrderBy("updated_at_desc")
ListNodesRequestOrderByNameAsc = ListNodesRequestOrderBy("name_asc")
ListNodesRequestOrderByNameDesc = ListNodesRequestOrderBy("name_desc")
ListNodesRequestOrderByStatusAsc = ListNodesRequestOrderBy("status_asc")
ListNodesRequestOrderByStatusDesc = ListNodesRequestOrderBy("status_desc")
ListNodesRequestOrderByVersionAsc = ListNodesRequestOrderBy("version_asc")
ListNodesRequestOrderByVersionDesc = ListNodesRequestOrderBy("version_desc")
)
func (enum ListNodesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNodesRequestOrderBy) Values() []ListNodesRequestOrderBy {
return []ListNodesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
"version_asc",
"version_desc",
}
}
func (enum ListNodesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNodesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNodesRequestOrderBy(ListNodesRequestOrderBy(tmp).String())
return nil
}
type ListPoolsRequestOrderBy string
const (
ListPoolsRequestOrderByCreatedAtAsc = ListPoolsRequestOrderBy("created_at_asc")
ListPoolsRequestOrderByCreatedAtDesc = ListPoolsRequestOrderBy("created_at_desc")
ListPoolsRequestOrderByUpdatedAtAsc = ListPoolsRequestOrderBy("updated_at_asc")
ListPoolsRequestOrderByUpdatedAtDesc = ListPoolsRequestOrderBy("updated_at_desc")
ListPoolsRequestOrderByNameAsc = ListPoolsRequestOrderBy("name_asc")
ListPoolsRequestOrderByNameDesc = ListPoolsRequestOrderBy("name_desc")
ListPoolsRequestOrderByStatusAsc = ListPoolsRequestOrderBy("status_asc")
ListPoolsRequestOrderByStatusDesc = ListPoolsRequestOrderBy("status_desc")
ListPoolsRequestOrderByVersionAsc = ListPoolsRequestOrderBy("version_asc")
ListPoolsRequestOrderByVersionDesc = ListPoolsRequestOrderBy("version_desc")
)
func (enum ListPoolsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPoolsRequestOrderBy) Values() []ListPoolsRequestOrderBy {
return []ListPoolsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
"version_asc",
"version_desc",
}
}
func (enum ListPoolsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPoolsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPoolsRequestOrderBy(ListPoolsRequestOrderBy(tmp).String())
return nil
}
type MaintenanceWindowDayOfTheWeek string
const (
MaintenanceWindowDayOfTheWeekAny = MaintenanceWindowDayOfTheWeek("any")
MaintenanceWindowDayOfTheWeekMonday = MaintenanceWindowDayOfTheWeek("monday")
MaintenanceWindowDayOfTheWeekTuesday = MaintenanceWindowDayOfTheWeek("tuesday")
MaintenanceWindowDayOfTheWeekWednesday = MaintenanceWindowDayOfTheWeek("wednesday")
MaintenanceWindowDayOfTheWeekThursday = MaintenanceWindowDayOfTheWeek("thursday")
MaintenanceWindowDayOfTheWeekFriday = MaintenanceWindowDayOfTheWeek("friday")
MaintenanceWindowDayOfTheWeekSaturday = MaintenanceWindowDayOfTheWeek("saturday")
MaintenanceWindowDayOfTheWeekSunday = MaintenanceWindowDayOfTheWeek("sunday")
)
func (enum MaintenanceWindowDayOfTheWeek) String() string {
if enum == "" {
// return default value if empty
return "any"
}
return string(enum)
}
func (enum MaintenanceWindowDayOfTheWeek) Values() []MaintenanceWindowDayOfTheWeek {
return []MaintenanceWindowDayOfTheWeek{
"any",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
}
}
func (enum MaintenanceWindowDayOfTheWeek) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MaintenanceWindowDayOfTheWeek) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MaintenanceWindowDayOfTheWeek(MaintenanceWindowDayOfTheWeek(tmp).String())
return nil
}
type NodeStatus string
const (
NodeStatusUnknown = NodeStatus("unknown")
// Node is provisioning.
NodeStatusCreating = NodeStatus("creating")
// Node is unable to connect to apiserver.
NodeStatusNotReady = NodeStatus("not_ready")
// Node is ready to execute workload (marked schedulable by k8s scheduler).
NodeStatusReady = NodeStatus("ready")
// Node is waiting to be processed for deletion.
NodeStatusDeleting = NodeStatus("deleting")
NodeStatusDeleted = NodeStatus("deleted")
// Node is locked because an abuse has been detected or reported.
NodeStatusLocked = NodeStatus("locked")
// Node is rebooting.
NodeStatusRebooting = NodeStatus("rebooting")
NodeStatusCreationError = NodeStatus("creation_error")
NodeStatusUpgrading = NodeStatus("upgrading")
NodeStatusStarting = NodeStatus("starting")
NodeStatusRegistering = NodeStatus("registering")
)
func (enum NodeStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NodeStatus) Values() []NodeStatus {
return []NodeStatus{
"unknown",
"creating",
"not_ready",
"ready",
"deleting",
"deleted",
"locked",
"rebooting",
"creation_error",
"upgrading",
"starting",
"registering",
}
}
func (enum NodeStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeStatus(NodeStatus(tmp).String())
return nil
}
type PoolStatus string
const (
PoolStatusUnknown = PoolStatus("unknown")
// Pool has the right amount of nodes and is ready to process the workload.
PoolStatusReady = PoolStatus("ready")
// Pool is waiting to be processed for deletion.
PoolStatusDeleting = PoolStatus("deleting")
PoolStatusDeleted = PoolStatus("deleted")
// Pool is growing or shrinking.
PoolStatusScaling = PoolStatus("scaling")
PoolStatusWarning = PoolStatus("warning")
// Pool is locked because an abuse has been detected or reported.
PoolStatusLocked = PoolStatus("locked")
// Pool is upgrading its Kubernetes version.
PoolStatusUpgrading = PoolStatus("upgrading")
)
func (enum PoolStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum PoolStatus) Values() []PoolStatus {
return []PoolStatus{
"unknown",
"ready",
"deleting",
"deleted",
"scaling",
"warning",
"locked",
"upgrading",
}
}
func (enum PoolStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PoolStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PoolStatus(PoolStatus(tmp).String())
return nil
}
type PoolVolumeType string
const (
PoolVolumeTypeDefaultVolumeType = PoolVolumeType("default_volume_type")
// Local Block Storage: your system is stored locally on your node hypervisor. Lower latency, no persistence across node replacements.
PoolVolumeTypeLSSD = PoolVolumeType("l_ssd")
// Remote Block Storage: your system is stored on a centralized and resilient cluster. Higher latency, persistence across node replacements.
PoolVolumeTypeBSSD = PoolVolumeType("b_ssd")
PoolVolumeTypeSbs5k = PoolVolumeType("sbs_5k")
PoolVolumeTypeSbs15k = PoolVolumeType("sbs_15k")
)
func (enum PoolVolumeType) String() string {
if enum == "" {
// return default value if empty
return "default_volume_type"
}
return string(enum)
}
func (enum PoolVolumeType) Values() []PoolVolumeType {
return []PoolVolumeType{
"default_volume_type",
"l_ssd",
"b_ssd",
"sbs_5k",
"sbs_15k",
}
}
func (enum PoolVolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PoolVolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PoolVolumeType(PoolVolumeType(tmp).String())
return nil
}
type Runtime string
const (
RuntimeUnknownRuntime = Runtime("unknown_runtime")
RuntimeDocker = Runtime("docker")
// Containerd Runtime will be configured (https://github.com/containerd/containerd).
RuntimeContainerd = Runtime("containerd")
RuntimeCrio = Runtime("crio")
)
func (enum Runtime) String() string {
if enum == "" {
// return default value if empty
return "unknown_runtime"
}
return string(enum)
}
func (enum Runtime) Values() []Runtime {
return []Runtime{
"unknown_runtime",
"docker",
"containerd",
"crio",
}
}
func (enum Runtime) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Runtime) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Runtime(Runtime(tmp).String())
return nil
}
// MaintenanceWindow: maintenance window.
type MaintenanceWindow struct {
// StartHour: start time of the two-hour maintenance window.
StartHour uint32 `json:"start_hour"`
// Day: day of the week for the maintenance window.
// Default value: any
Day MaintenanceWindowDayOfTheWeek `json:"day"`
}
// PoolUpgradePolicy: pool upgrade policy.
type PoolUpgradePolicy struct {
MaxUnavailable uint32 `json:"max_unavailable"`
MaxSurge uint32 `json:"max_surge"`
}
// CreateClusterRequestPoolConfigUpgradePolicy: create cluster request pool config upgrade policy.
type CreateClusterRequestPoolConfigUpgradePolicy struct {
// MaxUnavailable: the maximum number of nodes that can be not ready at the same time.
MaxUnavailable *uint32 `json:"max_unavailable"`
// MaxSurge: the maximum number of nodes to be created during the upgrade.
MaxSurge *uint32 `json:"max_surge"`
}
// ClusterAutoUpgrade: cluster auto upgrade.
type ClusterAutoUpgrade struct {
// Enabled: defines whether auto upgrade is enabled for the cluster.
Enabled bool `json:"enabled"`
// MaintenanceWindow: maintenance window of the cluster auto upgrades.
MaintenanceWindow *MaintenanceWindow `json:"maintenance_window"`
}
// ClusterAutoscalerConfig: cluster autoscaler config.
type ClusterAutoscalerConfig struct {
// ScaleDownDisabled: disable the cluster autoscaler.
ScaleDownDisabled bool `json:"scale_down_disabled"`
// ScaleDownDelayAfterAdd: how long after scale up the scale down evaluation resumes.
ScaleDownDelayAfterAdd string `json:"scale_down_delay_after_add"`
// Estimator: type of resource estimator to be used in scale up.
// Default value: unknown_estimator
Estimator AutoscalerEstimator `json:"estimator"`
// Expander: type of node group expander to be used in scale up.
// Default value: unknown_expander
Expander AutoscalerExpander `json:"expander"`
// IgnoreDaemonsetsUtilization: ignore DaemonSet pods when calculating resource utilization for scaling down.
IgnoreDaemonsetsUtilization bool `json:"ignore_daemonsets_utilization"`
// BalanceSimilarNodeGroups: detect similar node groups and balance the number of nodes between them.
BalanceSimilarNodeGroups bool `json:"balance_similar_node_groups"`
// ExpendablePodsPriorityCutoff: pods with priority below cutoff will be expendable. They can be killed without any consideration during scale down and they won't cause scale up. Pods with null priority (PodPriority disabled) are non expendable.
ExpendablePodsPriorityCutoff int32 `json:"expendable_pods_priority_cutoff"`
// ScaleDownUnneededTime: how long a node should be unneeded before it is eligible to be scaled down.
ScaleDownUnneededTime string `json:"scale_down_unneeded_time"`
// ScaleDownUtilizationThreshold: node utilization level, defined as a sum of requested resources divided by capacity, below which a node can be considered for scale down.
ScaleDownUtilizationThreshold float32 `json:"scale_down_utilization_threshold"`
// MaxGracefulTerminationSec: maximum number of seconds the cluster autoscaler waits for pod termination when trying to scale down a node.
MaxGracefulTerminationSec uint32 `json:"max_graceful_termination_sec"`
}
// ClusterOpenIDConnectConfig: cluster open id connect config.
type ClusterOpenIDConnectConfig struct {
// IssuerURL: URL of the provider which allows the API server to discover public signing keys. Only URLs using the `https://` scheme are accepted. This is typically the provider's discovery URL without a path, for example "https://accounts.google.com" or "https://login.salesforce.com".
IssuerURL string `json:"issuer_url"`
// ClientID: a client ID that all tokens must be issued for.
ClientID string `json:"client_id"`
// UsernameClaim: jWT claim to use as the user name. The default is `sub`, which is expected to be the end user's unique identifier. Admins can choose other claims, such as `email` or `name`, depending on their provider. However, claims other than `email` will be prefixed with the issuer URL to prevent name collision.
UsernameClaim string `json:"username_claim"`
// UsernamePrefix: prefix prepended to username claims to prevent name collision (such as `system:` users). For example, the value `oidc:` will create usernames like `oidc:jane.doe`. If this flag is not provided and `username_claim` is a value other than `email`, the prefix defaults to `( Issuer URL )#` where `( Issuer URL )` is the value of `issuer_url`. The value `-` can be used to disable all prefixing.
UsernamePrefix string `json:"username_prefix"`
// GroupsClaim: jWT claim to use as the user's group.
GroupsClaim []string `json:"groups_claim"`
// GroupsPrefix: prefix prepended to group claims to prevent name collision (such as `system:` groups). For example, the value `oidc:` will create group names like `oidc:engineering` and `oidc:infra`.
GroupsPrefix string `json:"groups_prefix"`
// RequiredClaim: multiple key=value pairs describing a required claim in the ID token. If set, the claims are verified to be present in the ID token with a matching value.
RequiredClaim []string `json:"required_claim"`
}
// Pool: pool.
type Pool struct {
// ID: pool ID.
ID string `json:"id"`
// ClusterID: cluster ID of the pool.
ClusterID string `json:"cluster_id"`
// CreatedAt: date on which the pool was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the pool was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// Name: pool name.
Name string `json:"name"`
// Status: pool status.
// Default value: unknown
Status PoolStatus `json:"status"`
// Version: pool version.
Version string `json:"version"`
// NodeType: node type is the type of Scaleway Instance wanted for the pool. Nodes with insufficient memory are not eligible (DEV1-S, PLAY2-PICO, STARDUST). 'external' is a special node type used to provision instances from other cloud providers in a Kosmos Cluster.
NodeType string `json:"node_type"`
// Autoscaling: defines whether the autoscaling feature is enabled for the pool.
Autoscaling bool `json:"autoscaling"`
// Size: size (number of nodes) of the pool.
Size uint32 `json:"size"`
// MinSize: defines the minimum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MinSize uint32 `json:"min_size"`
// MaxSize: defines the maximum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MaxSize uint32 `json:"max_size"`
// ContainerRuntime: customization of the container runtime is available for each pool.
// Default value: unknown_runtime
ContainerRuntime Runtime `json:"container_runtime"`
// Autohealing: defines whether the autohealing feature is enabled for the pool.
Autohealing bool `json:"autohealing"`
// Tags: tags associated with the pool, see [managing tags](https://www.scaleway.com/en/docs/containers/kubernetes/api-cli/managing-tags).
Tags []string `json:"tags"`
// PlacementGroupID: placement group ID in which all the nodes of the pool will be created, placement groups are limited to 20 instances.
PlacementGroupID *string `json:"placement_group_id"`
// KubeletArgs: kubelet arguments to be used by this pool. Note that this feature is experimental.
KubeletArgs map[string]string `json:"kubelet_args"`
// UpgradePolicy: pool upgrade policy.
UpgradePolicy *PoolUpgradePolicy `json:"upgrade_policy"`
// Zone: zone in which the pool's nodes will be spawned.
Zone scw.Zone `json:"zone"`
// RootVolumeType: * `l_ssd` is a local block storage which means your system is stored locally on your node's hypervisor. This type is not available for all node types
// * `sbs-5k` is a remote block storage which means your system is stored on a centralized and resilient cluster with 5k IOPS limits
// * `sbs-15k` is a faster remote block storage which means your system is stored on a centralized and resilient cluster with 15k IOPS limits
// * `b_ssd` is the legacy remote block storage which means your system is stored on a centralized and resilient cluster. Consider using `sbs-5k` or `sbs-15k` instead.
// Default value: default_volume_type
RootVolumeType PoolVolumeType `json:"root_volume_type"`
// RootVolumeSize: system volume disk size.
RootVolumeSize *scw.Size `json:"root_volume_size"`
// PublicIPDisabled: defines if the public IP should be removed from Nodes. To use this feature, your Cluster must have an attached Private Network set up with a Public Gateway.
PublicIPDisabled bool `json:"public_ip_disabled"`
// Region: cluster region of the pool.
Region scw.Region `json:"region"`
}
// ACLRuleRequest: acl rule request.
type ACLRuleRequest struct {
// IP: IP subnet to allow.
// Precisely one of IP, ScalewayRanges must be set.
IP *scw.IPNet `json:"ip,omitempty"`
// ScalewayRanges: only one rule with this field set to true can be added.
// Precisely one of IP, ScalewayRanges must be set.
ScalewayRanges *bool `json:"scaleway_ranges,omitempty"`
// Description: description of the ACL.
Description string `json:"description"`
}
// ACLRule: acl rule.
type ACLRule struct {
// ID: ID of the ACL rule.
ID string `json:"id"`
// IP: IP subnet to allow.
// Precisely one of IP, ScalewayRanges must be set.
IP *scw.IPNet `json:"ip,omitempty"`
// ScalewayRanges: only one rule with this field set to true can be added.
// Precisely one of IP, ScalewayRanges must be set.
ScalewayRanges *bool `json:"scaleway_ranges,omitempty"`
// Description: description of the ACL.
Description string `json:"description"`
}
// CreateClusterRequestAutoUpgrade: create cluster request auto upgrade.
type CreateClusterRequestAutoUpgrade struct {
// Enable: defines whether auto upgrade is enabled for the cluster.
Enable bool `json:"enable"`
// MaintenanceWindow: maintenance window of the cluster auto upgrades.
MaintenanceWindow *MaintenanceWindow `json:"maintenance_window"`
}
// CreateClusterRequestAutoscalerConfig: create cluster request autoscaler config.
type CreateClusterRequestAutoscalerConfig struct {
// ScaleDownDisabled: disable the cluster autoscaler.
ScaleDownDisabled *bool `json:"scale_down_disabled"`
// ScaleDownDelayAfterAdd: how long after scale up the scale down evaluation resumes.
ScaleDownDelayAfterAdd *string `json:"scale_down_delay_after_add"`
// Estimator: type of resource estimator to be used in scale up.
// Default value: unknown_estimator
Estimator AutoscalerEstimator `json:"estimator"`
// Expander: type of node group expander to be used in scale up.
// Default value: unknown_expander
Expander AutoscalerExpander `json:"expander"`
// IgnoreDaemonsetsUtilization: ignore DaemonSet pods when calculating resource utilization for scaling down.
IgnoreDaemonsetsUtilization *bool `json:"ignore_daemonsets_utilization"`
// BalanceSimilarNodeGroups: detect similar node groups and balance the number of nodes between them.
BalanceSimilarNodeGroups *bool `json:"balance_similar_node_groups"`
// ExpendablePodsPriorityCutoff: pods with priority below cutoff will be expendable. They can be killed without any consideration during scale down and they won't cause scale up. Pods with null priority (PodPriority disabled) are non expendable.
ExpendablePodsPriorityCutoff *int32 `json:"expendable_pods_priority_cutoff"`
// ScaleDownUnneededTime: how long a node should be unneeded before it is eligible to be scaled down.
ScaleDownUnneededTime *string `json:"scale_down_unneeded_time"`
// ScaleDownUtilizationThreshold: node utilization level, defined as a sum of requested resources divided by capacity, below which a node can be considered for scale down.
ScaleDownUtilizationThreshold *float32 `json:"scale_down_utilization_threshold"`
// MaxGracefulTerminationSec: maximum number of seconds the cluster autoscaler waits for pod termination when trying to scale down a node.
MaxGracefulTerminationSec *uint32 `json:"max_graceful_termination_sec"`
}
// CreateClusterRequestOpenIDConnectConfig: create cluster request open id connect config.
type CreateClusterRequestOpenIDConnectConfig struct {
// IssuerURL: URL of the provider which allows the API server to discover public signing keys. Only URLs using the `https://` scheme are accepted. This is typically the provider's discovery URL without a path, for example "https://accounts.google.com" or "https://login.salesforce.com".
IssuerURL string `json:"issuer_url"`
// ClientID: a client ID that all tokens must be issued for.
ClientID string `json:"client_id"`
// UsernameClaim: jWT claim to use as the user name. The default is `sub`, which is expected to be the end user's unique identifier. Admins can choose other claims, such as `email` or `name`, depending on their provider. However, claims other than `email` will be prefixed with the issuer URL to prevent name collision.
UsernameClaim *string `json:"username_claim"`
// UsernamePrefix: prefix prepended to username claims to prevent name collision (such as `system:` users). For example, the value `oidc:` will create usernames like `oidc:jane.doe`. If this flag is not provided and `username_claim` is a value other than `email`, the prefix defaults to `( Issuer URL )#` where `( Issuer URL )` is the value of `issuer_url`. The value `-` can be used to disable all prefixing.
UsernamePrefix *string `json:"username_prefix"`
// GroupsClaim: jWT claim to use as the user's group.
GroupsClaim *[]string `json:"groups_claim"`
// GroupsPrefix: prefix prepended to group claims to prevent name collision (such as `system:` groups). For example, the value `oidc:` will create group names like `oidc:engineering` and `oidc:infra`.
GroupsPrefix *string `json:"groups_prefix"`
// RequiredClaim: multiple key=value pairs describing a required claim in the ID token. If set, the claims are verified to be present in the ID token with a matching value.
RequiredClaim *[]string `json:"required_claim"`
}
// CreateClusterRequestPoolConfig: create cluster request pool config.
type CreateClusterRequestPoolConfig struct {
// Name: name of the pool.
Name string `json:"name"`
// NodeType: node type is the type of Scaleway Instance wanted for the pool. Nodes with insufficient memory are not eligible (DEV1-S, PLAY2-PICO, STARDUST). 'external' is a special node type used to provision instances from other cloud providers in a Kosmos Cluster.
NodeType string `json:"node_type"`
// PlacementGroupID: placement group ID in which all the nodes of the pool will be created, placement groups are limited to 20 instances.
PlacementGroupID *string `json:"placement_group_id"`
// Autoscaling: defines whether the autoscaling feature is enabled for the pool.
Autoscaling bool `json:"autoscaling"`
// Size: size (number of nodes) of the pool.
Size uint32 `json:"size"`
// MinSize: defines the minimum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MinSize *uint32 `json:"min_size"`
// MaxSize: defines the maximum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MaxSize *uint32 `json:"max_size"`
// ContainerRuntime: customization of the container runtime is available for each pool.
// Default value: unknown_runtime
ContainerRuntime Runtime `json:"container_runtime"`
// Autohealing: defines whether the autohealing feature is enabled for the pool.
Autohealing bool `json:"autohealing"`
// Tags: tags associated with the pool, see [managing tags](https://www.scaleway.com/en/docs/containers/kubernetes/api-cli/managing-tags).
Tags []string `json:"tags"`
// KubeletArgs: kubelet arguments to be used by this pool. Note that this feature is experimental.
KubeletArgs map[string]string `json:"kubelet_args"`
// UpgradePolicy: pool upgrade policy.
UpgradePolicy *CreateClusterRequestPoolConfigUpgradePolicy `json:"upgrade_policy"`
// Zone: zone in which the pool's nodes will be spawned.
Zone scw.Zone `json:"zone"`
// RootVolumeType: * `l_ssd` is a local block storage which means your system is stored locally on your node's hypervisor. This type is not available for all node types
// * `sbs-5k` is a remote block storage which means your system is stored on a centralized and resilient cluster with 5k IOPS limits
// * `sbs-15k` is a faster remote block storage which means your system is stored on a centralized and resilient cluster with 15k IOPS limits
// * `b_ssd` is the legacy remote block storage which means your system is stored on a centralized and resilient cluster. Consider using `sbs-5k` or `sbs-15k` instead.
// Default value: default_volume_type
RootVolumeType PoolVolumeType `json:"root_volume_type"`
// RootVolumeSize: system volume disk size.
RootVolumeSize *scw.Size `json:"root_volume_size"`
// PublicIPDisabled: defines if the public IP should be removed from Nodes. To use this feature, your Cluster must have an attached Private Network set up with a Public Gateway.
PublicIPDisabled bool `json:"public_ip_disabled"`
}
// CreatePoolRequestUpgradePolicy: create pool request upgrade policy.
type CreatePoolRequestUpgradePolicy struct {
MaxUnavailable *uint32 `json:"max_unavailable"`
MaxSurge *uint32 `json:"max_surge"`
}
// ExternalNodeCoreV1Taint: external node core v1 taint.
type ExternalNodeCoreV1Taint struct {
Key string `json:"key"`
Value string `json:"value"`
Effect string `json:"effect"`
}
// ClusterType: cluster type.
type ClusterType struct {
// Name: cluster type name.
Name string `json:"name"`
// Availability: cluster type availability.
// Default value: available
Availability ClusterTypeAvailability `json:"availability"`
// MaxNodes: maximum number of nodes supported by the offer.
MaxNodes uint32 `json:"max_nodes"`
// CommitmentDelay: time period during which you can no longer switch to a lower offer.
CommitmentDelay *scw.Duration `json:"commitment_delay"`
// SLA: value of the Service Level Agreement of the offer.
SLA float32 `json:"sla"`
// Resiliency: resiliency offered by the offer.
// Default value: unknown_resiliency
Resiliency ClusterTypeResiliency `json:"resiliency"`
// Memory: max RAM allowed for the control plane.
Memory scw.Size `json:"memory"`
// Dedicated: returns information if this offer uses dedicated resources.
Dedicated bool `json:"dedicated"`
// AuditLogsSupported: true if the offer allows activation of the audit log functionality. Please note that audit logs are sent to Cockpit.
AuditLogsSupported bool `json:"audit_logs_supported"`
// MaxEtcdSize: maximum amount of data that can be stored in etcd for the offer.
MaxEtcdSize scw.Size `json:"max_etcd_size"`
}
// Version: version.
type Version struct {
// Name: name of the Kubernetes version.
Name string `json:"name"`
// Label: label of the Kubernetes version.
Label string `json:"label"`
// Region: region in which this version is available.
Region scw.Region `json:"region"`
// AvailableCnis: supported Container Network Interface (CNI) plugins for this version.
AvailableCnis []CNI `json:"available_cnis"`
// AvailableContainerRuntimes: supported container runtimes for this version.
AvailableContainerRuntimes []Runtime `json:"available_container_runtimes"`
// AvailableFeatureGates: supported feature gates for this version.
AvailableFeatureGates []string `json:"available_feature_gates"`
// AvailableAdmissionPlugins: supported admission plugins for this version.
AvailableAdmissionPlugins []string `json:"available_admission_plugins"`
// AvailableKubeletArgs: supported kubelet arguments for this version.
AvailableKubeletArgs map[string]string `json:"available_kubelet_args"`
}
// Cluster: cluster.
type Cluster struct {
// ID: cluster ID.
ID string `json:"id"`
// Type: cluster type.
Type string `json:"type"`
// Name: cluster name.
Name string `json:"name"`
// Status: status of the cluster.
// Default value: unknown
Status ClusterStatus `json:"status"`
// Version: kubernetes version of the cluster.
Version string `json:"version"`
// Region: region in which the cluster is deployed.
Region scw.Region `json:"region"`
// OrganizationID: ID of the Organization owning the cluster.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the Project owning the cluster.
ProjectID string `json:"project_id"`
// Tags: tags associated with the cluster.
Tags []string `json:"tags"`
// Cni: container Network Interface (CNI) plugin running in the cluster.
// Default value: unknown_cni
Cni CNI `json:"cni"`
// Description: cluster description.
Description string `json:"description"`
// ClusterURL: kubernetes API server URL of the cluster.
ClusterURL string `json:"cluster_url"`
// DNSWildcard: wildcard DNS resolving all the ready cluster nodes.
DNSWildcard string `json:"dns_wildcard"`
// CreatedAt: date on which the cluster was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the cluster was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// AutoscalerConfig: autoscaler config for the cluster.
AutoscalerConfig *ClusterAutoscalerConfig `json:"autoscaler_config"`
// AutoUpgrade: auto upgrade Kubernetes version of the cluster.
AutoUpgrade *ClusterAutoUpgrade `json:"auto_upgrade"`
// UpgradeAvailable: defines whether a new Kubernetes version is available.
UpgradeAvailable bool `json:"upgrade_available"`
// FeatureGates: list of enabled feature gates.
FeatureGates []string `json:"feature_gates"`
// AdmissionPlugins: list of enabled admission plugins.
AdmissionPlugins []string `json:"admission_plugins"`
// OpenIDConnectConfig: this configuration enables to update the OpenID Connect configuration of the Kubernetes API server.
OpenIDConnectConfig *ClusterOpenIDConnectConfig `json:"open_id_connect_config"`
// ApiserverCertSans: additional Subject Alternative Names for the Kubernetes API server certificate.
ApiserverCertSans []string `json:"apiserver_cert_sans"`
// PrivateNetworkID: private network ID for internal cluster communication.
PrivateNetworkID *string `json:"private_network_id"`
// CommitmentEndsAt: date on which it will be possible to switch to a smaller offer.
CommitmentEndsAt *time.Time `json:"commitment_ends_at"`
// Deprecated: SbsCsiEnabled: defines whether the SBS-enabled CSI starting from v0.3 is installed on the cluster.
SbsCsiEnabled *bool `json:"sbs_csi_enabled,omitempty"`
// Deprecated: ACLAvailable: defines whether ACL is available on the cluster.
ACLAvailable *bool `json:"acl_available,omitempty"`
}
// Node: node.
type Node struct {
// ID: node ID.
ID string `json:"id"`
// PoolID: pool ID of the node.
PoolID string `json:"pool_id"`
// ClusterID: cluster ID of the node.
ClusterID string `json:"cluster_id"`
// ProviderID: underlying instance ID. It is prefixed by instance type and location information (see https://pkg.go.dev/k8s.io/api/core/v1#NodeSpec.ProviderID).
ProviderID string `json:"provider_id"`
// Region: cluster region of the node.
Region scw.Region `json:"region"`
// Name: name of the node.
Name string `json:"name"`
// Deprecated: PublicIPV4: public IPv4 address of the node.
PublicIPV4 *net.IP `json:"public_ip_v4,omitempty"`
// Deprecated: PublicIPV6: public IPv6 address of the node.
PublicIPV6 *net.IP `json:"public_ip_v6,omitempty"`
// Deprecated: Conditions: conditions of the node. These conditions contain the Node Problem Detector conditions, as well as some in house conditions.
Conditions *map[string]string `json:"conditions,omitempty"`
// Status: status of the node.
// Default value: unknown
Status NodeStatus `json:"status"`
// ErrorMessage: details of the error, if any occurred when managing the node.
ErrorMessage *string `json:"error_message"`
// CreatedAt: date on which the node was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the node was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// NodeMetadataCoreV1Taint: node metadata core v1 taint.
type NodeMetadataCoreV1Taint struct {
Key string `json:"key"`
Value string `json:"value"`
Effect string `json:"effect"`
}
// UpdateClusterRequestAutoUpgrade: update cluster request auto upgrade.
type UpdateClusterRequestAutoUpgrade struct {
// Enable: defines whether auto upgrade is enabled for the cluster.
Enable *bool `json:"enable"`
// MaintenanceWindow: maintenance window of the cluster auto upgrades.
MaintenanceWindow *MaintenanceWindow `json:"maintenance_window"`
}
// UpdateClusterRequestAutoscalerConfig: update cluster request autoscaler config.
type UpdateClusterRequestAutoscalerConfig struct {
// ScaleDownDisabled: disable the cluster autoscaler.
ScaleDownDisabled *bool `json:"scale_down_disabled"`
// ScaleDownDelayAfterAdd: how long after scale up the scale down evaluation resumes.
ScaleDownDelayAfterAdd *string `json:"scale_down_delay_after_add"`
// Estimator: type of resource estimator to be used in scale up.
// Default value: unknown_estimator
Estimator AutoscalerEstimator `json:"estimator"`
// Expander: type of node group expander to be used in scale up.
// Default value: unknown_expander
Expander AutoscalerExpander `json:"expander"`
// IgnoreDaemonsetsUtilization: ignore DaemonSet pods when calculating resource utilization for scaling down.
IgnoreDaemonsetsUtilization *bool `json:"ignore_daemonsets_utilization"`
// BalanceSimilarNodeGroups: detect similar node groups and balance the number of nodes between them.
BalanceSimilarNodeGroups *bool `json:"balance_similar_node_groups"`
// ExpendablePodsPriorityCutoff: pods with priority below cutoff will be expendable. They can be killed without any consideration during scale down and they won't cause scale up. Pods with null priority (PodPriority disabled) are non expendable.
ExpendablePodsPriorityCutoff *int32 `json:"expendable_pods_priority_cutoff"`
// ScaleDownUnneededTime: how long a node should be unneeded before it is eligible to be scaled down.
ScaleDownUnneededTime *string `json:"scale_down_unneeded_time"`
// ScaleDownUtilizationThreshold: node utilization level, defined as a sum of requested resources divided by capacity, below which a node can be considered for scale down.
ScaleDownUtilizationThreshold *float32 `json:"scale_down_utilization_threshold"`
// MaxGracefulTerminationSec: maximum number of seconds the cluster autoscaler waits for pod termination when trying to scale down a node.
MaxGracefulTerminationSec *uint32 `json:"max_graceful_termination_sec"`
}
// UpdateClusterRequestOpenIDConnectConfig: update cluster request open id connect config.
type UpdateClusterRequestOpenIDConnectConfig struct {
// IssuerURL: URL of the provider which allows the API server to discover public signing keys. Only URLs using the `https://` scheme are accepted. This is typically the provider's discovery URL without a path, for example "https://accounts.google.com" or "https://login.salesforce.com".
IssuerURL *string `json:"issuer_url"`
// ClientID: a client ID that all tokens must be issued for.
ClientID *string `json:"client_id"`
// UsernameClaim: jWT claim to use as the user name. The default is `sub`, which is expected to be the end user's unique identifier. Admins can choose other claims, such as `email` or `name`, depending on their provider. However, claims other than `email` will be prefixed with the issuer URL to prevent name collision.
UsernameClaim *string `json:"username_claim"`
// UsernamePrefix: prefix prepended to username claims to prevent name collision (such as `system:` users). For example, the value `oidc:` will create usernames like `oidc:jane.doe`. If this flag is not provided and `username_claim` is a value other than `email`, the prefix defaults to `( Issuer URL )#` where `( Issuer URL )` is the value of `issuer_url`. The value `-` can be used to disable all prefixing.
UsernamePrefix *string `json:"username_prefix"`
// GroupsClaim: jWT claim to use as the user's group.
GroupsClaim *[]string `json:"groups_claim"`
// GroupsPrefix: prefix prepended to group claims to prevent name collision (such as `system:` groups). For example, the value `oidc:` will create group names like `oidc:engineering` and `oidc:infra`.
GroupsPrefix *string `json:"groups_prefix"`
// RequiredClaim: multiple key=value pairs describing a required claim in the ID token. If set, the claims are verified to be present in the ID token with a matching value.
RequiredClaim *[]string `json:"required_claim"`
}
// UpdatePoolRequestUpgradePolicy: update pool request upgrade policy.
type UpdatePoolRequestUpgradePolicy struct {
MaxUnavailable *uint32 `json:"max_unavailable"`
MaxSurge *uint32 `json:"max_surge"`
}
// AddClusterACLRulesRequest: add cluster acl rules request.
type AddClusterACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster whose ACLs will be added.
ClusterID string `json:"-"`
// ACLs: aCLs to add.
ACLs []*ACLRuleRequest `json:"acls"`
}
// AddClusterACLRulesResponse: add cluster acl rules response.
type AddClusterACLRulesResponse struct {
// Rules: aCLs that were added.
Rules []*ACLRule `json:"rules"`
}
// AuthExternalNodeRequest: auth external node request.
type AuthExternalNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PoolID: pool the node will be attached to.
PoolID string `json:"-"`
}
// CreateClusterRequest: create cluster request.
type CreateClusterRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Deprecated: OrganizationID: organization ID in which the cluster will be created.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID in which the cluster will be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Type: type of the cluster. See [list available cluster types](#list-available-cluster-types-for-a-cluster) for a list of valid types.
Type string `json:"type"`
// Name: cluster name.
Name string `json:"name"`
// Description: cluster description.
Description string `json:"description"`
// Tags: tags associated with the cluster.
Tags []string `json:"tags"`
// Version: kubernetes version of the cluster.
Version string `json:"version"`
// Cni: container Network Interface (CNI) plugin running in the cluster.
// Default value: unknown_cni
Cni CNI `json:"cni"`
// Pools: pools created along with the cluster.
Pools []*CreateClusterRequestPoolConfig `json:"pools"`
// AutoscalerConfig: autoscaler configuration for the cluster. It allows you to set (to an extent) your preferred autoscaler configuration, which is an implementation of the cluster-autoscaler (https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler/).
AutoscalerConfig *CreateClusterRequestAutoscalerConfig `json:"autoscaler_config,omitempty"`
// AutoUpgrade: auto upgrade configuration of the cluster. This configuration enables to set a specific 2-hour time window in which the cluster can be automatically updated to the latest patch version.
AutoUpgrade *CreateClusterRequestAutoUpgrade `json:"auto_upgrade,omitempty"`
// FeatureGates: list of feature gates to enable.
FeatureGates []string `json:"feature_gates"`
// AdmissionPlugins: list of admission plugins to enable.
AdmissionPlugins []string `json:"admission_plugins"`
// OpenIDConnectConfig: openID Connect configuration of the cluster. This configuration enables to update the OpenID Connect configuration of the Kubernetes API server.
OpenIDConnectConfig *CreateClusterRequestOpenIDConnectConfig `json:"open_id_connect_config,omitempty"`
// ApiserverCertSans: additional Subject Alternative Names for the Kubernetes API server certificate.
ApiserverCertSans []string `json:"apiserver_cert_sans"`
// PrivateNetworkID: private network ID for internal cluster communication (cannot be changed later).
PrivateNetworkID *string `json:"private_network_id,omitempty"`
}
// CreateExternalNodeRequest: create external node request.
type CreateExternalNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
PoolID string `json:"-"`
}
// CreatePoolRequest: create pool request.
type CreatePoolRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID to which the pool will be attached.
ClusterID string `json:"-"`
// Name: pool name.
Name string `json:"name"`
// NodeType: node type is the type of Scaleway Instance wanted for the pool. Nodes with insufficient memory are not eligible (DEV1-S, PLAY2-PICO, STARDUST). 'external' is a special node type used to provision instances from other cloud providers in a Kosmos Cluster.
NodeType string `json:"node_type"`
// PlacementGroupID: placement group ID in which all the nodes of the pool will be created, placement groups are limited to 20 instances.
PlacementGroupID *string `json:"placement_group_id,omitempty"`
// Autoscaling: defines whether the autoscaling feature is enabled for the pool.
Autoscaling bool `json:"autoscaling"`
// Size: size (number of nodes) of the pool.
Size uint32 `json:"size"`
// MinSize: defines the minimum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MinSize *uint32 `json:"min_size,omitempty"`
// MaxSize: defines the maximum size of the pool. Note that this field is only used when autoscaling is enabled on the pool.
MaxSize *uint32 `json:"max_size,omitempty"`
// ContainerRuntime: customization of the container runtime is available for each pool.
// Default value: unknown_runtime
ContainerRuntime Runtime `json:"container_runtime"`
// Autohealing: defines whether the autohealing feature is enabled for the pool.
Autohealing bool `json:"autohealing"`
// Tags: tags associated with the pool, see [managing tags](https://www.scaleway.com/en/docs/containers/kubernetes/api-cli/managing-tags).
Tags []string `json:"tags"`
// KubeletArgs: kubelet arguments to be used by this pool. Note that this feature is experimental.
KubeletArgs map[string]string `json:"kubelet_args"`
// UpgradePolicy: pool upgrade policy.
UpgradePolicy *CreatePoolRequestUpgradePolicy `json:"upgrade_policy,omitempty"`
// Zone: zone in which the pool's nodes will be spawned.
Zone scw.Zone `json:"zone"`
// RootVolumeType: * `l_ssd` is a local block storage which means your system is stored locally on your node's hypervisor. This type is not available for all node types
// * `sbs-5k` is a remote block storage which means your system is stored on a centralized and resilient cluster with 5k IOPS limits
// * `sbs-15k` is a faster remote block storage which means your system is stored on a centralized and resilient cluster with 15k IOPS limits
// * `b_ssd` is the legacy remote block storage which means your system is stored on a centralized and resilient cluster. Consider using `sbs-5k` or `sbs-15k` instead.
// Default value: default_volume_type
RootVolumeType PoolVolumeType `json:"root_volume_type"`
// RootVolumeSize: system volume disk size.
RootVolumeSize *scw.Size `json:"root_volume_size,omitempty"`
// PublicIPDisabled: defines if the public IP should be removed from Nodes. To use this feature, your Cluster must have an attached Private Network set up with a Public Gateway.
PublicIPDisabled bool `json:"public_ip_disabled"`
}
// DeleteACLRuleRequest: delete acl rule request.
type DeleteACLRuleRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ACLID: ID of the ACL rule to delete.
ACLID string `json:"-"`
}
// DeleteClusterRequest: delete cluster request.
type DeleteClusterRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster to delete.
ClusterID string `json:"-"`
// WithAdditionalResources: defines whether all volumes (including retain volume type), empty Private Networks and Load Balancers with a name starting with the cluster ID will also be deleted.
WithAdditionalResources bool `json:"with_additional_resources"`
}
// DeleteNodeRequest: delete node request.
type DeleteNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NodeID: ID of the node to replace.
NodeID string `json:"-"`
// SkipDrain: skip draining node from its workload (Note: this parameter is currently inactive).
SkipDrain bool `json:"-"`
// Replace: add a new node after the deletion of this node.
Replace bool `json:"-"`
}
// DeletePoolRequest: delete pool request.
type DeletePoolRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PoolID: ID of the pool to delete.
PoolID string `json:"-"`
}
// ExternalNode: external node.
type ExternalNode struct {
ID string `json:"id"`
Name string `json:"name"`
ClusterURL string `json:"cluster_url"`
PoolVersion string `json:"pool_version"`
ClusterCa string `json:"cluster_ca"`
KubeToken string `json:"kube_token"`
KubeletConfig string `json:"kubelet_config"`
ExternalIP string `json:"external_ip"`
ContainerdVersion string `json:"containerd_version"`
RuncVersion string `json:"runc_version"`
CniPluginsVersion string `json:"cni_plugins_version"`
NodeLabels map[string]string `json:"node_labels"`
NodeTaints []*ExternalNodeCoreV1Taint `json:"node_taints"`
}
// ExternalNodeAuth: external node auth.
type ExternalNodeAuth struct {
NodeSecretKey string `json:"node_secret_key"`
MetadataURL string `json:"metadata_url"`
}
// GetClusterKubeConfigRequest: get cluster kube config request.
type GetClusterKubeConfigRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID for which to download the kubeconfig.
ClusterID string `json:"-"`
// Redacted: hide the legacy token from the kubeconfig.
Redacted *bool `json:"redacted,omitempty"`
}
// GetClusterRequest: get cluster request.
type GetClusterRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the requested cluster.
ClusterID string `json:"-"`
}
// GetNodeMetadataRequest: get node metadata request.
type GetNodeMetadataRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// GetNodeRequest: get node request.
type GetNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NodeID: ID of the requested node.
NodeID string `json:"-"`
}
// GetPoolRequest: get pool request.
type GetPoolRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PoolID: ID of the requested pool.
PoolID string `json:"-"`
}
// GetVersionRequest: get version request.
type GetVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// VersionName: requested version name.
VersionName string `json:"-"`
}
// ListClusterACLRulesRequest: list cluster acl rules request.
type ListClusterACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster whose ACLs will be listed.
ClusterID string `json:"-"`
// Page: page number for the returned ACLs.
Page *int32 `json:"-"`
// PageSize: maximum number of ACLs per page.
PageSize *uint32 `json:"-"`
}
// ListClusterACLRulesResponse: list cluster acl rules response.
type ListClusterACLRulesResponse struct {
// TotalCount: total number of ACLs that exist for the cluster.
TotalCount uint64 `json:"total_count"`
// Rules: paginated returned ACLs.
Rules []*ACLRule `json:"rules"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClusterACLRulesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClusterACLRulesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListClusterACLRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint64(len(results.Rules))
return uint64(len(results.Rules)), nil
}
// ListClusterAvailableTypesRequest: list cluster available types request.
type ListClusterAvailableTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID for which the available Kubernetes types will be listed.
ClusterID string `json:"-"`
}
// ListClusterAvailableTypesResponse: list cluster available types response.
type ListClusterAvailableTypesResponse struct {
// ClusterTypes: available cluster types for the cluster.
ClusterTypes []*ClusterType `json:"cluster_types"`
// TotalCount: total number of types.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClusterAvailableTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClusterAvailableTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListClusterAvailableTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ClusterTypes = append(r.ClusterTypes, results.ClusterTypes...)
r.TotalCount += uint64(len(results.ClusterTypes))
return uint64(len(results.ClusterTypes)), nil
}
// ListClusterAvailableVersionsRequest: list cluster available versions request.
type ListClusterAvailableVersionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID for which the available Kubernetes versions will be listed.
ClusterID string `json:"-"`
}
// ListClusterAvailableVersionsResponse: list cluster available versions response.
type ListClusterAvailableVersionsResponse struct {
// Versions: available Kubernetes versions for the cluster.
Versions []*Version `json:"versions"`
}
// ListClusterTypesRequest: list cluster types request.
type ListClusterTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number, from the paginated results, to return for cluster-types.
Page *int32 `json:"-"`
// PageSize: maximum number of clusters per page.
PageSize *uint32 `json:"-"`
}
// ListClusterTypesResponse: list cluster types response.
type ListClusterTypesResponse struct {
// TotalCount: total number of cluster-types.
TotalCount uint64 `json:"total_count"`
// ClusterTypes: paginated returned cluster-types.
ClusterTypes []*ClusterType `json:"cluster_types"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClusterTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClusterTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListClusterTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ClusterTypes = append(r.ClusterTypes, results.ClusterTypes...)
r.TotalCount += uint64(len(results.ClusterTypes))
return uint64(len(results.ClusterTypes)), nil
}
// ListClustersRequest: list clusters request.
type ListClustersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrganizationID: organization ID on which to filter the returned clusters.
OrganizationID *string `json:"-"`
// ProjectID: project ID on which to filter the returned clusters.
ProjectID *string `json:"-"`
// OrderBy: sort order of returned clusters.
// Default value: created_at_asc
OrderBy ListClustersRequestOrderBy `json:"-"`
// Page: page number to return for clusters, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of clusters per page.
PageSize *uint32 `json:"-"`
// Name: name to filter on, only clusters containing this substring in their name will be returned.
Name *string `json:"-"`
// Status: status to filter on, only clusters with this status will be returned.
// Default value: unknown
Status ClusterStatus `json:"-"`
// Type: type to filter on, only clusters with this type will be returned.
Type *string `json:"-"`
// PrivateNetworkID: private Network ID to filter on, only clusters within this Private Network will be returned.
PrivateNetworkID *string `json:"-"`
}
// ListClustersResponse: list clusters response.
type ListClustersResponse struct {
// TotalCount: total number of clusters.
TotalCount uint64 `json:"total_count"`
// Clusters: paginated returned clusters.
Clusters []*Cluster `json:"clusters"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClustersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClustersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListClustersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Clusters = append(r.Clusters, results.Clusters...)
r.TotalCount += uint64(len(results.Clusters))
return uint64(len(results.Clusters)), nil
}
// ListNodesRequest: list nodes request.
type ListNodesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID from which the nodes will be listed from.
ClusterID string `json:"-"`
// PoolID: pool ID on which to filter the returned nodes.
PoolID *string `json:"-"`
// OrderBy: sort order of the returned nodes.
// Default value: created_at_asc
OrderBy ListNodesRequestOrderBy `json:"-"`
// Page: page number for the returned nodes.
Page *int32 `json:"-"`
// PageSize: maximum number of nodes per page.
PageSize *uint32 `json:"-"`
// Name: name to filter on, only nodes containing this substring in their name will be returned.
Name *string `json:"-"`
// Status: status to filter on, only nodes with this status will be returned.
// Default value: unknown
Status NodeStatus `json:"-"`
}
// ListNodesResponse: list nodes response.
type ListNodesResponse struct {
// TotalCount: total number of nodes.
TotalCount uint64 `json:"total_count"`
// Nodes: paginated returned nodes.
Nodes []*Node `json:"nodes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListNodesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Nodes = append(r.Nodes, results.Nodes...)
r.TotalCount += uint64(len(results.Nodes))
return uint64(len(results.Nodes)), nil
}
// ListPoolsRequest: list pools request.
type ListPoolsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster whose pools will be listed.
ClusterID string `json:"-"`
// OrderBy: sort order of returned pools.
// Default value: created_at_asc
OrderBy ListPoolsRequestOrderBy `json:"-"`
// Page: page number for the returned pools.
Page *int32 `json:"-"`
// PageSize: maximum number of pools per page.
PageSize *uint32 `json:"-"`
// Name: name to filter on, only pools containing this substring in their name will be returned.
Name *string `json:"-"`
// Status: status to filter on, only pools with this status will be returned.
// Default value: unknown
Status PoolStatus `json:"-"`
}
// ListPoolsResponse: list pools response.
type ListPoolsResponse struct {
// TotalCount: total number of pools that exists for the cluster.
TotalCount uint64 `json:"total_count"`
// Pools: paginated returned pools.
Pools []*Pool `json:"pools"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPoolsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPoolsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPoolsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Pools = append(r.Pools, results.Pools...)
r.TotalCount += uint64(len(results.Pools))
return uint64(len(results.Pools)), nil
}
// ListVersionsRequest: list versions request.
type ListVersionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
}
// ListVersionsResponse: list versions response.
type ListVersionsResponse struct {
// Versions: available Kubernetes versions.
Versions []*Version `json:"versions"`
}
// MigrateClusterToSBSCSIRequest: migrate cluster to sbscsi request.
type MigrateClusterToSBSCSIRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID for which the latest CSI compatible with Scaleway Block Storage will be enabled.
ClusterID string `json:"-"`
}
// NodeMetadata: node metadata.
type NodeMetadata struct {
ID string `json:"id"`
Name string `json:"name"`
ClusterURL string `json:"cluster_url"`
ClusterCa string `json:"cluster_ca"`
CredentialProviderConfig string `json:"credential_provider_config"`
PoolVersion string `json:"pool_version"`
KubeletConfig string `json:"kubelet_config"`
NodeLabels map[string]string `json:"node_labels"`
NodeTaints []*NodeMetadataCoreV1Taint `json:"node_taints"`
HasGpu bool `json:"has_gpu"`
ExternalIP string `json:"external_ip"`
RepoURI string `json:"repo_uri"`
}
// RebootNodeRequest: reboot node request.
type RebootNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NodeID: ID of the node to reboot.
NodeID string `json:"-"`
}
// ReplaceNodeRequest: replace node request.
type ReplaceNodeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NodeID: ID of the node to replace.
NodeID string `json:"-"`
}
// ResetClusterAdminTokenRequest: reset cluster admin token request.
type ResetClusterAdminTokenRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: cluster ID on which the admin token will be renewed.
ClusterID string `json:"-"`
}
// SetClusterACLRulesRequest: set cluster acl rules request.
type SetClusterACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster whose ACLs will be set.
ClusterID string `json:"-"`
// ACLs: aCLs to set.
ACLs []*ACLRuleRequest `json:"acls"`
}
// SetClusterACLRulesResponse: set cluster acl rules response.
type SetClusterACLRulesResponse struct {
// Rules: aCLs that were set.
Rules []*ACLRule `json:"rules"`
}
// SetClusterTypeRequest: set cluster type request.
type SetClusterTypeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster to migrate from one type to another.
ClusterID string `json:"-"`
// Type: type of the cluster. Note that some migrations are not possible (please refer to product documentation).
Type string `json:"type"`
}
// UpdateClusterRequest: update cluster request.
type UpdateClusterRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster to update.
ClusterID string `json:"-"`
// Name: new external name for the cluster.
Name *string `json:"name,omitempty"`
// Description: new description for the cluster.
Description *string `json:"description,omitempty"`
// Tags: new tags associated with the cluster.
Tags *[]string `json:"tags,omitempty"`
// AutoscalerConfig: new autoscaler config for the cluster.
AutoscalerConfig *UpdateClusterRequestAutoscalerConfig `json:"autoscaler_config,omitempty"`
// AutoUpgrade: new auto upgrade configuration for the cluster. Note that all fields needs to be set.
AutoUpgrade *UpdateClusterRequestAutoUpgrade `json:"auto_upgrade,omitempty"`
// FeatureGates: list of feature gates to enable.
FeatureGates *[]string `json:"feature_gates,omitempty"`
// AdmissionPlugins: list of admission plugins to enable.
AdmissionPlugins *[]string `json:"admission_plugins,omitempty"`
// OpenIDConnectConfig: openID Connect configuration of the cluster. This configuration enables to update the OpenID Connect configuration of the Kubernetes API server.
OpenIDConnectConfig *UpdateClusterRequestOpenIDConnectConfig `json:"open_id_connect_config,omitempty"`
// ApiserverCertSans: additional Subject Alternative Names for the Kubernetes API server certificate.
ApiserverCertSans *[]string `json:"apiserver_cert_sans,omitempty"`
}
// UpdatePoolRequest: update pool request.
type UpdatePoolRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PoolID: ID of the pool to update.
PoolID string `json:"-"`
// Autoscaling: new value for the pool autoscaling enablement.
Autoscaling *bool `json:"autoscaling,omitempty"`
// Size: new desired pool size.
Size *uint32 `json:"size,omitempty"`
// MinSize: new minimum size for the pool.
MinSize *uint32 `json:"min_size,omitempty"`
// MaxSize: new maximum size for the pool.
MaxSize *uint32 `json:"max_size,omitempty"`
// Autohealing: new value for the pool autohealing enablement.
Autohealing *bool `json:"autohealing,omitempty"`
// Tags: new tags associated with the pool.
Tags *[]string `json:"tags,omitempty"`
// KubeletArgs: new Kubelet arguments to be used by this pool. Note that this feature is experimental.
KubeletArgs *map[string]string `json:"kubelet_args,omitempty"`
// UpgradePolicy: new upgrade policy for the pool.
UpgradePolicy *UpdatePoolRequestUpgradePolicy `json:"upgrade_policy,omitempty"`
}
// UpgradeClusterRequest: upgrade cluster request.
type UpgradeClusterRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ClusterID: ID of the cluster to upgrade.
ClusterID string `json:"-"`
// Version: new Kubernetes version of the cluster. Note that the version should either be a higher patch version of the same minor version or the direct minor version after the current one.
Version string `json:"version"`
// UpgradePools: defines whether pools will also be upgraded once the control plane is upgraded.
UpgradePools bool `json:"upgrade_pools"`
}
// UpgradePoolRequest: upgrade pool request.
type UpgradePoolRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PoolID: ID of the pool to upgrade.
PoolID string `json:"-"`
// Version: new Kubernetes version for the pool.
Version string `json:"version"`
}
// This API allows you to manage Kubernetes Kapsule and Kosmos clusters.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListClusters: List all existing Kubernetes clusters in a specific region.
func (s *API) ListClusters(req *ListClustersRequest, opts ...scw.RequestOption) (*ListClustersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters",
Query: query,
}
var resp ListClustersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateCluster: Create a new Kubernetes cluster in a Scaleway region.
func (s *API) CreateCluster(req *CreateClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("k8s")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCluster: Retrieve information about a specific Kubernetes cluster.
func (s *API) GetCluster(req *GetClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCluster: Update information on a specific Kubernetes cluster. You can update details such as its name, description, tags and configuration. To upgrade a cluster, you will need to use the dedicated endpoint.
func (s *API) UpdateCluster(req *UpdateClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCluster: Delete a specific Kubernetes cluster and all its associated pools and nodes, and possibly its associated Load Balancers or Block Volumes.
func (s *API) DeleteCluster(req *DeleteClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "with_additional_resources", req.WithAdditionalResources)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
Query: query,
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradeCluster: Upgrade a specific Kubernetes cluster and possibly its associated pools to a specific and supported Kubernetes version.
func (s *API) UpgradeCluster(req *UpgradeClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetClusterType: Change the type of a specific Kubernetes cluster. To see the possible values you can enter for the `type` field, [list available cluster types](#list-available-cluster-types-for-a-cluster).
func (s *API) SetClusterType(req *SetClusterTypeRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/set-type",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusterAvailableVersions: List the versions that a specific Kubernetes cluster is allowed to upgrade to. Results will include every patch version greater than the current patch, as well as one minor version ahead of the current version. Any upgrade skipping a minor version will not work.
func (s *API) ListClusterAvailableVersions(req *ListClusterAvailableVersionsRequest, opts ...scw.RequestOption) (*ListClusterAvailableVersionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/available-versions",
}
var resp ListClusterAvailableVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusterAvailableTypes: List the cluster types that a specific Kubernetes cluster is allowed to switch to.
func (s *API) ListClusterAvailableTypes(req *ListClusterAvailableTypesRequest, opts ...scw.RequestOption) (*ListClusterAvailableTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/available-types",
}
var resp ListClusterAvailableTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// getClusterKubeConfig: Download the Kubernetes cluster config file (also known as `kubeconfig`) for a specific cluster to use it with `kubectl`.
// Tip: add `?dl=1` at the end of the URL to directly retrieve the base64 decoded kubeconfig. If you choose not to, the kubeconfig will be base64 encoded.
func (s *API) getClusterKubeConfig(req *GetClusterKubeConfigRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "redacted", req.Redacted)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/kubeconfig",
Query: query,
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ResetClusterAdminToken: Reset the admin token for a specific Kubernetes cluster. This will revoke the old admin token (which will not be usable afterwards) and create a new one. Note that you will need to download the kubeconfig again to keep interacting with the cluster.
func (s *API) ResetClusterAdminToken(req *ResetClusterAdminTokenRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/reset-admin-token",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// MigrateClusterToSBSCSI: Enable the latest CSI compatible with Scaleway Block Storage (SBS) and migrate all existing PersistentVolumes/VolumeSnapshotContents to SBS.
// Make sure to have the necessary Quota before running this command.
func (s *API) MigrateClusterToSBSCSI(req *MigrateClusterToSBSCSIRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/migrate-to-sbs-csi",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusterACLRules: List ACLs for a specific cluster.
func (s *API) ListClusterACLRules(req *ListClusterACLRulesRequest, opts ...scw.RequestOption) (*ListClusterACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/acls",
Query: query,
}
var resp ListClusterACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddClusterACLRules: Add new ACL rules for a specific cluster.
func (s *API) AddClusterACLRules(req *AddClusterACLRulesRequest, opts ...scw.RequestOption) (*AddClusterACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddClusterACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetClusterACLRules: Set new ACL rules for a specific cluster.
func (s *API) SetClusterACLRules(req *SetClusterACLRulesRequest, opts ...scw.RequestOption) (*SetClusterACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetClusterACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteACLRule: Delete an existing ACL.
func (s *API) DeleteACLRule(req *DeleteACLRuleRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPools: List all the existing pools for a specific Kubernetes cluster.
func (s *API) ListPools(req *ListPoolsRequest, opts ...scw.RequestOption) (*ListPoolsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "status", req.Status)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/pools",
Query: query,
}
var resp ListPoolsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePool: Create a new pool in a specific Kubernetes cluster.
func (s *API) CreatePool(req *CreatePoolRequest, opts ...scw.RequestOption) (*Pool, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("pool")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/pools",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Pool
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPool: Retrieve details about a specific pool in a Kubernetes cluster.
func (s *API) GetPool(req *GetPoolRequest, opts ...scw.RequestOption) (*Pool, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "",
}
var resp Pool
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradePool: Upgrade the Kubernetes version of a specific pool. Note that it only works if the targeted version matches the cluster's version.
// This will drain and replace the nodes in that pool.
func (s *API) UpgradePool(req *UpgradePoolRequest, opts ...scw.RequestOption) (*Pool, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Pool
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePool: Update the attributes of a specific pool, such as its desired size, autoscaling settings, and tags. To upgrade a pool, you will need to use the dedicated endpoint.
func (s *API) UpdatePool(req *UpdatePoolRequest, opts ...scw.RequestOption) (*Pool, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Pool
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePool: Delete a specific pool from a cluster. Note that all the pool's nodes will also be deleted.
func (s *API) DeletePool(req *DeletePoolRequest, opts ...scw.RequestOption) (*Pool, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "",
}
var resp Pool
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNodeMetadata: Rerieve metadata to instantiate a Kapsule/Kosmos node. This method is not intended to be called by end users but rather programmatically by the node-installer.
func (s *API) GetNodeMetadata(req *GetNodeMetadataRequest, opts ...scw.RequestOption) (*NodeMetadata, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/node-metadata",
}
var resp NodeMetadata
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AuthExternalNode: Creates a newer Kosmos node and returns its token. This method is not intended to be called by end users but rather programmatically by the node-installer.
func (s *API) AuthExternalNode(req *AuthExternalNodeRequest, opts ...scw.RequestOption) (*ExternalNodeAuth, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "/external-nodes/auth",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ExternalNodeAuth
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateExternalNode: Retrieve metadata for a Kosmos node. This method is not intended to be called by end users but rather programmatically by the kapsule-node-agent.
func (s *API) CreateExternalNode(req *CreateExternalNodeRequest, opts ...scw.RequestOption) (*ExternalNode, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PoolID) == "" {
return nil, errors.New("field PoolID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/pools/" + fmt.Sprint(req.PoolID) + "/external-nodes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ExternalNode
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNodes: List all the existing nodes for a specific Kubernetes cluster.
func (s *API) ListNodes(req *ListNodesRequest, opts ...scw.RequestOption) (*ListNodesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "pool_id", req.PoolID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "status", req.Status)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/nodes",
Query: query,
}
var resp ListNodesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNode: Retrieve details about a specific Kubernetes Node.
func (s *API) GetNode(req *GetNodeRequest, opts ...scw.RequestOption) (*Node, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NodeID) == "" {
return nil, errors.New("field NodeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/nodes/" + fmt.Sprint(req.NodeID) + "",
}
var resp Node
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: ReplaceNode: Replace a specific Node. The node will first be drained and pods will be rescheduled onto another node. Note that when there is not enough space to reschedule all the pods (such as in a one-node cluster, or with specific constraints), disruption of your applications may occur.
func (s *API) ReplaceNode(req *ReplaceNodeRequest, opts ...scw.RequestOption) (*Node, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NodeID) == "" {
return nil, errors.New("field NodeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/nodes/" + fmt.Sprint(req.NodeID) + "/replace",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Node
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RebootNode: Reboot a specific Node. The node will first be drained and pods will be rescheduled onto another node. Note that when there is not enough space to reschedule all the pods (such as in a one-node cluster, or with specific constraints), disruption of your applications may occur.
func (s *API) RebootNode(req *RebootNodeRequest, opts ...scw.RequestOption) (*Node, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NodeID) == "" {
return nil, errors.New("field NodeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/nodes/" + fmt.Sprint(req.NodeID) + "/reboot",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Node
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNode: Delete a specific Node. The node will first be drained and pods will be rescheduled onto another node. Note that when there is not enough space to reschedule all the pods (such as in a one-node cluster, or with specific constraints), disruption of your applications may occur.
func (s *API) DeleteNode(req *DeleteNodeRequest, opts ...scw.RequestOption) (*Node, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "skip_drain", req.SkipDrain)
parameter.AddToQuery(query, "replace", req.Replace)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NodeID) == "" {
return nil, errors.New("field NodeID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/nodes/" + fmt.Sprint(req.NodeID) + "",
Query: query,
}
var resp Node
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVersions: List all available versions for the creation of a new Kubernetes cluster.
func (s *API) ListVersions(req *ListVersionsRequest, opts ...scw.RequestOption) (*ListVersionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/versions",
}
var resp ListVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetVersion: Retrieve a specific Kubernetes version and its details.
func (s *API) GetVersion(req *GetVersionRequest, opts ...scw.RequestOption) (*Version, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.VersionName) == "" {
return nil, errors.New("field VersionName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/versions/" + fmt.Sprint(req.VersionName) + "",
}
var resp Version
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusterTypes: List available cluster types and their technical details.
func (s *API) ListClusterTypes(req *ListClusterTypesRequest, opts ...scw.RequestOption) (*ListClusterTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/k8s/v1/regions/" + fmt.Sprint(req.Region) + "/cluster-types",
Query: query,
}
var resp ListClusterTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/kubeconfig.go 0000664 0000000 0000000 00000007362 14747113137 0026523 0 ustar 00root root 0000000 0000000 package k8s
import (
"io"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/scw"
"gopkg.in/yaml.v2"
)
// Kubeconfig represents a kubernetes kubeconfig file
type Kubeconfig struct {
raw []byte
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
CurrentContext string `yaml:"current-context"`
Clusters []*KubeconfigClusterWithName `yaml:"clusters"`
Contexts []*KubeconfigContextWithName `yaml:"contexts"`
Users []*KubeconfigUserWithName `yaml:"users"`
}
// KubeconfigUserWithName represents a named cluster in the kubeconfig file
type KubeconfigClusterWithName struct {
Name string `yaml:"name"`
Cluster KubeconfigCluster `yaml:"cluster"`
}
// KubeconfigCluster represents a cluster in the kubeconfig file
type KubeconfigCluster struct {
Server string `yaml:"server,omitempty"`
CertificateAuthorityData string `yaml:"certificate-authority-data,omitempty"`
}
// KubeconfigContextWithName represents a named context in the kubeconfig file
type KubeconfigContextWithName struct {
Name string `yaml:"name"`
Context KubeconfigContext `yaml:"context"`
}
// KubeconfigContext represents a context in the kubeconfig file
type KubeconfigContext struct {
Cluster string `yaml:"cluster"`
Namespace string `yaml:"namespace,omitempty"`
User string `yaml:"user"`
}
// KubeconfigUserWithName represents a named user in the kubeconfig file
type KubeconfigUserWithName struct {
Name string `yaml:"name"`
User KubeconfigUser `yaml:"user"`
}
// KubeconfigUser represents a user in the kubeconfig file
type KubeconfigUser struct {
ClientCertificateData string `yaml:"client-certificate-data,omitempty"`
ClientKeyData string `yaml:"client-key-data,omitempty"`
Password string `yaml:"password,omitempty"`
Username string `yaml:"username,omitempty"`
Token string `yaml:"token,omitempty"`
}
// GetRaw returns the raw bytes of the kubeconfig
func (k *Kubeconfig) GetRaw() []byte {
return k.raw
}
// GetServer returns the server URL of the cluster in the kubeconfig
func (k *Kubeconfig) GetServer() (string, error) {
if len(k.Clusters) != 1 {
return "", errors.New("kubeconfig should have only one cluster")
}
return k.Clusters[0].Cluster.Server, nil
}
// GetCertificateAuthorityData returns the server certificate authority data of the cluster in the kubeconfig
func (k *Kubeconfig) GetCertificateAuthorityData() (string, error) {
if len(k.Clusters) != 1 {
return "", errors.New("kubeconfig should have only one cluster")
}
return k.Clusters[0].Cluster.CertificateAuthorityData, nil
}
// GetToken returns the token for the cluster in the kubeconfig
func (k *Kubeconfig) GetToken() (string, error) {
if len(k.Users) != 1 {
return "", errors.New("kubeconfig should have only one user")
}
return k.Users[0].User.Token, nil
}
// GetClusterKubeConfig downloads the kubeconfig for the given cluster
func (s *API) GetClusterKubeConfig(req *GetClusterKubeConfigRequest, opts ...scw.RequestOption) (*Kubeconfig, error) {
kubeconfigFile, err := s.getClusterKubeConfig(&GetClusterKubeConfigRequest{
Region: req.Region,
ClusterID: req.ClusterID,
}, opts...)
if err != nil {
return nil, errors.Wrap(err, "error getting cluster kubeconfig")
}
kubeconfigContent, err := io.ReadAll(kubeconfigFile.Content)
if err != nil {
return nil, errors.Wrap(err, "error reading kubeconfig content")
}
var kubeconfig Kubeconfig
err = yaml.Unmarshal(kubeconfigContent, &kubeconfig)
if err != nil {
return nil, errors.Wrap(err, "error unmarshaling kubeconfig")
}
kubeconfig.raw = kubeconfigContent
return &kubeconfig, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0025705 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/k8s/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000003050 14747113137 0030067 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/k8s/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepCluster(scwClient *scw.Client, region scw.Region) error {
k8sAPI := k8s.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the k8s cluster in (%s)", region)
listClusters, err := k8sAPI.ListClusters(&k8s.ListClustersRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing clusters in (%s) in sweeper: %s", region, err)
}
for _, cluster := range listClusters.Clusters {
// remove pools
listPools, err := k8sAPI.ListPools(&k8s.ListPoolsRequest{
Region: region,
ClusterID: cluster.ID,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing pool in (%s) in sweeper: %s", region, err)
}
for _, pool := range listPools.Pools {
_, err := k8sAPI.DeletePool(&k8s.DeletePoolRequest{
Region: region,
PoolID: pool.ID,
})
if err != nil {
return fmt.Errorf("error deleting pool in sweeper: %s", err)
}
}
_, err = k8sAPI.DeleteCluster(&k8s.DeleteClusterRequest{
Region: region,
ClusterID: cluster.ID,
WithAdditionalResources: true,
})
if err != nil {
return fmt.Errorf("error deleting cluster in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&k8s.API{}).Regions() {
err := SweepCluster(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/key_manager/ 0000775 0000000 0000000 00000000000 14747113137 0025277 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/key_manager/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0026714 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/key_manager/v1alpha1/key_manager_sdk.go 0000664 0000000 0000000 00000101013 14747113137 0032362 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package key_manager provides methods and message types of the key_manager v1alpha1 API.
package key_manager
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DataKeyAlgorithmSymmetricEncryption string
const (
DataKeyAlgorithmSymmetricEncryptionUnknownSymmetricEncryption = DataKeyAlgorithmSymmetricEncryption("unknown_symmetric_encryption")
// AES-GCM (256-bits) is the only data key algorithm currently supported by Key Manager.
DataKeyAlgorithmSymmetricEncryptionAes256Gcm = DataKeyAlgorithmSymmetricEncryption("aes_256_gcm")
)
func (enum DataKeyAlgorithmSymmetricEncryption) String() string {
if enum == "" {
// return default value if empty
return "unknown_symmetric_encryption"
}
return string(enum)
}
func (enum DataKeyAlgorithmSymmetricEncryption) Values() []DataKeyAlgorithmSymmetricEncryption {
return []DataKeyAlgorithmSymmetricEncryption{
"unknown_symmetric_encryption",
"aes_256_gcm",
}
}
func (enum DataKeyAlgorithmSymmetricEncryption) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DataKeyAlgorithmSymmetricEncryption) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DataKeyAlgorithmSymmetricEncryption(DataKeyAlgorithmSymmetricEncryption(tmp).String())
return nil
}
type KeyAlgorithmSymmetricEncryption string
const (
KeyAlgorithmSymmetricEncryptionUnknownSymmetricEncryption = KeyAlgorithmSymmetricEncryption("unknown_symmetric_encryption")
// AES-GCM (256-bits) is the only key algorithm currently supported by Key Manager.
KeyAlgorithmSymmetricEncryptionAes256Gcm = KeyAlgorithmSymmetricEncryption("aes_256_gcm")
)
func (enum KeyAlgorithmSymmetricEncryption) String() string {
if enum == "" {
// return default value if empty
return "unknown_symmetric_encryption"
}
return string(enum)
}
func (enum KeyAlgorithmSymmetricEncryption) Values() []KeyAlgorithmSymmetricEncryption {
return []KeyAlgorithmSymmetricEncryption{
"unknown_symmetric_encryption",
"aes_256_gcm",
}
}
func (enum KeyAlgorithmSymmetricEncryption) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *KeyAlgorithmSymmetricEncryption) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = KeyAlgorithmSymmetricEncryption(KeyAlgorithmSymmetricEncryption(tmp).String())
return nil
}
type KeyOrigin string
const (
KeyOriginUnknownOrigin = KeyOrigin("unknown_origin")
// Scaleway Key Manager generates the key material upon key creation.
KeyOriginScalewayKms = KeyOrigin("scaleway_kms")
// Scaleway Key Manager creates a key with key material coming from an external source.
KeyOriginExternal = KeyOrigin("external")
)
func (enum KeyOrigin) String() string {
if enum == "" {
// return default value if empty
return "unknown_origin"
}
return string(enum)
}
func (enum KeyOrigin) Values() []KeyOrigin {
return []KeyOrigin{
"unknown_origin",
"scaleway_kms",
"external",
}
}
func (enum KeyOrigin) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *KeyOrigin) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = KeyOrigin(KeyOrigin(tmp).String())
return nil
}
type KeyState string
const (
KeyStateUnknownState = KeyState("unknown_state")
// The key can be used for cryptographic operations.
KeyStateEnabled = KeyState("enabled")
// The key cannot be used for cryptographic operations.
KeyStateDisabled = KeyState("disabled")
// Key material must be imported before the key can be used for cryptographic operations.
KeyStatePendingKeyMaterial = KeyState("pending_key_material")
)
func (enum KeyState) String() string {
if enum == "" {
// return default value if empty
return "unknown_state"
}
return string(enum)
}
func (enum KeyState) Values() []KeyState {
return []KeyState{
"unknown_state",
"enabled",
"disabled",
"pending_key_material",
}
}
func (enum KeyState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *KeyState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = KeyState(KeyState(tmp).String())
return nil
}
type ListKeysRequestOrderBy string
const (
ListKeysRequestOrderByNameAsc = ListKeysRequestOrderBy("name_asc")
ListKeysRequestOrderByNameDesc = ListKeysRequestOrderBy("name_desc")
ListKeysRequestOrderByCreatedAtAsc = ListKeysRequestOrderBy("created_at_asc")
ListKeysRequestOrderByCreatedAtDesc = ListKeysRequestOrderBy("created_at_desc")
ListKeysRequestOrderByUpdatedAtAsc = ListKeysRequestOrderBy("updated_at_asc")
ListKeysRequestOrderByUpdatedAtDesc = ListKeysRequestOrderBy("updated_at_desc")
)
func (enum ListKeysRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListKeysRequestOrderBy) Values() []ListKeysRequestOrderBy {
return []ListKeysRequestOrderBy{
"name_asc",
"name_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListKeysRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListKeysRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListKeysRequestOrderBy(ListKeysRequestOrderBy(tmp).String())
return nil
}
// KeyRotationPolicy: key rotation policy.
type KeyRotationPolicy struct {
// RotationPeriod: duration between two key rotations. The minimum duration is 24 hours and the maximum duration is 876000 hours (1 year).
RotationPeriod *scw.Duration `json:"rotation_period"`
// NextRotationAt: date at which the key will be rotated next.
NextRotationAt *time.Time `json:"next_rotation_at"`
}
// KeyUsage: key usage.
type KeyUsage struct {
// SymmetricEncryption: see the `Key.Algorithm.SymmetricEncryption` enum for a description of values.
// Default value: unknown_symmetric_encryption
// Precisely one of SymmetricEncryption must be set.
SymmetricEncryption *KeyAlgorithmSymmetricEncryption `json:"symmetric_encryption,omitempty"`
}
// Key: key.
type Key struct {
// ID: ID of the key.
ID string `json:"id"`
// ProjectID: ID of the Project containing the key.
ProjectID string `json:"project_id"`
// Name: name of the key.
Name string `json:"name"`
// Usage: keys with a usage set to `symmetric_encryption` are used to encrypt and decrypt data. The only key algorithm currently supported by Key Manager is AES-256-GCM.
Usage *KeyUsage `json:"usage"`
// State: see the `Key.State` enum for a description of values.
// Default value: unknown_state
State KeyState `json:"state"`
// RotationCount: the rotation count tracks the amount of times that the key was rotated.
RotationCount uint32 `json:"rotation_count"`
// CreatedAt: key creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: key last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Protected: returns `true` if key protection is applied to the key.
Protected bool `json:"protected"`
// Locked: returns `true` if the key is locked.
Locked bool `json:"locked"`
// Description: description of the key.
Description *string `json:"description"`
// Tags: list of the key's tags.
Tags []string `json:"tags"`
// RotatedAt: key last rotation date.
RotatedAt *time.Time `json:"rotated_at"`
// RotationPolicy: key rotation policy.
RotationPolicy *KeyRotationPolicy `json:"rotation_policy"`
// Origin: refer to the `Key.Origin` enum for a description of values.
// Default value: unknown_origin
Origin KeyOrigin `json:"origin"`
// Region: region of the key.
Region scw.Region `json:"region"`
}
// CreateKeyRequest: create key request.
type CreateKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project containing the key.
ProjectID string `json:"project_id"`
// Name: (Optional) Name of the key.
Name *string `json:"name,omitempty"`
// Usage: see the `Key.Algorithm.SymmetricEncryption` enum for a description of values.
Usage *KeyUsage `json:"usage,omitempty"`
// Description: (Optional) Description of the key.
Description *string `json:"description,omitempty"`
// Tags: (Optional) List of the key's tags.
Tags []string `json:"tags"`
// RotationPolicy: if not specified, no rotation policy will be applied to the key.
RotationPolicy *KeyRotationPolicy `json:"rotation_policy,omitempty"`
// Unprotected: default value is `false`.
Unprotected bool `json:"unprotected"`
// Origin: refer to the `Key.Origin` enum for a description of values.
// Default value: unknown_origin
Origin KeyOrigin `json:"origin"`
}
// DataKey: data key.
type DataKey struct {
// KeyID: ID of the data encryption key.
KeyID string `json:"key_id"`
// Algorithm: symmetric encryption algorithm of the data encryption key.
// Default value: unknown_symmetric_encryption
Algorithm DataKeyAlgorithmSymmetricEncryption `json:"algorithm"`
// Ciphertext: your data encryption key's ciphertext can be stored safely. It can only be decrypted through the keys you create in Key Manager, using the relevant key ID.
Ciphertext []byte `json:"ciphertext"`
// Plaintext: (Optional) Your data encryption key's plaintext allows you to use the key immediately upon creation. It must neither be stored or shared.
Plaintext *[]byte `json:"plaintext"`
// CreatedAt: data encryption key creation date.
CreatedAt *time.Time `json:"created_at"`
}
// DecryptRequest: decrypt request.
type DecryptRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to decrypt.
KeyID string `json:"-"`
// Ciphertext: data size must be between 1 and 131071 bytes.
Ciphertext []byte `json:"ciphertext"`
// AssociatedData: the additional data must match the value passed in the encryption request.
AssociatedData *[]byte `json:"associated_data,omitempty"`
}
// DecryptResponse: decrypt response.
type DecryptResponse struct {
// KeyID: ID of the key used for decryption.
KeyID string `json:"key_id"`
// Plaintext: key's decrypted data.
Plaintext []byte `json:"plaintext"`
// Ciphertext: if the data was already encrypted with the latest key rotation, no output will be returned in the response object.
Ciphertext *[]byte `json:"ciphertext"`
}
// DeleteKeyMaterialRequest: delete key material request.
type DeleteKeyMaterialRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key of which to delete the key material.
KeyID string `json:"-"`
}
// DeleteKeyRequest: delete key request.
type DeleteKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to delete.
KeyID string `json:"-"`
}
// DisableKeyRequest: disable key request.
type DisableKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to disable.
KeyID string `json:"-"`
}
// EnableKeyRequest: enable key request.
type EnableKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to enable.
KeyID string `json:"-"`
}
// EncryptRequest: encrypt request.
type EncryptRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to encrypt.
KeyID string `json:"-"`
// Plaintext: data size must be between 1 and 65535 bytes.
Plaintext []byte `json:"plaintext"`
// AssociatedData: additional data which will not be encrypted, but authenticated and appended to the encrypted payload.
AssociatedData *[]byte `json:"associated_data,omitempty"`
}
// EncryptResponse: encrypt response.
type EncryptResponse struct {
// KeyID: ID of the key used for encryption.
KeyID string `json:"key_id"`
// Ciphertext: key's encrypted data.
Ciphertext []byte `json:"ciphertext"`
}
// GenerateDataKeyRequest: generate data key request.
type GenerateDataKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key.
KeyID string `json:"-"`
// Algorithm: see the `DataKey.Algorithm.SymmetricEncryption` enum for a description of values.
// Default value: unknown_symmetric_encryption
Algorithm DataKeyAlgorithmSymmetricEncryption `json:"algorithm"`
// WithoutPlaintext: default value is `false`, meaning that the plaintext is returned.
// Set it to `true` if you do not wish the plaintext to be returned in the response object.
WithoutPlaintext bool `json:"without_plaintext"`
}
// GetKeyRequest: get key request.
type GetKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to target.
KeyID string `json:"-"`
}
// ImportKeyMaterialRequest: import key material request.
type ImportKeyMaterialRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: the key's origin must be 'external'.
KeyID string `json:"-"`
// KeyMaterial: the key material The key material is a random sequence of bytes used to derive a cryptographic key.
KeyMaterial []byte `json:"key_material"`
// Salt: a salt can be used to improve the quality of randomness when the key material is generated from a low entropy source.
Salt *[]byte `json:"salt,omitempty"`
}
// ListKeysRequest: list keys request.
type ListKeysRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrganizationID: (Optional) Filter by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: (Optional) Filter by Project ID.
ProjectID *string `json:"-"`
// OrderBy: default value: name_asc
OrderBy ListKeysRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// Tags: (Optional) List of tags to filter on.
Tags []string `json:"-"`
// Name: (Optional) Filter by key name.
Name *string `json:"-"`
}
// ListKeysResponse: list keys response.
type ListKeysResponse struct {
// Keys: single page of keys matching the requested criteria.
Keys []*Key `json:"keys"`
// TotalCount: total count of keys matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListKeysResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListKeysResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListKeysResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Keys = append(r.Keys, results.Keys...)
r.TotalCount += uint64(len(results.Keys))
return uint64(len(results.Keys)), nil
}
// ProtectKeyRequest: protect key request.
type ProtectKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to apply key protection to.
KeyID string `json:"-"`
}
// RotateKeyRequest: rotate key request.
type RotateKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to rotate.
KeyID string `json:"-"`
}
// UnprotectKeyRequest: unprotect key request.
type UnprotectKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to remove key protection from.
KeyID string `json:"-"`
}
// UpdateKeyRequest: update key request.
type UpdateKeyRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// KeyID: ID of the key to update.
KeyID string `json:"-"`
// Name: (Optional) Updated name of the key.
Name *string `json:"name,omitempty"`
// Description: (Optional) Updated description of the key.
Description *string `json:"description,omitempty"`
// Tags: (Optional) Updated list of the key's tags.
Tags *[]string `json:"tags,omitempty"`
// RotationPolicy: if not specified, the key's existing rotation policy applies.
RotationPolicy *KeyRotationPolicy `json:"rotation_policy,omitempty"`
}
// This API allows you to create, manage and use cryptographic keys in a centralized and secure service.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateKey: Create a key in a given region specified by the `region` parameter. Keys only support symmetric encryption. You can use keys to encrypt or decrypt arbitrary payloads, or to generate data encryption keys that can be used without being stored in Key Manager.
func (s *API) CreateKey(req *CreateKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetKey: Retrieve the metadata of a key specified by the `region` and `key_id` parameters.
func (s *API) GetKey(req *GetKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "",
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateKey: Update a key's metadata (name, description and tags), specified by the `key_id` and `region` parameters.
func (s *API) UpdateKey(req *UpdateKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteKey: Delete an existing key specified by the `region` and `key_id` parameters. Deleting a key is permanent and cannot be undone. All data encrypted using this key, including data encryption keys, will become unusable.
func (s *API) DeleteKey(req *DeleteKeyRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RotateKey: Generate a new version of an existing key with randomly generated key material. Rotated keys can still be used to decrypt previously encrypted data. The key's new material will be used for subsequent encryption operations and data key generation.
func (s *API) RotateKey(req *RotateKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/rotate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ProtectKey: Apply key protection to a given key specified by the `key_id` parameter. Applying key protection means that your key can be used and modified, but it cannot be deleted.
func (s *API) ProtectKey(req *ProtectKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/protect",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnprotectKey: Remove key protection from a given key specified by the `key_id` parameter. Removing key protection means that your key can be deleted anytime.
func (s *API) UnprotectKey(req *UnprotectKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/unprotect",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableKey: Enable a given key to be used for cryptographic operations. Enabling a key allows you to make a disabled key usable again. You must specify the `region` and `key_id` parameters.
func (s *API) EnableKey(req *EnableKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableKey: Disable a given key to be used for cryptographic operations. Disabling a key renders it unusable. You must specify the `region` and `key_id` parameters.
func (s *API) DisableKey(req *DisableKeyRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListKeys: Retrieve the list of keys created within all Projects of an Organization or in a given Project. You must specify the `region`, and either the `organization_id` or the `project_id`.
func (s *API) ListKeys(req *ListKeysRequest, opts ...scw.RequestOption) (*ListKeysResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys",
Query: query,
}
var resp ListKeysResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GenerateDataKey: Generate a new data encryption key to use for cryptographic operations outside of Key Manager. Note that Key Manager does not store your data encryption key. The data encryption key is encrypted and must be decrypted using the key you have created in Key Manager. The data encryption key's plaintext is returned in the response object, for immediate usage.
//
// Always store the data encryption key's ciphertext, rather than its plaintext, which must not be stored. To retrieve your key's plaintext, call the Decrypt endpoint with your key's ID and ciphertext.
func (s *API) GenerateDataKey(req *GenerateDataKeyRequest, opts ...scw.RequestOption) (*DataKey, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/generate-data-key",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DataKey
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Encrypt: Encrypt data using an existing key, specified by the `key_id` parameter. Only keys with a usage set to **symmetric_encryption** are supported by this method. The maximum payload size that can be encrypted is 64KB of plaintext.
func (s *API) Encrypt(req *EncryptRequest, opts ...scw.RequestOption) (*EncryptResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/encrypt",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp EncryptResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Decrypt: Decrypt data using an existing key, specified by the `key_id` parameter. The maximum payload size that can be decrypted is the result of the encryption of 64KB of data (around 131KB).
func (s *API) Decrypt(req *DecryptRequest, opts ...scw.RequestOption) (*DecryptResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/decrypt",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DecryptResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ImportKeyMaterial: Import key material to use to derive a new cryptographic key. The key's origin must be `external`.
func (s *API) ImportKeyMaterial(req *ImportKeyMaterialRequest, opts ...scw.RequestOption) (*Key, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return nil, errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/import-key-material",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Key
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteKeyMaterial: Delete previously imported key material. This renders the associated cryptographic key unusable for any operation. The key's origin must be `external`.
func (s *API) DeleteKeyMaterial(req *DeleteKeyMaterialRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.KeyID) == "" {
return errors.New("field KeyID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/key-manager/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/keys/" + fmt.Sprint(req.KeyID) + "/delete-key-material",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/ 0000775 0000000 0000000 00000000000 14747113137 0023412 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/v1/ 0000775 0000000 0000000 00000000000 14747113137 0023740 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/v1/lb_sdk.go 0000664 0000000 0000000 00000766342 14747113137 0025547 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package lb provides methods and message types of the lb v1 API.
package lb
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ACLActionRedirectRedirectType string
const (
ACLActionRedirectRedirectTypeLocation = ACLActionRedirectRedirectType("location")
ACLActionRedirectRedirectTypeScheme = ACLActionRedirectRedirectType("scheme")
)
func (enum ACLActionRedirectRedirectType) String() string {
if enum == "" {
// return default value if empty
return "location"
}
return string(enum)
}
func (enum ACLActionRedirectRedirectType) Values() []ACLActionRedirectRedirectType {
return []ACLActionRedirectRedirectType{
"location",
"scheme",
}
}
func (enum ACLActionRedirectRedirectType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLActionRedirectRedirectType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLActionRedirectRedirectType(ACLActionRedirectRedirectType(tmp).String())
return nil
}
type ACLActionType string
const (
ACLActionTypeAllow = ACLActionType("allow")
ACLActionTypeDeny = ACLActionType("deny")
ACLActionTypeRedirect = ACLActionType("redirect")
)
func (enum ACLActionType) String() string {
if enum == "" {
// return default value if empty
return "allow"
}
return string(enum)
}
func (enum ACLActionType) Values() []ACLActionType {
return []ACLActionType{
"allow",
"deny",
"redirect",
}
}
func (enum ACLActionType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLActionType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLActionType(ACLActionType(tmp).String())
return nil
}
type ACLHTTPFilter string
const (
ACLHTTPFilterACLHTTPFilterNone = ACLHTTPFilter("acl_http_filter_none")
ACLHTTPFilterPathBegin = ACLHTTPFilter("path_begin")
ACLHTTPFilterPathEnd = ACLHTTPFilter("path_end")
ACLHTTPFilterRegex = ACLHTTPFilter("regex")
ACLHTTPFilterHTTPHeaderMatch = ACLHTTPFilter("http_header_match")
)
func (enum ACLHTTPFilter) String() string {
if enum == "" {
// return default value if empty
return "acl_http_filter_none"
}
return string(enum)
}
func (enum ACLHTTPFilter) Values() []ACLHTTPFilter {
return []ACLHTTPFilter{
"acl_http_filter_none",
"path_begin",
"path_end",
"regex",
"http_header_match",
}
}
func (enum ACLHTTPFilter) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLHTTPFilter) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLHTTPFilter(ACLHTTPFilter(tmp).String())
return nil
}
type BackendServerStatsHealthCheckStatus string
const (
BackendServerStatsHealthCheckStatusUnknown = BackendServerStatsHealthCheckStatus("unknown")
BackendServerStatsHealthCheckStatusNeutral = BackendServerStatsHealthCheckStatus("neutral")
BackendServerStatsHealthCheckStatusFailed = BackendServerStatsHealthCheckStatus("failed")
BackendServerStatsHealthCheckStatusPassed = BackendServerStatsHealthCheckStatus("passed")
BackendServerStatsHealthCheckStatusCondpass = BackendServerStatsHealthCheckStatus("condpass")
)
func (enum BackendServerStatsHealthCheckStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum BackendServerStatsHealthCheckStatus) Values() []BackendServerStatsHealthCheckStatus {
return []BackendServerStatsHealthCheckStatus{
"unknown",
"neutral",
"failed",
"passed",
"condpass",
}
}
func (enum BackendServerStatsHealthCheckStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BackendServerStatsHealthCheckStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BackendServerStatsHealthCheckStatus(BackendServerStatsHealthCheckStatus(tmp).String())
return nil
}
type BackendServerStatsServerState string
const (
BackendServerStatsServerStateStopped = BackendServerStatsServerState("stopped")
BackendServerStatsServerStateStarting = BackendServerStatsServerState("starting")
BackendServerStatsServerStateRunning = BackendServerStatsServerState("running")
BackendServerStatsServerStateStopping = BackendServerStatsServerState("stopping")
)
func (enum BackendServerStatsServerState) String() string {
if enum == "" {
// return default value if empty
return "stopped"
}
return string(enum)
}
func (enum BackendServerStatsServerState) Values() []BackendServerStatsServerState {
return []BackendServerStatsServerState{
"stopped",
"starting",
"running",
"stopping",
}
}
func (enum BackendServerStatsServerState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BackendServerStatsServerState) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BackendServerStatsServerState(BackendServerStatsServerState(tmp).String())
return nil
}
type CertificateStatus string
const (
CertificateStatusPending = CertificateStatus("pending")
CertificateStatusReady = CertificateStatus("ready")
CertificateStatusError = CertificateStatus("error")
)
func (enum CertificateStatus) String() string {
if enum == "" {
// return default value if empty
return "pending"
}
return string(enum)
}
func (enum CertificateStatus) Values() []CertificateStatus {
return []CertificateStatus{
"pending",
"ready",
"error",
}
}
func (enum CertificateStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *CertificateStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = CertificateStatus(CertificateStatus(tmp).String())
return nil
}
type CertificateType string
const (
CertificateTypeLetsencryt = CertificateType("letsencryt")
CertificateTypeCustom = CertificateType("custom")
)
func (enum CertificateType) String() string {
if enum == "" {
// return default value if empty
return "letsencryt"
}
return string(enum)
}
func (enum CertificateType) Values() []CertificateType {
return []CertificateType{
"letsencryt",
"custom",
}
}
func (enum CertificateType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *CertificateType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = CertificateType(CertificateType(tmp).String())
return nil
}
type ForwardPortAlgorithm string
const (
ForwardPortAlgorithmRoundrobin = ForwardPortAlgorithm("roundrobin")
ForwardPortAlgorithmLeastconn = ForwardPortAlgorithm("leastconn")
ForwardPortAlgorithmFirst = ForwardPortAlgorithm("first")
)
func (enum ForwardPortAlgorithm) String() string {
if enum == "" {
// return default value if empty
return "roundrobin"
}
return string(enum)
}
func (enum ForwardPortAlgorithm) Values() []ForwardPortAlgorithm {
return []ForwardPortAlgorithm{
"roundrobin",
"leastconn",
"first",
}
}
func (enum ForwardPortAlgorithm) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ForwardPortAlgorithm) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ForwardPortAlgorithm(ForwardPortAlgorithm(tmp).String())
return nil
}
type InstanceStatus string
const (
InstanceStatusUnknown = InstanceStatus("unknown")
InstanceStatusReady = InstanceStatus("ready")
InstanceStatusPending = InstanceStatus("pending")
InstanceStatusStopped = InstanceStatus("stopped")
InstanceStatusError = InstanceStatus("error")
InstanceStatusLocked = InstanceStatus("locked")
InstanceStatusMigrating = InstanceStatus("migrating")
)
func (enum InstanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum InstanceStatus) Values() []InstanceStatus {
return []InstanceStatus{
"unknown",
"ready",
"pending",
"stopped",
"error",
"locked",
"migrating",
}
}
func (enum InstanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceStatus(InstanceStatus(tmp).String())
return nil
}
type LBStatus string
const (
LBStatusUnknown = LBStatus("unknown")
LBStatusReady = LBStatus("ready")
LBStatusPending = LBStatus("pending")
LBStatusStopped = LBStatus("stopped")
LBStatusError = LBStatus("error")
LBStatusLocked = LBStatus("locked")
LBStatusMigrating = LBStatus("migrating")
LBStatusToCreate = LBStatus("to_create")
LBStatusCreating = LBStatus("creating")
LBStatusToDelete = LBStatus("to_delete")
LBStatusDeleting = LBStatus("deleting")
)
func (enum LBStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum LBStatus) Values() []LBStatus {
return []LBStatus{
"unknown",
"ready",
"pending",
"stopped",
"error",
"locked",
"migrating",
"to_create",
"creating",
"to_delete",
"deleting",
}
}
func (enum LBStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LBStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LBStatus(LBStatus(tmp).String())
return nil
}
type LBTypeStock string
const (
LBTypeStockUnknown = LBTypeStock("unknown")
LBTypeStockLowStock = LBTypeStock("low_stock")
LBTypeStockOutOfStock = LBTypeStock("out_of_stock")
LBTypeStockAvailable = LBTypeStock("available")
)
func (enum LBTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum LBTypeStock) Values() []LBTypeStock {
return []LBTypeStock{
"unknown",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum LBTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LBTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LBTypeStock(LBTypeStock(tmp).String())
return nil
}
type ListACLRequestOrderBy string
const (
ListACLRequestOrderByCreatedAtAsc = ListACLRequestOrderBy("created_at_asc")
ListACLRequestOrderByCreatedAtDesc = ListACLRequestOrderBy("created_at_desc")
ListACLRequestOrderByNameAsc = ListACLRequestOrderBy("name_asc")
ListACLRequestOrderByNameDesc = ListACLRequestOrderBy("name_desc")
)
func (enum ListACLRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListACLRequestOrderBy) Values() []ListACLRequestOrderBy {
return []ListACLRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListACLRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListACLRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListACLRequestOrderBy(ListACLRequestOrderBy(tmp).String())
return nil
}
type ListBackendsRequestOrderBy string
const (
ListBackendsRequestOrderByCreatedAtAsc = ListBackendsRequestOrderBy("created_at_asc")
ListBackendsRequestOrderByCreatedAtDesc = ListBackendsRequestOrderBy("created_at_desc")
ListBackendsRequestOrderByNameAsc = ListBackendsRequestOrderBy("name_asc")
ListBackendsRequestOrderByNameDesc = ListBackendsRequestOrderBy("name_desc")
)
func (enum ListBackendsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListBackendsRequestOrderBy) Values() []ListBackendsRequestOrderBy {
return []ListBackendsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListBackendsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListBackendsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListBackendsRequestOrderBy(ListBackendsRequestOrderBy(tmp).String())
return nil
}
type ListCertificatesRequestOrderBy string
const (
ListCertificatesRequestOrderByCreatedAtAsc = ListCertificatesRequestOrderBy("created_at_asc")
ListCertificatesRequestOrderByCreatedAtDesc = ListCertificatesRequestOrderBy("created_at_desc")
ListCertificatesRequestOrderByNameAsc = ListCertificatesRequestOrderBy("name_asc")
ListCertificatesRequestOrderByNameDesc = ListCertificatesRequestOrderBy("name_desc")
)
func (enum ListCertificatesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListCertificatesRequestOrderBy) Values() []ListCertificatesRequestOrderBy {
return []ListCertificatesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListCertificatesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListCertificatesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListCertificatesRequestOrderBy(ListCertificatesRequestOrderBy(tmp).String())
return nil
}
type ListFrontendsRequestOrderBy string
const (
ListFrontendsRequestOrderByCreatedAtAsc = ListFrontendsRequestOrderBy("created_at_asc")
ListFrontendsRequestOrderByCreatedAtDesc = ListFrontendsRequestOrderBy("created_at_desc")
ListFrontendsRequestOrderByNameAsc = ListFrontendsRequestOrderBy("name_asc")
ListFrontendsRequestOrderByNameDesc = ListFrontendsRequestOrderBy("name_desc")
)
func (enum ListFrontendsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListFrontendsRequestOrderBy) Values() []ListFrontendsRequestOrderBy {
return []ListFrontendsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListFrontendsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListFrontendsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListFrontendsRequestOrderBy(ListFrontendsRequestOrderBy(tmp).String())
return nil
}
type ListIPsRequestIPType string
const (
ListIPsRequestIPTypeAll = ListIPsRequestIPType("all")
ListIPsRequestIPTypeIPv4 = ListIPsRequestIPType("ipv4")
ListIPsRequestIPTypeIPv6 = ListIPsRequestIPType("ipv6")
)
func (enum ListIPsRequestIPType) String() string {
if enum == "" {
// return default value if empty
return "all"
}
return string(enum)
}
func (enum ListIPsRequestIPType) Values() []ListIPsRequestIPType {
return []ListIPsRequestIPType{
"all",
"ipv4",
"ipv6",
}
}
func (enum ListIPsRequestIPType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListIPsRequestIPType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListIPsRequestIPType(ListIPsRequestIPType(tmp).String())
return nil
}
type ListLBsRequestOrderBy string
const (
ListLBsRequestOrderByCreatedAtAsc = ListLBsRequestOrderBy("created_at_asc")
ListLBsRequestOrderByCreatedAtDesc = ListLBsRequestOrderBy("created_at_desc")
ListLBsRequestOrderByNameAsc = ListLBsRequestOrderBy("name_asc")
ListLBsRequestOrderByNameDesc = ListLBsRequestOrderBy("name_desc")
)
func (enum ListLBsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListLBsRequestOrderBy) Values() []ListLBsRequestOrderBy {
return []ListLBsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListLBsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListLBsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListLBsRequestOrderBy(ListLBsRequestOrderBy(tmp).String())
return nil
}
type ListPrivateNetworksRequestOrderBy string
const (
ListPrivateNetworksRequestOrderByCreatedAtAsc = ListPrivateNetworksRequestOrderBy("created_at_asc")
ListPrivateNetworksRequestOrderByCreatedAtDesc = ListPrivateNetworksRequestOrderBy("created_at_desc")
)
func (enum ListPrivateNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPrivateNetworksRequestOrderBy) Values() []ListPrivateNetworksRequestOrderBy {
return []ListPrivateNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListPrivateNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPrivateNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPrivateNetworksRequestOrderBy(ListPrivateNetworksRequestOrderBy(tmp).String())
return nil
}
type ListRoutesRequestOrderBy string
const (
ListRoutesRequestOrderByCreatedAtAsc = ListRoutesRequestOrderBy("created_at_asc")
ListRoutesRequestOrderByCreatedAtDesc = ListRoutesRequestOrderBy("created_at_desc")
)
func (enum ListRoutesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRoutesRequestOrderBy) Values() []ListRoutesRequestOrderBy {
return []ListRoutesRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListRoutesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRoutesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRoutesRequestOrderBy(ListRoutesRequestOrderBy(tmp).String())
return nil
}
type ListSubscriberRequestOrderBy string
const (
ListSubscriberRequestOrderByCreatedAtAsc = ListSubscriberRequestOrderBy("created_at_asc")
ListSubscriberRequestOrderByCreatedAtDesc = ListSubscriberRequestOrderBy("created_at_desc")
ListSubscriberRequestOrderByNameAsc = ListSubscriberRequestOrderBy("name_asc")
ListSubscriberRequestOrderByNameDesc = ListSubscriberRequestOrderBy("name_desc")
)
func (enum ListSubscriberRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSubscriberRequestOrderBy) Values() []ListSubscriberRequestOrderBy {
return []ListSubscriberRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListSubscriberRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSubscriberRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSubscriberRequestOrderBy(ListSubscriberRequestOrderBy(tmp).String())
return nil
}
type OnMarkedDownAction string
const (
OnMarkedDownActionOnMarkedDownActionNone = OnMarkedDownAction("on_marked_down_action_none")
OnMarkedDownActionShutdownSessions = OnMarkedDownAction("shutdown_sessions")
)
func (enum OnMarkedDownAction) String() string {
if enum == "" {
// return default value if empty
return "on_marked_down_action_none"
}
return string(enum)
}
func (enum OnMarkedDownAction) Values() []OnMarkedDownAction {
return []OnMarkedDownAction{
"on_marked_down_action_none",
"shutdown_sessions",
}
}
func (enum OnMarkedDownAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OnMarkedDownAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OnMarkedDownAction(OnMarkedDownAction(tmp).String())
return nil
}
type PrivateNetworkStatus string
const (
PrivateNetworkStatusUnknown = PrivateNetworkStatus("unknown")
PrivateNetworkStatusReady = PrivateNetworkStatus("ready")
PrivateNetworkStatusPending = PrivateNetworkStatus("pending")
PrivateNetworkStatusError = PrivateNetworkStatus("error")
)
func (enum PrivateNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum PrivateNetworkStatus) Values() []PrivateNetworkStatus {
return []PrivateNetworkStatus{
"unknown",
"ready",
"pending",
"error",
}
}
func (enum PrivateNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PrivateNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PrivateNetworkStatus(PrivateNetworkStatus(tmp).String())
return nil
}
type Protocol string
const (
ProtocolTCP = Protocol("tcp")
ProtocolHTTP = Protocol("http")
)
func (enum Protocol) String() string {
if enum == "" {
// return default value if empty
return "tcp"
}
return string(enum)
}
func (enum Protocol) Values() []Protocol {
return []Protocol{
"tcp",
"http",
}
}
func (enum Protocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Protocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Protocol(Protocol(tmp).String())
return nil
}
type ProxyProtocol string
const (
ProxyProtocolProxyProtocolUnknown = ProxyProtocol("proxy_protocol_unknown")
ProxyProtocolProxyProtocolNone = ProxyProtocol("proxy_protocol_none")
ProxyProtocolProxyProtocolV1 = ProxyProtocol("proxy_protocol_v1")
ProxyProtocolProxyProtocolV2 = ProxyProtocol("proxy_protocol_v2")
ProxyProtocolProxyProtocolV2Ssl = ProxyProtocol("proxy_protocol_v2_ssl")
ProxyProtocolProxyProtocolV2SslCn = ProxyProtocol("proxy_protocol_v2_ssl_cn")
)
func (enum ProxyProtocol) String() string {
if enum == "" {
// return default value if empty
return "proxy_protocol_unknown"
}
return string(enum)
}
func (enum ProxyProtocol) Values() []ProxyProtocol {
return []ProxyProtocol{
"proxy_protocol_unknown",
"proxy_protocol_none",
"proxy_protocol_v1",
"proxy_protocol_v2",
"proxy_protocol_v2_ssl",
"proxy_protocol_v2_ssl_cn",
}
}
func (enum ProxyProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ProxyProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ProxyProtocol(ProxyProtocol(tmp).String())
return nil
}
type SSLCompatibilityLevel string
const (
SSLCompatibilityLevelSslCompatibilityLevelUnknown = SSLCompatibilityLevel("ssl_compatibility_level_unknown")
SSLCompatibilityLevelSslCompatibilityLevelIntermediate = SSLCompatibilityLevel("ssl_compatibility_level_intermediate")
SSLCompatibilityLevelSslCompatibilityLevelModern = SSLCompatibilityLevel("ssl_compatibility_level_modern")
SSLCompatibilityLevelSslCompatibilityLevelOld = SSLCompatibilityLevel("ssl_compatibility_level_old")
)
func (enum SSLCompatibilityLevel) String() string {
if enum == "" {
// return default value if empty
return "ssl_compatibility_level_unknown"
}
return string(enum)
}
func (enum SSLCompatibilityLevel) Values() []SSLCompatibilityLevel {
return []SSLCompatibilityLevel{
"ssl_compatibility_level_unknown",
"ssl_compatibility_level_intermediate",
"ssl_compatibility_level_modern",
"ssl_compatibility_level_old",
}
}
func (enum SSLCompatibilityLevel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SSLCompatibilityLevel) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SSLCompatibilityLevel(SSLCompatibilityLevel(tmp).String())
return nil
}
type StickySessionsType string
const (
StickySessionsTypeNone = StickySessionsType("none")
StickySessionsTypeCookie = StickySessionsType("cookie")
StickySessionsTypeTable = StickySessionsType("table")
)
func (enum StickySessionsType) String() string {
if enum == "" {
// return default value if empty
return "none"
}
return string(enum)
}
func (enum StickySessionsType) Values() []StickySessionsType {
return []StickySessionsType{
"none",
"cookie",
"table",
}
}
func (enum StickySessionsType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *StickySessionsType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = StickySessionsType(StickySessionsType(tmp).String())
return nil
}
// SubscriberEmailConfig: subscriber email config.
type SubscriberEmailConfig struct {
// Email: email address to send alerts to.
Email string `json:"email"`
}
// SubscriberWebhookConfig: Webhook alert of subscriber.
type SubscriberWebhookConfig struct {
// URI: URI to receive POST requests.
URI string `json:"uri"`
}
// HealthCheckHTTPConfig: health check http config.
type HealthCheckHTTPConfig struct {
// URI: the HTTP URI to use when performing a health check on backend servers.
URI string `json:"uri"`
// Method: the HTTP method used when performing a health check on backend servers.
Method string `json:"method"`
// Code: the HTTP response code that should be returned for a health check to be considered successful.
Code *int32 `json:"code"`
// HostHeader: the HTTP host header used when performing a health check on backend servers.
HostHeader string `json:"host_header"`
}
// HealthCheckHTTPSConfig: health check https config.
type HealthCheckHTTPSConfig struct {
// URI: the HTTP URI to use when performing a health check on backend servers.
URI string `json:"uri"`
// Method: the HTTP method used when performing a health check on backend servers.
Method string `json:"method"`
// Code: the HTTP response code that should be returned for a health check to be considered successful.
Code *int32 `json:"code"`
// HostHeader: the HTTP host header used when performing a health check on backend servers.
HostHeader string `json:"host_header"`
// Sni: the SNI value used when performing a health check on backend servers over SSL.
Sni string `json:"sni"`
}
// HealthCheckLdapConfig: health check ldap config.
type HealthCheckLdapConfig struct {
}
// HealthCheckMysqlConfig: health check mysql config.
type HealthCheckMysqlConfig struct {
// User: mySQL user to use for the health check.
User string `json:"user"`
}
// HealthCheckPgsqlConfig: health check pgsql config.
type HealthCheckPgsqlConfig struct {
// User: postgreSQL user to use for the health check.
User string `json:"user"`
}
// HealthCheckRedisConfig: health check redis config.
type HealthCheckRedisConfig struct {
}
// HealthCheckTCPConfig: health check tcp config.
type HealthCheckTCPConfig struct {
}
// IP: ip.
type IP struct {
// ID: IP address ID.
ID string `json:"id"`
// IPAddress: IP address.
IPAddress string `json:"ip_address"`
// OrganizationID: organization ID of the Scaleway Organization the IP address is in.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID of the Scaleway Project the IP address is in.
ProjectID string `json:"project_id"`
// LBID: load Balancer ID.
LBID *string `json:"lb_id"`
// Reverse: reverse DNS (domain name) of the IP address.
Reverse string `json:"reverse"`
// Tags: IP tags.
Tags []string `json:"tags"`
// Deprecated: Region: the region the IP address is in.
Region *scw.Region `json:"region,omitempty"`
// Zone: the zone the IP address is in.
Zone scw.Zone `json:"zone"`
}
// Instance: instance.
type Instance struct {
// ID: underlying Instance ID.
ID string `json:"id"`
// Status: instance status.
// Default value: unknown
Status InstanceStatus `json:"status"`
// IPAddress: instance IP address.
IPAddress string `json:"ip_address"`
// CreatedAt: date on which the Instance was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the Instance was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// Deprecated: Region: the region the Instance is in.
Region *scw.Region `json:"region,omitempty"`
// Zone: the zone the Instance is in.
Zone scw.Zone `json:"zone"`
}
// Subscriber: Subscriber.
type Subscriber struct {
// ID: subscriber ID.
ID string `json:"id"`
// Name: subscriber name.
Name string `json:"name"`
// EmailConfig: email address of subscriber.
// Precisely one of EmailConfig, WebhookConfig must be set.
EmailConfig *SubscriberEmailConfig `json:"email_config,omitempty"`
// WebhookConfig: webhook URI of subscriber.
// Precisely one of EmailConfig, WebhookConfig must be set.
WebhookConfig *SubscriberWebhookConfig `json:"webhook_config,omitempty"`
}
// HealthCheck: health check.
type HealthCheck struct {
// Port: port to use for the backend server health check.
Port int32 `json:"port"`
// CheckDelay: time to wait between two consecutive health checks.
CheckDelay *time.Duration `json:"check_delay"`
// CheckTimeout: maximum time a backend server has to reply to the health check.
CheckTimeout *time.Duration `json:"check_timeout"`
// CheckMaxRetries: number of consecutive unsuccessful health checks after which the server will be considered dead.
CheckMaxRetries int32 `json:"check_max_retries"`
// TCPConfig: object to configure a basic TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
TCPConfig *HealthCheckTCPConfig `json:"tcp_config,omitempty"`
// MysqlConfig: object to configure a MySQL health check. The check requires MySQL >=3.22 or <9.0. For older or newer versions, use a TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
MysqlConfig *HealthCheckMysqlConfig `json:"mysql_config,omitempty"`
// PgsqlConfig: object to configure a PostgreSQL health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
PgsqlConfig *HealthCheckPgsqlConfig `json:"pgsql_config,omitempty"`
// LdapConfig: object to configure an LDAP health check. The response is analyzed to find the LDAPv3 response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
LdapConfig *HealthCheckLdapConfig `json:"ldap_config,omitempty"`
// RedisConfig: object to configure a Redis health check. The response is analyzed to find the +PONG response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
RedisConfig *HealthCheckRedisConfig `json:"redis_config,omitempty"`
// HTTPConfig: object to configure an HTTP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPConfig *HealthCheckHTTPConfig `json:"http_config,omitempty"`
// HTTPSConfig: object to configure an HTTPS health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPSConfig *HealthCheckHTTPSConfig `json:"https_config,omitempty"`
// CheckSendProxy: defines whether proxy protocol should be activated for the health check.
CheckSendProxy bool `json:"check_send_proxy"`
// TransientCheckDelay: time to wait between two consecutive health checks when a backend server is in a transient state (going UP or DOWN).
TransientCheckDelay *scw.Duration `json:"transient_check_delay"`
}
func (m *HealthCheck) UnmarshalJSON(b []byte) error {
type tmpType HealthCheck
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = HealthCheck(tmp.tmpType)
m.CheckDelay = tmp.TmpCheckDelay.Standard()
m.CheckTimeout = tmp.TmpCheckTimeout.Standard()
return nil
}
func (m HealthCheck) MarshalJSON() ([]byte, error) {
type tmpType HealthCheck
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout"`
}{
tmpType: tmpType(m),
TmpCheckDelay: marshaler.NewDuration(m.CheckDelay),
TmpCheckTimeout: marshaler.NewDuration(m.CheckTimeout),
}
return json.Marshal(tmp)
}
// LB: lb.
type LB struct {
// ID: underlying Instance ID.
ID string `json:"id"`
// Name: load Balancer name.
Name string `json:"name"`
// Description: load Balancer description.
Description string `json:"description"`
// Status: load Balancer status.
// Default value: unknown
Status LBStatus `json:"status"`
// Instances: list of underlying Instances.
Instances []*Instance `json:"instances"`
// OrganizationID: scaleway Organization ID.
OrganizationID string `json:"organization_id"`
// ProjectID: scaleway Project ID.
ProjectID string `json:"project_id"`
// IP: list of IP addresses attached to the Load Balancer.
IP []*IP `json:"ip"`
// Tags: load Balancer tags.
Tags []string `json:"tags"`
// FrontendCount: number of frontends the Load Balancer has.
FrontendCount int32 `json:"frontend_count"`
// BackendCount: number of backends the Load Balancer has.
BackendCount int32 `json:"backend_count"`
// Type: load Balancer offer type.
Type string `json:"type"`
// Subscriber: subscriber information.
Subscriber *Subscriber `json:"subscriber"`
// SslCompatibilityLevel: determines the minimal SSL version which needs to be supported on client side.
// Default value: ssl_compatibility_level_unknown
SslCompatibilityLevel SSLCompatibilityLevel `json:"ssl_compatibility_level"`
// CreatedAt: date on which the Load Balancer was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the Load Balancer was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// PrivateNetworkCount: number of Private Networks attached to the Load Balancer.
PrivateNetworkCount int32 `json:"private_network_count"`
// RouteCount: number of routes configured on the Load Balancer.
RouteCount int32 `json:"route_count"`
// Deprecated: Region: the region the Load Balancer is in.
Region *scw.Region `json:"region,omitempty"`
// Zone: the zone the Load Balancer is in.
Zone scw.Zone `json:"zone"`
}
// ACLActionRedirect: acl action redirect.
type ACLActionRedirect struct {
// Type: redirect type.
// Default value: location
Type ACLActionRedirectRedirectType `json:"type"`
// Target: redirect target. For a location redirect, you can use a URL e.g. `https://scaleway.com`. Using a scheme name (e.g. `https`, `http`, `ftp`, `git`) will replace the request's original scheme. This can be useful to implement HTTP to HTTPS redirects. Valid placeholders that can be used in a `location` redirect to preserve parts of the original request in the redirection URL are \{\{host\}\}, \{\{query\}\}, \{\{path\}\} and \{\{scheme\}\}.
Target string `json:"target"`
// Code: HTTP redirect code to use. Valid values are 301, 302, 303, 307 and 308. Default value is 302.
Code *int32 `json:"code"`
}
// Backend: backend.
type Backend struct {
// ID: backend ID.
ID string `json:"id"`
// Name: name of the backend.
Name string `json:"name"`
// ForwardProtocol: protocol used by the backend when forwarding traffic to backend servers.
// Default value: tcp
ForwardProtocol Protocol `json:"forward_protocol"`
// ForwardPort: port used by the backend when forwarding traffic to backend servers.
ForwardPort int32 `json:"forward_port"`
// ForwardPortAlgorithm: load balancing algorithm to use when determining which backend server to forward new traffic to.
// Default value: roundrobin
ForwardPortAlgorithm ForwardPortAlgorithm `json:"forward_port_algorithm"`
// StickySessions: defines whether sticky sessions (binding a particular session to a particular backend server) are activated and the method to use if so. None disables sticky sessions. Cookie-based uses an HTTP cookie to stick a session to a backend server. Table-based uses the source (client) IP address to stick a session to a backend server.
// Default value: none
StickySessions StickySessionsType `json:"sticky_sessions"`
// StickySessionsCookieName: cookie name for cookie-based sticky sessions.
StickySessionsCookieName string `json:"sticky_sessions_cookie_name"`
// HealthCheck: object defining the health check to be carried out by the backend when checking the status and health of backend servers.
HealthCheck *HealthCheck `json:"health_check"`
// Pool: list of IP addresses of backend servers attached to this backend.
Pool []string `json:"pool"`
// LB: load Balancer the backend is attached to.
LB *LB `json:"lb"`
// Deprecated: SendProxyV2: deprecated in favor of proxy_protocol field.
SendProxyV2 *bool `json:"send_proxy_v2,omitempty"`
// TimeoutServer: maximum allowed time for a backend server to process a request.
TimeoutServer *time.Duration `json:"timeout_server"`
// TimeoutConnect: maximum allowed time for establishing a connection to a backend server.
TimeoutConnect *time.Duration `json:"timeout_connect"`
// TimeoutTunnel: maximum allowed tunnel inactivity time after Websocket is established (takes precedence over client and server timeout).
TimeoutTunnel *time.Duration `json:"timeout_tunnel"`
// OnMarkedDownAction: action to take when a backend server is marked as down.
// Default value: on_marked_down_action_none
OnMarkedDownAction OnMarkedDownAction `json:"on_marked_down_action"`
// ProxyProtocol: protocol to use between the Load Balancer and backend servers. Allows the backend servers to be informed of the client's real IP address. The PROXY protocol must be supported by the backend servers' software.
// Default value: proxy_protocol_unknown
ProxyProtocol ProxyProtocol `json:"proxy_protocol"`
// CreatedAt: date at which the backend was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date at which the backend was updated.
UpdatedAt *time.Time `json:"updated_at"`
// FailoverHost: scaleway Object Storage bucket website to be served as failover if all backend servers are down, e.g. failover-website.s3-website.fr-par.scw.cloud.
FailoverHost *string `json:"failover_host"`
// SslBridging: defines whether to enable SSL bridging between the Load Balancer and backend servers.
SslBridging *bool `json:"ssl_bridging"`
// IgnoreSslServerVerify: defines whether the server certificate verification should be ignored.
IgnoreSslServerVerify *bool `json:"ignore_ssl_server_verify"`
// RedispatchAttemptCount: whether to use another backend server on each attempt.
RedispatchAttemptCount *int32 `json:"redispatch_attempt_count"`
// MaxRetries: number of retries when a backend server connection failed.
MaxRetries *int32 `json:"max_retries"`
// MaxConnections: maximum number of connections allowed per backend server.
MaxConnections *int32 `json:"max_connections"`
// TimeoutQueue: maximum time for a request to be left pending in queue when `max_connections` is reached.
TimeoutQueue *scw.Duration `json:"timeout_queue"`
}
func (m *Backend) UnmarshalJSON(b []byte) error {
type tmpType Backend
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = Backend(tmp.tmpType)
m.TimeoutServer = tmp.TmpTimeoutServer.Standard()
m.TimeoutConnect = tmp.TmpTimeoutConnect.Standard()
m.TimeoutTunnel = tmp.TmpTimeoutTunnel.Standard()
return nil
}
func (m Backend) MarshalJSON() ([]byte, error) {
type tmpType Backend
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel"`
}{
tmpType: tmpType(m),
TmpTimeoutServer: marshaler.NewDuration(m.TimeoutServer),
TmpTimeoutConnect: marshaler.NewDuration(m.TimeoutConnect),
TmpTimeoutTunnel: marshaler.NewDuration(m.TimeoutTunnel),
}
return json.Marshal(tmp)
}
// Certificate: certificate.
type Certificate struct {
// Type: certificate type (Let's Encrypt or custom).
// Default value: letsencryt
Type CertificateType `json:"type"`
// ID: certificate ID.
ID string `json:"id"`
// CommonName: main domain name of certificate.
CommonName string `json:"common_name"`
// SubjectAlternativeName: alternative domain names.
SubjectAlternativeName []string `json:"subject_alternative_name"`
// Fingerprint: identifier (SHA-1) of the certificate.
Fingerprint string `json:"fingerprint"`
// NotValidBefore: lower validity bound.
NotValidBefore *time.Time `json:"not_valid_before"`
// NotValidAfter: upper validity bound.
NotValidAfter *time.Time `json:"not_valid_after"`
// Status: certificate status.
// Default value: pending
Status CertificateStatus `json:"status"`
// LB: load Balancer object the certificate is attached to.
LB *LB `json:"lb"`
// Name: certificate name.
Name string `json:"name"`
// CreatedAt: date on which the certificate was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the certificate was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// StatusDetails: additional information about the certificate status (useful in case of certificate generation failure, for example).
StatusDetails *string `json:"status_details"`
}
// ACLAction: acl action.
type ACLAction struct {
// Type: action to take when incoming traffic matches an ACL filter.
// Default value: allow
Type ACLActionType `json:"type"`
// Redirect: redirection parameters when using an ACL with a `redirect` action.
Redirect *ACLActionRedirect `json:"redirect"`
}
// ACLMatch: acl match.
type ACLMatch struct {
// IPSubnet: list of IPs or CIDR v4/v6 addresses to filter for from the client side.
IPSubnet []*string `json:"ip_subnet"`
// HTTPFilter: type of HTTP filter to match. Extracts the request's URL path, which starts at the first slash and ends before the question mark (without the host part). Defines where to filter for the http_filter_value. Only supported for HTTP backends.
// Default value: acl_http_filter_none
HTTPFilter ACLHTTPFilter `json:"http_filter"`
// HTTPFilterValue: list of values to filter for.
HTTPFilterValue []*string `json:"http_filter_value"`
// HTTPFilterOption: name of the HTTP header to filter on if `http_header_match` was selected in `http_filter`.
HTTPFilterOption *string `json:"http_filter_option"`
// Invert: defines whether to invert the match condition. If set to `true`, the ACL carries out its action when the condition DOES NOT match.
Invert bool `json:"invert"`
}
// Frontend: frontend.
type Frontend struct {
// ID: frontend ID.
ID string `json:"id"`
// Name: name of the frontend.
Name string `json:"name"`
// InboundPort: port the frontend listens on.
InboundPort int32 `json:"inbound_port"`
// Backend: backend object the frontend is attached to.
Backend *Backend `json:"backend"`
// LB: load Balancer object the frontend is attached to.
LB *LB `json:"lb"`
// TimeoutClient: maximum allowed inactivity time on the client side.
TimeoutClient *time.Duration `json:"timeout_client"`
// Deprecated: Certificate: certificate, deprecated in favor of certificate_ids array.
Certificate *Certificate `json:"certificate,omitempty"`
// CertificateIDs: list of SSL/TLS certificate IDs to bind to the frontend.
CertificateIDs []string `json:"certificate_ids"`
// CreatedAt: date on which the frontend was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the frontend was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// EnableHTTP3: defines whether to enable HTTP/3 protocol on the frontend.
EnableHTTP3 bool `json:"enable_http3"`
}
func (m *Frontend) UnmarshalJSON(b []byte) error {
type tmpType Frontend
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = Frontend(tmp.tmpType)
m.TimeoutClient = tmp.TmpTimeoutClient.Standard()
return nil
}
func (m Frontend) MarshalJSON() ([]byte, error) {
type tmpType Frontend
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client"`
}{
tmpType: tmpType(m),
TmpTimeoutClient: marshaler.NewDuration(m.TimeoutClient),
}
return json.Marshal(tmp)
}
// PrivateNetworkDHCPConfig: private network dhcp config.
type PrivateNetworkDHCPConfig struct {
// Deprecated
IPID *string `json:"ip_id,omitempty"`
}
// PrivateNetworkIpamConfig: private network ipam config.
type PrivateNetworkIpamConfig struct {
}
// PrivateNetworkStaticConfig: private network static config.
type PrivateNetworkStaticConfig struct {
// Deprecated: IPAddress: array of a local IP address for the Load Balancer on this Private Network.
IPAddress *[]string `json:"ip_address,omitempty"`
}
// RouteMatch: route match.
type RouteMatch struct {
// Sni: value to match in the Server Name Indication TLS extension (SNI) field from an incoming connection made via an SSL/TLS transport layer. This field should be set for routes on TCP Load Balancers.
// Precisely one of Sni, HostHeader must be set.
Sni *string `json:"sni,omitempty"`
// HostHeader: value to match in the HTTP Host request header from an incoming connection. This field should be set for routes on HTTP Load Balancers.
// Precisely one of Sni, HostHeader must be set.
HostHeader *string `json:"host_header,omitempty"`
}
// CreateCertificateRequestCustomCertificate: create certificate request custom certificate.
type CreateCertificateRequestCustomCertificate struct {
// CertificateChain: full PEM-formatted certificate, consisting of the entire certificate chain including public key, private key, and (optionally) Certificate Authorities.
CertificateChain string `json:"certificate_chain"`
}
// CreateCertificateRequestLetsencryptConfig: create certificate request letsencrypt config.
type CreateCertificateRequestLetsencryptConfig struct {
// CommonName: main domain name of certificate (this domain must exist and resolve to your Load Balancer IP address).
CommonName string `json:"common_name"`
// SubjectAlternativeName: alternative domain names (all domain names must exist and resolve to your Load Balancer IP address).
SubjectAlternativeName []string `json:"subject_alternative_name"`
}
// BackendServerStats: backend server stats.
type BackendServerStats struct {
// InstanceID: ID of your Load Balancer's underlying Instance.
InstanceID string `json:"instance_id"`
// BackendID: backend ID.
BackendID string `json:"backend_id"`
// IP: iPv4 or IPv6 address of the backend server.
IP string `json:"ip"`
// ServerState: server operational state (stopped/starting/running/stopping).
// Default value: stopped
ServerState BackendServerStatsServerState `json:"server_state"`
// ServerStateChangedAt: time since last operational change.
ServerStateChangedAt *time.Time `json:"server_state_changed_at"`
// LastHealthCheckStatus: last health check status (unknown/neutral/failed/passed/condpass).
// Default value: unknown
LastHealthCheckStatus BackendServerStatsHealthCheckStatus `json:"last_health_check_status"`
}
// ACL: acl.
type ACL struct {
// ID: ACL ID.
ID string `json:"id"`
// Name: ACL name.
Name string `json:"name"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` & `http_filter_value` are required.
Match *ACLMatch `json:"match"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Frontend: ACL is attached to this frontend object.
Frontend *Frontend `json:"frontend"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// CreatedAt: date on which the ACL was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the ACL was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// Description: ACL description.
Description string `json:"description"`
}
// PrivateNetwork: private network.
type PrivateNetwork struct {
// LB: load Balancer object which is attached to the Private Network.
LB *LB `json:"lb"`
// IpamIDs: iPAM IDs of the booked IP addresses.
IpamIDs []string `json:"ipam_ids"`
// Deprecated: StaticConfig: object containing an array of a local IP address for the Load Balancer on this Private Network.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
StaticConfig *PrivateNetworkStaticConfig `json:"static_config,omitempty"`
// Deprecated: DHCPConfig: object containing DHCP-assigned IP addresses.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
DHCPConfig *PrivateNetworkDHCPConfig `json:"dhcp_config,omitempty"`
// Deprecated: IpamConfig: for internal use only.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
IpamConfig *PrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"private_network_id"`
// Status: status of Private Network connection.
// Default value: unknown
Status PrivateNetworkStatus `json:"status"`
// CreatedAt: date on which the Private Network was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the PN was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// LBType: lb type.
type LBType struct {
// Name: load Balancer commercial offer type name.
Name string `json:"name"`
// StockStatus: current stock status for a given Load Balancer type.
// Default value: unknown
StockStatus LBTypeStock `json:"stock_status"`
// Description: load Balancer commercial offer type description.
Description string `json:"description"`
// Deprecated: Region: the region the Load Balancer stock is in.
Region *scw.Region `json:"region,omitempty"`
// Zone: the zone the Load Balancer stock is in.
Zone scw.Zone `json:"zone"`
}
// Route: route.
type Route struct {
// ID: route ID.
ID string `json:"id"`
// FrontendID: ID of the source frontend.
FrontendID string `json:"frontend_id"`
// BackendID: ID of the target backend.
BackendID string `json:"backend_id"`
// Match: object defining the match condition for a route to be applied. If an incoming client session matches the specified condition (i.e. it has a matching SNI value or HTTP Host header value), it will be passed to the target backend.
Match *RouteMatch `json:"match"`
// CreatedAt: date on which the route was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the route was last updated.
UpdatedAt *time.Time `json:"updated_at"`
}
// ACLSpec: acl spec.
type ACLSpec struct {
// Name: ACL name.
Name string `json:"name"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` and `http_filter_value` are required.
Match *ACLMatch `json:"match"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// Description: ACL description.
Description string `json:"description"`
}
// AddBackendServersRequest: add backend servers request.
type AddBackendServersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses to add to backend servers.
ServerIP []string `json:"server_ip"`
}
// AttachPrivateNetworkRequest: attach private network request.
type AttachPrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Deprecated: StaticConfig: object containing an array of a local IP address for the Load Balancer on this Private Network.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
StaticConfig *PrivateNetworkStaticConfig `json:"static_config,omitempty"`
// Deprecated: DHCPConfig: defines whether to let DHCP assign IP addresses.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
DHCPConfig *PrivateNetworkDHCPConfig `json:"dhcp_config,omitempty"`
// Deprecated: IpamConfig: for internal use only.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
IpamConfig *PrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
// IpamIDs: iPAM ID of a pre-reserved IP address to assign to the Load Balancer on this Private Network. In the future, it will be possible to specify multiple IPs in this field (IPv4 and IPv6), for now only one ID of an IPv4 address is expected. When null, a new private IP address is created for the Load Balancer on this Private Network.
IpamIDs []string `json:"ipam_ids"`
}
// CreateACLRequest: Add an ACL to a Load Balancer frontend.
type CreateACLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: frontend ID to attach the ACL to.
FrontendID string `json:"-"`
// Name: ACL name.
Name string `json:"name"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` & `http_filter_value` are required.
Match *ACLMatch `json:"match,omitempty"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// Description: ACL description.
Description string `json:"description"`
}
// CreateBackendRequest: create backend request.
type CreateBackendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name for the backend.
Name string `json:"name"`
// ForwardProtocol: protocol to be used by the backend when forwarding traffic to backend servers.
// Default value: tcp
ForwardProtocol Protocol `json:"forward_protocol"`
// ForwardPort: port to be used by the backend when forwarding traffic to backend servers.
ForwardPort int32 `json:"forward_port"`
// ForwardPortAlgorithm: load balancing algorithm to be used when determining which backend server to forward new traffic to.
// Default value: roundrobin
ForwardPortAlgorithm ForwardPortAlgorithm `json:"forward_port_algorithm"`
// StickySessions: defines whether to activate sticky sessions (binding a particular session to a particular backend server) and the method to use if so. None disables sticky sessions. Cookie-based uses an HTTP cookie TO stick a session to a backend server. Table-based uses the source (client) IP address to stick a session to a backend server.
// Default value: none
StickySessions StickySessionsType `json:"sticky_sessions"`
// StickySessionsCookieName: cookie name for cookie-based sticky sessions.
StickySessionsCookieName string `json:"sticky_sessions_cookie_name"`
// HealthCheck: object defining the health check to be carried out by the backend when checking the status and health of backend servers.
HealthCheck *HealthCheck `json:"health_check"`
// ServerIP: list of backend server IP addresses (IPv4 or IPv6) the backend should forward traffic to.
ServerIP []string `json:"server_ip"`
// Deprecated: SendProxyV2: deprecated in favor of proxy_protocol field.
SendProxyV2 *bool `json:"send_proxy_v2,omitempty"`
// TimeoutServer: maximum allowed time for a backend server to process a request.
TimeoutServer *time.Duration `json:"timeout_server,omitempty"`
// TimeoutConnect: maximum allowed time for establishing a connection to a backend server.
TimeoutConnect *time.Duration `json:"timeout_connect,omitempty"`
// TimeoutTunnel: maximum allowed tunnel inactivity time after Websocket is established (takes precedence over client and server timeout).
TimeoutTunnel *time.Duration `json:"timeout_tunnel,omitempty"`
// OnMarkedDownAction: action to take when a backend server is marked as down.
// Default value: on_marked_down_action_none
OnMarkedDownAction OnMarkedDownAction `json:"on_marked_down_action"`
// ProxyProtocol: protocol to use between the Load Balancer and backend servers. Allows the backend servers to be informed of the client's real IP address. The PROXY protocol must be supported by the backend servers' software.
// Default value: proxy_protocol_unknown
ProxyProtocol ProxyProtocol `json:"proxy_protocol"`
// FailoverHost: scaleway Object Storage bucket website to be served as failover if all backend servers are down, e.g. failover-website.s3-website.fr-par.scw.cloud.
FailoverHost *string `json:"failover_host,omitempty"`
// SslBridging: defines whether to enable SSL bridging between the Load Balancer and backend servers.
SslBridging *bool `json:"ssl_bridging,omitempty"`
// IgnoreSslServerVerify: defines whether the server certificate verification should be ignored.
IgnoreSslServerVerify *bool `json:"ignore_ssl_server_verify,omitempty"`
// RedispatchAttemptCount: whether to use another backend server on each attempt.
RedispatchAttemptCount *int32 `json:"redispatch_attempt_count,omitempty"`
// MaxRetries: number of retries when a backend server connection failed.
MaxRetries *int32 `json:"max_retries,omitempty"`
// MaxConnections: maximum number of connections allowed per backend server.
MaxConnections *int32 `json:"max_connections,omitempty"`
// TimeoutQueue: maximum time for a request to be left pending in queue when `max_connections` is reached.
TimeoutQueue *scw.Duration `json:"timeout_queue,omitempty"`
}
func (m *CreateBackendRequest) UnmarshalJSON(b []byte) error {
type tmpType CreateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = CreateBackendRequest(tmp.tmpType)
m.TimeoutServer = tmp.TmpTimeoutServer.Standard()
m.TimeoutConnect = tmp.TmpTimeoutConnect.Standard()
m.TimeoutTunnel = tmp.TmpTimeoutTunnel.Standard()
return nil
}
func (m CreateBackendRequest) MarshalJSON() ([]byte, error) {
type tmpType CreateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutServer: marshaler.NewDuration(m.TimeoutServer),
TmpTimeoutConnect: marshaler.NewDuration(m.TimeoutConnect),
TmpTimeoutTunnel: marshaler.NewDuration(m.TimeoutTunnel),
}
return json.Marshal(tmp)
}
// CreateCertificateRequest: create certificate request.
type CreateCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name for the certificate.
Name string `json:"name"`
// Letsencrypt: object to define a new Let's Encrypt certificate to be generated.
// Precisely one of Letsencrypt, CustomCertificate must be set.
Letsencrypt *CreateCertificateRequestLetsencryptConfig `json:"letsencrypt,omitempty"`
// CustomCertificate: object to define an existing custom certificate to be imported.
// Precisely one of Letsencrypt, CustomCertificate must be set.
CustomCertificate *CreateCertificateRequestCustomCertificate `json:"custom_certificate,omitempty"`
}
// CreateFrontendRequest: create frontend request.
type CreateFrontendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID (ID of the Load Balancer to attach the frontend to).
LBID string `json:"-"`
// Name: name for the frontend.
Name string `json:"name"`
// InboundPort: port the frontend should listen on.
InboundPort int32 `json:"inbound_port"`
// BackendID: backend ID (ID of the backend the frontend should pass traffic to).
BackendID string `json:"backend_id"`
// TimeoutClient: maximum allowed inactivity time on the client side.
TimeoutClient *time.Duration `json:"timeout_client,omitempty"`
// Deprecated: CertificateID: certificate ID, deprecated in favor of certificate_ids array.
CertificateID *string `json:"certificate_id,omitempty"`
// CertificateIDs: list of SSL/TLS certificate IDs to bind to the frontend.
CertificateIDs *[]string `json:"certificate_ids,omitempty"`
// EnableHTTP3: defines whether to enable HTTP/3 protocol on the frontend.
EnableHTTP3 bool `json:"enable_http3"`
}
func (m *CreateFrontendRequest) UnmarshalJSON(b []byte) error {
type tmpType CreateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = CreateFrontendRequest(tmp.tmpType)
m.TimeoutClient = tmp.TmpTimeoutClient.Standard()
return nil
}
func (m CreateFrontendRequest) MarshalJSON() ([]byte, error) {
type tmpType CreateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutClient: marshaler.NewDuration(m.TimeoutClient),
}
return json.Marshal(tmp)
}
// CreateIPRequest: create ip request.
type CreateIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Deprecated: OrganizationID: organization ID of the Organization where the IP address should be created.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID of the Project where the IP address should be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Reverse: reverse DNS (domain name) for the IP address.
Reverse *string `json:"reverse,omitempty"`
// IsIPv6: if true, creates a Flexible IP with an ipv6 address.
IsIPv6 bool `json:"is_ipv6"`
// Tags: list of tags for the IP.
Tags []string `json:"tags"`
}
// CreateLBRequest: create lb request.
type CreateLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Deprecated: OrganizationID: scaleway Organization to create the Load Balancer in.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: scaleway Project to create the Load Balancer in.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Name: name for the Load Balancer.
Name string `json:"name"`
// Description: description for the Load Balancer.
Description string `json:"description"`
// Deprecated: IPID: ID of an existing flexible IP address to attach to the Load Balancer.
IPID *string `json:"ip_id,omitempty"`
// AssignFlexibleIP: defines whether to automatically assign a flexible public IP to the Load Balancer. Default value is `true` (assign).
AssignFlexibleIP *bool `json:"assign_flexible_ip,omitempty"`
// AssignFlexibleIPv6: defines whether to automatically assign a flexible public IPv6 to the Load Balancer. Default value is `false` (do not assign).
AssignFlexibleIPv6 *bool `json:"assign_flexible_ipv6,omitempty"`
// IPIDs: list of IP IDs to attach to the Load Balancer.
IPIDs []string `json:"ip_ids"`
// Tags: list of tags for the Load Balancer.
Tags []string `json:"tags"`
// Type: load Balancer commercial offer type. Use the Load Balancer types endpoint to retrieve a list of available offer types.
Type string `json:"type"`
// SslCompatibilityLevel: determines the minimal SSL version which needs to be supported on the client side, in an SSL/TLS offloading context. Intermediate is suitable for general-purpose servers with a variety of clients, recommended for almost all systems. Modern is suitable for services with clients that support TLS 1.3 and do not need backward compatibility. Old is compatible with a small number of very old clients and should be used only as a last resort.
// Default value: ssl_compatibility_level_unknown
SslCompatibilityLevel SSLCompatibilityLevel `json:"ssl_compatibility_level"`
}
// CreateRouteRequest: create route request.
type CreateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: ID of the source frontend to create the route on.
FrontendID string `json:"frontend_id"`
// BackendID: ID of the target backend for the route.
BackendID string `json:"backend_id"`
// Match: object defining the match condition for a route to be applied. If an incoming client session matches the specified condition (i.e. it has a matching SNI value or HTTP Host header value), it will be passed to the target backend.
Match *RouteMatch `json:"match,omitempty"`
}
// CreateSubscriberRequest: Create a new alert subscriber (webhook or email).
type CreateSubscriberRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: subscriber name.
Name string `json:"name"`
// EmailConfig: email address configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
EmailConfig *SubscriberEmailConfig `json:"email_config,omitempty"`
// WebhookConfig: webHook URI configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
WebhookConfig *SubscriberWebhookConfig `json:"webhook_config,omitempty"`
// Deprecated: OrganizationID: organization ID to create the subscriber in.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID to create the subscriber in.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
}
// DeleteACLRequest: delete acl request.
type DeleteACLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
}
// DeleteBackendRequest: delete backend request.
type DeleteBackendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: ID of the backend to delete.
BackendID string `json:"-"`
}
// DeleteCertificateRequest: delete certificate request.
type DeleteCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
}
// DeleteFrontendRequest: delete frontend request.
type DeleteFrontendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: ID of the frontend to delete.
FrontendID string `json:"-"`
}
// DeleteLBRequest: delete lb request.
type DeleteLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: ID of the Load Balancer to delete.
LBID string `json:"-"`
// ReleaseIP: defines whether the Load Balancer's flexible IP should be deleted. Set to true to release the flexible IP, or false to keep it available in your account for future Load Balancers.
ReleaseIP bool `json:"release_ip"`
}
// DeleteRouteRequest: delete route request.
type DeleteRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// DeleteSubscriberRequest: delete subscriber request.
type DeleteSubscriberRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
}
// DetachPrivateNetworkRequest: detach private network request.
type DetachPrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load balancer ID.
LBID string `json:"-"`
// PrivateNetworkID: set your instance private network id.
PrivateNetworkID string `json:"-"`
}
// GetACLRequest: get acl request.
type GetACLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
}
// GetBackendRequest: get backend request.
type GetBackendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
}
// GetCertificateRequest: get certificate request.
type GetCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
}
// GetFrontendRequest: get frontend request.
type GetFrontendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: frontend ID.
FrontendID string `json:"-"`
}
// GetIPRequest: get ip request.
type GetIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
}
// GetLBRequest: get lb request.
type GetLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
}
// GetLBStatsRequest: Get Load Balancer stats.
type GetLBStatsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// BackendID: ID of the backend.
BackendID *string `json:"backend_id,omitempty"`
}
// GetRouteRequest: get route request.
type GetRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// GetSubscriberRequest: get subscriber request.
type GetSubscriberRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
}
// LBStats: lb stats.
type LBStats struct {
// BackendServersStats: list of objects containing Load Balancer statistics.
BackendServersStats []*BackendServerStats `json:"backend_servers_stats"`
}
// ListACLResponse: list acl response.
type ListACLResponse struct {
// ACLs: list of ACL objects.
ACLs []*ACL `json:"acls"`
// TotalCount: the total number of objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListACLResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListACLResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListACLResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ACLs = append(r.ACLs, results.ACLs...)
r.TotalCount += uint32(len(results.ACLs))
return uint32(len(results.ACLs)), nil
}
// ListACLsRequest: list ac ls request.
type ListACLsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: frontend ID (ACLs attached to this frontend will be returned in the response).
FrontendID string `json:"-"`
// OrderBy: sort order of ACLs in the response.
// Default value: created_at_asc
OrderBy ListACLRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of ACLs to return.
PageSize *uint32 `json:"-"`
// Name: ACL name to filter for.
Name *string `json:"-"`
}
// ListBackendStatsRequest: list backend stats request.
type ListBackendStatsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of items to return.
PageSize *uint32 `json:"-"`
// BackendID: ID of the backend.
BackendID *string `json:"-"`
}
// ListBackendStatsResponse: list backend stats response.
type ListBackendStatsResponse struct {
// BackendServersStats: list of objects containing backend server statistics.
BackendServersStats []*BackendServerStats `json:"backend_servers_stats"`
// TotalCount: the total number of objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListBackendStatsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListBackendStatsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListBackendStatsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.BackendServersStats = append(r.BackendServersStats, results.BackendServersStats...)
r.TotalCount += uint32(len(results.BackendServersStats))
return uint32(len(results.BackendServersStats)), nil
}
// ListBackendsRequest: list backends request.
type ListBackendsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name of the backend to filter for.
Name *string `json:"-"`
// OrderBy: sort order of backends in the response.
// Default value: created_at_asc
OrderBy ListBackendsRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of backends to return.
PageSize *uint32 `json:"-"`
}
// ListBackendsResponse: list backends response.
type ListBackendsResponse struct {
// Backends: list of backend objects of a given Load Balancer.
Backends []*Backend `json:"backends"`
// TotalCount: total count of backend objects, without pagination.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListBackendsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListBackendsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListBackendsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Backends = append(r.Backends, results.Backends...)
r.TotalCount += uint32(len(results.Backends))
return uint32(len(results.Backends)), nil
}
// ListCertificatesRequest: list certificates request.
type ListCertificatesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// OrderBy: sort order of certificates in the response.
// Default value: created_at_asc
OrderBy ListCertificatesRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of certificates to return.
PageSize *uint32 `json:"-"`
// Name: certificate name to filter for, only certificates of this name will be returned.
Name *string `json:"-"`
}
// ListCertificatesResponse: list certificates response.
type ListCertificatesResponse struct {
// Certificates: list of certificate objects.
Certificates []*Certificate `json:"certificates"`
// TotalCount: the total number of objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListCertificatesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListCertificatesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListCertificatesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Certificates = append(r.Certificates, results.Certificates...)
r.TotalCount += uint32(len(results.Certificates))
return uint32(len(results.Certificates)), nil
}
// ListFrontendsRequest: list frontends request.
type ListFrontendsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name of the frontend to filter for.
Name *string `json:"-"`
// OrderBy: sort order of frontends in the response.
// Default value: created_at_asc
OrderBy ListFrontendsRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of frontends to return.
PageSize *uint32 `json:"-"`
}
// ListFrontendsResponse: list frontends response.
type ListFrontendsResponse struct {
// Frontends: list of frontend objects of a given Load Balancer.
Frontends []*Frontend `json:"frontends"`
// TotalCount: total count of frontend objects, without pagination.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFrontendsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFrontendsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListFrontendsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Frontends = append(r.Frontends, results.Frontends...)
r.TotalCount += uint32(len(results.Frontends))
return uint32(len(results.Frontends)), nil
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of IP addresses to return.
PageSize *uint32 `json:"-"`
// IPAddress: IP address to filter for.
IPAddress *string `json:"-"`
// OrganizationID: organization ID to filter for, only Load Balancer IP addresses from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only Load Balancer IP addresses from this Project will be returned.
ProjectID *string `json:"-"`
// IPType: IP type to filter for.
// Default value: all
IPType ListIPsRequestIPType `json:"-"`
// Tags: tag to filter for, only IPs with one or more matching tags will be returned.
Tags []string `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
// IPs: list of IP address objects.
IPs []*IP `json:"ips"`
// TotalCount: total count of IP address objects, without pagination.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint32(len(results.IPs))
return uint32(len(results.IPs)), nil
}
// ListLBPrivateNetworksRequest: list lb private networks request.
type ListLBPrivateNetworksRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// OrderBy: sort order of Private Network objects in the response.
// Default value: created_at_asc
OrderBy ListPrivateNetworksRequestOrderBy `json:"-"`
// PageSize: number of objects to return.
PageSize *uint32 `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
}
// ListLBPrivateNetworksResponse: list lb private networks response.
type ListLBPrivateNetworksResponse struct {
// PrivateNetwork: list of Private Network objects attached to the Load Balancer.
PrivateNetwork []*PrivateNetwork `json:"private_network"`
// TotalCount: total number of objects in the response.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLBPrivateNetworksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLBPrivateNetworksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListLBPrivateNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PrivateNetwork = append(r.PrivateNetwork, results.PrivateNetwork...)
r.TotalCount += uint32(len(results.PrivateNetwork))
return uint32(len(results.PrivateNetwork)), nil
}
// ListLBTypesRequest: list lb types request.
type ListLBTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of items to return.
PageSize *uint32 `json:"-"`
}
// ListLBTypesResponse: list lb types response.
type ListLBTypesResponse struct {
// LBTypes: list of Load Balancer commercial offer type objects.
LBTypes []*LBType `json:"lb_types"`
// TotalCount: total number of Load Balancer offer type objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLBTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLBTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListLBTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.LBTypes = append(r.LBTypes, results.LBTypes...)
r.TotalCount += uint32(len(results.LBTypes))
return uint32(len(results.LBTypes)), nil
}
// ListLBsRequest: list l bs request.
type ListLBsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: load Balancer name to filter for.
Name *string `json:"-"`
// OrderBy: sort order of Load Balancers in the response.
// Default value: created_at_asc
OrderBy ListLBsRequestOrderBy `json:"-"`
// PageSize: number of Load Balancers to return.
PageSize *uint32 `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// OrganizationID: organization ID to filter for, only Load Balancers from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only Load Balancers from this Project will be returned.
ProjectID *string `json:"-"`
// Tags: filter by tag, only Load Balancers with one or more matching tags will be returned.
Tags []string `json:"-"`
}
// ListLBsResponse: list l bs response.
type ListLBsResponse struct {
// LBs: list of Load Balancer objects.
LBs []*LB `json:"lbs"`
// TotalCount: the total number of Load Balancer objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLBsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLBsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListLBsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.LBs = append(r.LBs, results.LBs...)
r.TotalCount += uint32(len(results.LBs))
return uint32(len(results.LBs)), nil
}
// ListRoutesRequest: list routes request.
type ListRoutesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of routes in the response.
// Default value: created_at_asc
OrderBy ListRoutesRequestOrderBy `json:"-"`
// PageSize: the number of route objects to return.
PageSize *uint32 `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// FrontendID: frontend ID to filter for, only Routes from this Frontend will be returned.
FrontendID *string `json:"-"`
}
// ListRoutesResponse: list routes response.
type ListRoutesResponse struct {
// Routes: list of route objects.
Routes []*Route `json:"routes"`
// TotalCount: the total number of route objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRoutesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRoutesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListRoutesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Routes = append(r.Routes, results.Routes...)
r.TotalCount += uint32(len(results.Routes))
return uint32(len(results.Routes)), nil
}
// ListSubscriberRequest: list subscriber request.
type ListSubscriberRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of subscribers in the response.
// Default value: created_at_asc
OrderBy ListSubscriberRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of items to return.
PageSize *uint32 `json:"-"`
// Name: subscriber name to search for.
Name *string `json:"-"`
// OrganizationID: filter subscribers by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter subscribers by Project ID.
ProjectID *string `json:"-"`
}
// ListSubscriberResponse: list subscriber response.
type ListSubscriberResponse struct {
// Subscribers: list of subscriber objects.
Subscribers []*Subscriber `json:"subscribers"`
// TotalCount: the total number of objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSubscriberResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSubscriberResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSubscriberResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Subscribers = append(r.Subscribers, results.Subscribers...)
r.TotalCount += uint32(len(results.Subscribers))
return uint32(len(results.Subscribers)), nil
}
// MigrateLBRequest: migrate lb request.
type MigrateLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Type: load Balancer type to migrate to (use the List all Load Balancer offer types endpoint to get a list of available offer types).
Type string `json:"type"`
}
// ReleaseIPRequest: release ip request.
type ReleaseIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
}
// RemoveBackendServersRequest: remove backend servers request.
type RemoveBackendServersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses to remove from backend servers.
ServerIP []string `json:"server_ip"`
}
// SetACLsResponse: set ac ls response.
type SetACLsResponse struct {
// ACLs: list of ACL objects.
ACLs []*ACL `json:"acls"`
// TotalCount: the total number of ACL objects.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *SetACLsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *SetACLsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*SetACLsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ACLs = append(r.ACLs, results.ACLs...)
r.TotalCount += uint32(len(results.ACLs))
return uint32(len(results.ACLs)), nil
}
// SetBackendServersRequest: set backend servers request.
type SetBackendServersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses for backend servers. Any other existing backend servers will be removed.
ServerIP []string `json:"server_ip"`
}
// SubscribeToLBRequest: subscribe to lb request.
type SubscribeToLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"subscriber_id"`
}
// UnsubscribeFromLBRequest: unsubscribe from lb request.
type UnsubscribeFromLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
}
// UpdateACLRequest: update acl request.
type UpdateACLRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
// Name: ACL name.
Name string `json:"name"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` & `http_filter_value` are required.
Match *ACLMatch `json:"match,omitempty"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// Description: ACL description.
Description *string `json:"description,omitempty"`
}
// UpdateBackendRequest: update backend request.
type UpdateBackendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// Name: backend name.
Name string `json:"name"`
// ForwardProtocol: protocol to be used by the backend when forwarding traffic to backend servers.
// Default value: tcp
ForwardProtocol Protocol `json:"forward_protocol"`
// ForwardPort: port to be used by the backend when forwarding traffic to backend servers.
ForwardPort int32 `json:"forward_port"`
// ForwardPortAlgorithm: load balancing algorithm to be used when determining which backend server to forward new traffic to.
// Default value: roundrobin
ForwardPortAlgorithm ForwardPortAlgorithm `json:"forward_port_algorithm"`
// StickySessions: defines whether to activate sticky sessions (binding a particular session to a particular backend server) and the method to use if so. None disables sticky sessions. Cookie-based uses an HTTP cookie to stick a session to a backend server. Table-based uses the source (client) IP address to stick a session to a backend server.
// Default value: none
StickySessions StickySessionsType `json:"sticky_sessions"`
// StickySessionsCookieName: cookie name for cookie-based sticky sessions.
StickySessionsCookieName string `json:"sticky_sessions_cookie_name"`
// Deprecated: SendProxyV2: deprecated in favor of proxy_protocol field.
SendProxyV2 *bool `json:"send_proxy_v2,omitempty"`
// TimeoutServer: maximum allowed time for a backend server to process a request.
TimeoutServer *time.Duration `json:"timeout_server,omitempty"`
// TimeoutConnect: maximum allowed time for establishing a connection to a backend server.
TimeoutConnect *time.Duration `json:"timeout_connect,omitempty"`
// TimeoutTunnel: maximum allowed tunnel inactivity time after Websocket is established (takes precedence over client and server timeout).
TimeoutTunnel *time.Duration `json:"timeout_tunnel,omitempty"`
// OnMarkedDownAction: action to take when a backend server is marked as down.
// Default value: on_marked_down_action_none
OnMarkedDownAction OnMarkedDownAction `json:"on_marked_down_action"`
// ProxyProtocol: protocol to use between the Load Balancer and backend servers. Allows the backend servers to be informed of the client's real IP address. The PROXY protocol must be supported by the backend servers' software.
// Default value: proxy_protocol_unknown
ProxyProtocol ProxyProtocol `json:"proxy_protocol"`
// FailoverHost: scaleway Object Storage bucket website to be served as failover if all backend servers are down, e.g. failover-website.s3-website.fr-par.scw.cloud.
FailoverHost *string `json:"failover_host,omitempty"`
// SslBridging: defines whether to enable SSL bridging between the Load Balancer and backend servers.
SslBridging *bool `json:"ssl_bridging,omitempty"`
// IgnoreSslServerVerify: defines whether the server certificate verification should be ignored.
IgnoreSslServerVerify *bool `json:"ignore_ssl_server_verify,omitempty"`
// RedispatchAttemptCount: whether to use another backend server on each attempt.
RedispatchAttemptCount *int32 `json:"redispatch_attempt_count,omitempty"`
// MaxRetries: number of retries when a backend server connection failed.
MaxRetries *int32 `json:"max_retries,omitempty"`
// MaxConnections: maximum number of connections allowed per backend server.
MaxConnections *int32 `json:"max_connections,omitempty"`
// TimeoutQueue: maximum time for a request to be left pending in queue when `max_connections` is reached.
TimeoutQueue *scw.Duration `json:"timeout_queue,omitempty"`
}
func (m *UpdateBackendRequest) UnmarshalJSON(b []byte) error {
type tmpType UpdateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = UpdateBackendRequest(tmp.tmpType)
m.TimeoutServer = tmp.TmpTimeoutServer.Standard()
m.TimeoutConnect = tmp.TmpTimeoutConnect.Standard()
m.TimeoutTunnel = tmp.TmpTimeoutTunnel.Standard()
return nil
}
func (m UpdateBackendRequest) MarshalJSON() ([]byte, error) {
type tmpType UpdateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutServer: marshaler.NewDuration(m.TimeoutServer),
TmpTimeoutConnect: marshaler.NewDuration(m.TimeoutConnect),
TmpTimeoutTunnel: marshaler.NewDuration(m.TimeoutTunnel),
}
return json.Marshal(tmp)
}
// UpdateCertificateRequest: update certificate request.
type UpdateCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
// Name: certificate name.
Name string `json:"name"`
}
// UpdateFrontendRequest: update frontend request.
type UpdateFrontendRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// FrontendID: frontend ID.
FrontendID string `json:"-"`
// Name: frontend name.
Name string `json:"name"`
// InboundPort: port the frontend should listen on.
InboundPort int32 `json:"inbound_port"`
// BackendID: backend ID (ID of the backend the frontend should pass traffic to).
BackendID string `json:"backend_id"`
// TimeoutClient: maximum allowed inactivity time on the client side.
TimeoutClient *time.Duration `json:"timeout_client,omitempty"`
// Deprecated: CertificateID: certificate ID, deprecated in favor of certificate_ids array.
CertificateID *string `json:"certificate_id,omitempty"`
// CertificateIDs: list of SSL/TLS certificate IDs to bind to the frontend.
CertificateIDs *[]string `json:"certificate_ids,omitempty"`
// EnableHTTP3: defines whether to enable HTTP/3 protocol on the frontend.
EnableHTTP3 bool `json:"enable_http3"`
}
func (m *UpdateFrontendRequest) UnmarshalJSON(b []byte) error {
type tmpType UpdateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = UpdateFrontendRequest(tmp.tmpType)
m.TimeoutClient = tmp.TmpTimeoutClient.Standard()
return nil
}
func (m UpdateFrontendRequest) MarshalJSON() ([]byte, error) {
type tmpType UpdateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutClient: marshaler.NewDuration(m.TimeoutClient),
}
return json.Marshal(tmp)
}
// UpdateHealthCheckRequest: update health check request.
type UpdateHealthCheckRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// Port: port to use for the backend server health check.
Port int32 `json:"port"`
// CheckDelay: time to wait between two consecutive health checks.
CheckDelay *time.Duration `json:"check_delay,omitempty"`
// CheckTimeout: maximum time a backend server has to reply to the health check.
CheckTimeout *time.Duration `json:"check_timeout,omitempty"`
// CheckMaxRetries: number of consecutive unsuccessful health checks after which the server will be considered dead.
CheckMaxRetries int32 `json:"check_max_retries"`
// CheckSendProxy: defines whether proxy protocol should be activated for the health check.
CheckSendProxy bool `json:"check_send_proxy"`
// TCPConfig: object to configure a basic TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
TCPConfig *HealthCheckTCPConfig `json:"tcp_config,omitempty"`
// MysqlConfig: object to configure a MySQL health check. The check requires MySQL >=3.22 or <9.0. For older or newer versions, use a TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
MysqlConfig *HealthCheckMysqlConfig `json:"mysql_config,omitempty"`
// PgsqlConfig: object to configure a PostgreSQL health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
PgsqlConfig *HealthCheckPgsqlConfig `json:"pgsql_config,omitempty"`
// LdapConfig: object to configure an LDAP health check. The response is analyzed to find the LDAPv3 response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
LdapConfig *HealthCheckLdapConfig `json:"ldap_config,omitempty"`
// RedisConfig: object to configure a Redis health check. The response is analyzed to find the +PONG response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
RedisConfig *HealthCheckRedisConfig `json:"redis_config,omitempty"`
// HTTPConfig: object to configure an HTTP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPConfig *HealthCheckHTTPConfig `json:"http_config,omitempty"`
// HTTPSConfig: object to configure an HTTPS health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPSConfig *HealthCheckHTTPSConfig `json:"https_config,omitempty"`
// TransientCheckDelay: time to wait between two consecutive health checks when a backend server is in a transient state (going UP or DOWN).
TransientCheckDelay *scw.Duration `json:"transient_check_delay,omitempty"`
}
func (m *UpdateHealthCheckRequest) UnmarshalJSON(b []byte) error {
type tmpType UpdateHealthCheckRequest
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay,omitempty"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = UpdateHealthCheckRequest(tmp.tmpType)
m.CheckDelay = tmp.TmpCheckDelay.Standard()
m.CheckTimeout = tmp.TmpCheckTimeout.Standard()
return nil
}
func (m UpdateHealthCheckRequest) MarshalJSON() ([]byte, error) {
type tmpType UpdateHealthCheckRequest
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay,omitempty"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout,omitempty"`
}{
tmpType: tmpType(m),
TmpCheckDelay: marshaler.NewDuration(m.CheckDelay),
TmpCheckTimeout: marshaler.NewDuration(m.CheckTimeout),
}
return json.Marshal(tmp)
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
// Reverse: reverse DNS (domain name) for the IP address.
Reverse *string `json:"reverse,omitempty"`
// LBID: ID of the server on which to attach the flexible IP.
LBID *string `json:"lb_id,omitempty"`
// Tags: list of tags for the IP.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateLBRequest: update lb request.
type UpdateLBRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: load Balancer name.
Name string `json:"name"`
// Description: load Balancer description.
Description string `json:"description"`
// Tags: list of tags for the Load Balancer.
Tags []string `json:"tags"`
// SslCompatibilityLevel: determines the minimal SSL version which needs to be supported on the client side, in an SSL/TLS offloading context. Intermediate is suitable for general-purpose servers with a variety of clients, recommended for almost all systems. Modern is suitable for services with clients that support TLS 1.3 and don't need backward compatibility. Old is compatible with a small number of very old clients and should be used only as a last resort.
// Default value: ssl_compatibility_level_unknown
SslCompatibilityLevel SSLCompatibilityLevel `json:"ssl_compatibility_level"`
}
// UpdateRouteRequest: update route request.
type UpdateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
// BackendID: ID of the target backend for the route.
BackendID string `json:"backend_id"`
// Match: object defining the match condition for a route to be applied. If an incoming client session matches the specified condition (i.e. it has a matching SNI value or HTTP Host header value), it will be passed to the target backend.
Match *RouteMatch `json:"match,omitempty"`
}
// UpdateSubscriberRequest: update subscriber request.
type UpdateSubscriberRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
// Name: subscriber name.
Name string `json:"name"`
// EmailConfig: email address configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
EmailConfig *SubscriberEmailConfig `json:"email_config,omitempty"`
// WebhookConfig: webhook URI configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
WebhookConfig *SubscriberWebhookConfig `json:"webhook_config,omitempty"`
}
// ZonedAPIAddBackendServersRequest: zoned api add backend servers request.
type ZonedAPIAddBackendServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses to add to backend servers.
ServerIP []string `json:"server_ip"`
}
// ZonedAPIAttachPrivateNetworkRequest: zoned api attach private network request.
type ZonedAPIAttachPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Deprecated: StaticConfig: object containing an array of a local IP address for the Load Balancer on this Private Network.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
StaticConfig *PrivateNetworkStaticConfig `json:"static_config,omitempty"`
// Deprecated: DHCPConfig: defines whether to let DHCP assign IP addresses.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
DHCPConfig *PrivateNetworkDHCPConfig `json:"dhcp_config,omitempty"`
// Deprecated: IpamConfig: for internal use only.
// Precisely one of StaticConfig, DHCPConfig, IpamConfig must be set.
IpamConfig *PrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
// IpamIDs: iPAM ID of a pre-reserved IP address to assign to the Load Balancer on this Private Network. In the future, it will be possible to specify multiple IPs in this field (IPv4 and IPv6), for now only one ID of an IPv4 address is expected. When null, a new private IP address is created for the Load Balancer on this Private Network.
IpamIDs []string `json:"ipam_ids"`
}
// ZonedAPICreateACLRequest: Add an ACL to a Load Balancer frontend.
type ZonedAPICreateACLRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: frontend ID to attach the ACL to.
FrontendID string `json:"-"`
// Name: ACL name.
Name string `json:"name"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` & `http_filter_value` are required.
Match *ACLMatch `json:"match,omitempty"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// Description: ACL description.
Description string `json:"description"`
}
// ZonedAPICreateBackendRequest: zoned api create backend request.
type ZonedAPICreateBackendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name for the backend.
Name string `json:"name"`
// ForwardProtocol: protocol to be used by the backend when forwarding traffic to backend servers.
// Default value: tcp
ForwardProtocol Protocol `json:"forward_protocol"`
// ForwardPort: port to be used by the backend when forwarding traffic to backend servers.
ForwardPort int32 `json:"forward_port"`
// ForwardPortAlgorithm: load balancing algorithm to be used when determining which backend server to forward new traffic to.
// Default value: roundrobin
ForwardPortAlgorithm ForwardPortAlgorithm `json:"forward_port_algorithm"`
// StickySessions: defines whether to activate sticky sessions (binding a particular session to a particular backend server) and the method to use if so. None disables sticky sessions. Cookie-based uses an HTTP cookie TO stick a session to a backend server. Table-based uses the source (client) IP address to stick a session to a backend server.
// Default value: none
StickySessions StickySessionsType `json:"sticky_sessions"`
// StickySessionsCookieName: cookie name for cookie-based sticky sessions.
StickySessionsCookieName string `json:"sticky_sessions_cookie_name"`
// HealthCheck: object defining the health check to be carried out by the backend when checking the status and health of backend servers.
HealthCheck *HealthCheck `json:"health_check"`
// ServerIP: list of backend server IP addresses (IPv4 or IPv6) the backend should forward traffic to.
ServerIP []string `json:"server_ip"`
// Deprecated: SendProxyV2: deprecated in favor of proxy_protocol field.
SendProxyV2 *bool `json:"send_proxy_v2,omitempty"`
// TimeoutServer: maximum allowed time for a backend server to process a request.
TimeoutServer *time.Duration `json:"timeout_server,omitempty"`
// TimeoutConnect: maximum allowed time for establishing a connection to a backend server.
TimeoutConnect *time.Duration `json:"timeout_connect,omitempty"`
// TimeoutTunnel: maximum allowed tunnel inactivity time after Websocket is established (takes precedence over client and server timeout).
TimeoutTunnel *time.Duration `json:"timeout_tunnel,omitempty"`
// OnMarkedDownAction: action to take when a backend server is marked as down.
// Default value: on_marked_down_action_none
OnMarkedDownAction OnMarkedDownAction `json:"on_marked_down_action"`
// ProxyProtocol: protocol to use between the Load Balancer and backend servers. Allows the backend servers to be informed of the client's real IP address. The PROXY protocol must be supported by the backend servers' software.
// Default value: proxy_protocol_unknown
ProxyProtocol ProxyProtocol `json:"proxy_protocol"`
// FailoverHost: scaleway Object Storage bucket website to be served as failover if all backend servers are down, e.g. failover-website.s3-website.fr-par.scw.cloud.
FailoverHost *string `json:"failover_host,omitempty"`
// SslBridging: defines whether to enable SSL bridging between the Load Balancer and backend servers.
SslBridging *bool `json:"ssl_bridging,omitempty"`
// IgnoreSslServerVerify: defines whether the server certificate verification should be ignored.
IgnoreSslServerVerify *bool `json:"ignore_ssl_server_verify,omitempty"`
// RedispatchAttemptCount: whether to use another backend server on each attempt.
RedispatchAttemptCount *int32 `json:"redispatch_attempt_count,omitempty"`
// MaxRetries: number of retries when a backend server connection failed.
MaxRetries *int32 `json:"max_retries,omitempty"`
// MaxConnections: maximum number of connections allowed per backend server.
MaxConnections *int32 `json:"max_connections,omitempty"`
// TimeoutQueue: maximum time for a request to be left pending in queue when `max_connections` is reached.
TimeoutQueue *scw.Duration `json:"timeout_queue,omitempty"`
}
func (m *ZonedAPICreateBackendRequest) UnmarshalJSON(b []byte) error {
type tmpType ZonedAPICreateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = ZonedAPICreateBackendRequest(tmp.tmpType)
m.TimeoutServer = tmp.TmpTimeoutServer.Standard()
m.TimeoutConnect = tmp.TmpTimeoutConnect.Standard()
m.TimeoutTunnel = tmp.TmpTimeoutTunnel.Standard()
return nil
}
func (m ZonedAPICreateBackendRequest) MarshalJSON() ([]byte, error) {
type tmpType ZonedAPICreateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutServer: marshaler.NewDuration(m.TimeoutServer),
TmpTimeoutConnect: marshaler.NewDuration(m.TimeoutConnect),
TmpTimeoutTunnel: marshaler.NewDuration(m.TimeoutTunnel),
}
return json.Marshal(tmp)
}
// ZonedAPICreateCertificateRequest: zoned api create certificate request.
type ZonedAPICreateCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name for the certificate.
Name string `json:"name"`
// Letsencrypt: object to define a new Let's Encrypt certificate to be generated.
// Precisely one of Letsencrypt, CustomCertificate must be set.
Letsencrypt *CreateCertificateRequestLetsencryptConfig `json:"letsencrypt,omitempty"`
// CustomCertificate: object to define an existing custom certificate to be imported.
// Precisely one of Letsencrypt, CustomCertificate must be set.
CustomCertificate *CreateCertificateRequestCustomCertificate `json:"custom_certificate,omitempty"`
}
// ZonedAPICreateFrontendRequest: zoned api create frontend request.
type ZonedAPICreateFrontendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID (ID of the Load Balancer to attach the frontend to).
LBID string `json:"-"`
// Name: name for the frontend.
Name string `json:"name"`
// InboundPort: port the frontend should listen on.
InboundPort int32 `json:"inbound_port"`
// BackendID: backend ID (ID of the backend the frontend should pass traffic to).
BackendID string `json:"backend_id"`
// TimeoutClient: maximum allowed inactivity time on the client side.
TimeoutClient *time.Duration `json:"timeout_client,omitempty"`
// Deprecated: CertificateID: certificate ID, deprecated in favor of certificate_ids array.
CertificateID *string `json:"certificate_id,omitempty"`
// CertificateIDs: list of SSL/TLS certificate IDs to bind to the frontend.
CertificateIDs *[]string `json:"certificate_ids,omitempty"`
// EnableHTTP3: defines whether to enable HTTP/3 protocol on the frontend.
EnableHTTP3 bool `json:"enable_http3"`
}
func (m *ZonedAPICreateFrontendRequest) UnmarshalJSON(b []byte) error {
type tmpType ZonedAPICreateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = ZonedAPICreateFrontendRequest(tmp.tmpType)
m.TimeoutClient = tmp.TmpTimeoutClient.Standard()
return nil
}
func (m ZonedAPICreateFrontendRequest) MarshalJSON() ([]byte, error) {
type tmpType ZonedAPICreateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutClient: marshaler.NewDuration(m.TimeoutClient),
}
return json.Marshal(tmp)
}
// ZonedAPICreateIPRequest: zoned api create ip request.
type ZonedAPICreateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Deprecated: OrganizationID: organization ID of the Organization where the IP address should be created.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID of the Project where the IP address should be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Reverse: reverse DNS (domain name) for the IP address.
Reverse *string `json:"reverse,omitempty"`
// IsIPv6: if true, creates a Flexible IP with an ipv6 address.
IsIPv6 bool `json:"is_ipv6"`
// Tags: list of tags for the IP.
Tags []string `json:"tags"`
}
// ZonedAPICreateLBRequest: zoned api create lb request.
type ZonedAPICreateLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Deprecated: OrganizationID: scaleway Organization to create the Load Balancer in.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: scaleway Project to create the Load Balancer in.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Name: name for the Load Balancer.
Name string `json:"name"`
// Description: description for the Load Balancer.
Description string `json:"description"`
// Deprecated: IPID: ID of an existing flexible IP address to attach to the Load Balancer.
IPID *string `json:"ip_id,omitempty"`
// AssignFlexibleIP: defines whether to automatically assign a flexible public IP to the Load Balancer. Default value is `true` (assign).
AssignFlexibleIP *bool `json:"assign_flexible_ip,omitempty"`
// AssignFlexibleIPv6: defines whether to automatically assign a flexible public IPv6 to the Load Balancer. Default value is `false` (do not assign).
AssignFlexibleIPv6 *bool `json:"assign_flexible_ipv6,omitempty"`
// IPIDs: list of IP IDs to attach to the Load Balancer.
IPIDs []string `json:"ip_ids"`
// Tags: list of tags for the Load Balancer.
Tags []string `json:"tags"`
// Type: load Balancer commercial offer type. Use the Load Balancer types endpoint to retrieve a list of available offer types.
Type string `json:"type"`
// SslCompatibilityLevel: determines the minimal SSL version which needs to be supported on the client side, in an SSL/TLS offloading context. Intermediate is suitable for general-purpose servers with a variety of clients, recommended for almost all systems. Modern is suitable for services with clients that support TLS 1.3 and do not need backward compatibility. Old is compatible with a small number of very old clients and should be used only as a last resort.
// Default value: ssl_compatibility_level_unknown
SslCompatibilityLevel SSLCompatibilityLevel `json:"ssl_compatibility_level"`
}
// ZonedAPICreateRouteRequest: zoned api create route request.
type ZonedAPICreateRouteRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: ID of the source frontend to create the route on.
FrontendID string `json:"frontend_id"`
// BackendID: ID of the target backend for the route.
BackendID string `json:"backend_id"`
// Match: object defining the match condition for a route to be applied. If an incoming client session matches the specified condition (i.e. it has a matching SNI value or HTTP Host header value), it will be passed to the target backend.
Match *RouteMatch `json:"match,omitempty"`
}
// ZonedAPICreateSubscriberRequest: Create a new alert subscriber (webhook or email).
type ZonedAPICreateSubscriberRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: subscriber name.
Name string `json:"name"`
// EmailConfig: email address configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
EmailConfig *SubscriberEmailConfig `json:"email_config,omitempty"`
// WebhookConfig: webHook URI configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
WebhookConfig *SubscriberWebhookConfig `json:"webhook_config,omitempty"`
// Deprecated: OrganizationID: organization ID to create the subscriber in.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID to create the subscriber in.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
}
// ZonedAPIDeleteACLRequest: zoned api delete acl request.
type ZonedAPIDeleteACLRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
}
// ZonedAPIDeleteBackendRequest: zoned api delete backend request.
type ZonedAPIDeleteBackendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: ID of the backend to delete.
BackendID string `json:"-"`
}
// ZonedAPIDeleteCertificateRequest: zoned api delete certificate request.
type ZonedAPIDeleteCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
}
// ZonedAPIDeleteFrontendRequest: zoned api delete frontend request.
type ZonedAPIDeleteFrontendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: ID of the frontend to delete.
FrontendID string `json:"-"`
}
// ZonedAPIDeleteLBRequest: zoned api delete lb request.
type ZonedAPIDeleteLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: ID of the Load Balancer to delete.
LBID string `json:"-"`
// ReleaseIP: defines whether the Load Balancer's flexible IP should be deleted. Set to true to release the flexible IP, or false to keep it available in your account for future Load Balancers.
ReleaseIP bool `json:"release_ip"`
}
// ZonedAPIDeleteRouteRequest: zoned api delete route request.
type ZonedAPIDeleteRouteRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// ZonedAPIDeleteSubscriberRequest: zoned api delete subscriber request.
type ZonedAPIDeleteSubscriberRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
}
// ZonedAPIDetachPrivateNetworkRequest: zoned api detach private network request.
type ZonedAPIDetachPrivateNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load balancer ID.
LBID string `json:"-"`
// PrivateNetworkID: set your instance private network id.
PrivateNetworkID string `json:"-"`
}
// ZonedAPIGetACLRequest: zoned api get acl request.
type ZonedAPIGetACLRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
}
// ZonedAPIGetBackendRequest: zoned api get backend request.
type ZonedAPIGetBackendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
}
// ZonedAPIGetCertificateRequest: zoned api get certificate request.
type ZonedAPIGetCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
}
// ZonedAPIGetFrontendRequest: zoned api get frontend request.
type ZonedAPIGetFrontendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: frontend ID.
FrontendID string `json:"-"`
}
// ZonedAPIGetIPRequest: zoned api get ip request.
type ZonedAPIGetIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
}
// ZonedAPIGetLBRequest: zoned api get lb request.
type ZonedAPIGetLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
}
// ZonedAPIGetLBStatsRequest: Get Load Balancer stats.
type ZonedAPIGetLBStatsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// BackendID: ID of the backend.
BackendID *string `json:"backend_id,omitempty"`
}
// ZonedAPIGetRouteRequest: zoned api get route request.
type ZonedAPIGetRouteRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// ZonedAPIGetSubscriberRequest: zoned api get subscriber request.
type ZonedAPIGetSubscriberRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
}
// ZonedAPIListACLsRequest: zoned api list ac ls request.
type ZonedAPIListACLsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: frontend ID (ACLs attached to this frontend will be returned in the response).
FrontendID string `json:"-"`
// OrderBy: sort order of ACLs in the response.
// Default value: created_at_asc
OrderBy ListACLRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of ACLs to return.
PageSize *uint32 `json:"-"`
// Name: ACL name to filter for.
Name *string `json:"-"`
}
// ZonedAPIListBackendStatsRequest: zoned api list backend stats request.
type ZonedAPIListBackendStatsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of items to return.
PageSize *uint32 `json:"-"`
// BackendID: ID of the backend.
BackendID *string `json:"-"`
}
// ZonedAPIListBackendsRequest: zoned api list backends request.
type ZonedAPIListBackendsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name of the backend to filter for.
Name *string `json:"-"`
// OrderBy: sort order of backends in the response.
// Default value: created_at_asc
OrderBy ListBackendsRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of backends to return.
PageSize *uint32 `json:"-"`
}
// ZonedAPIListCertificatesRequest: zoned api list certificates request.
type ZonedAPIListCertificatesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// OrderBy: sort order of certificates in the response.
// Default value: created_at_asc
OrderBy ListCertificatesRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of certificates to return.
PageSize *uint32 `json:"-"`
// Name: certificate name to filter for, only certificates of this name will be returned.
Name *string `json:"-"`
}
// ZonedAPIListFrontendsRequest: zoned api list frontends request.
type ZonedAPIListFrontendsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: name of the frontend to filter for.
Name *string `json:"-"`
// OrderBy: sort order of frontends in the response.
// Default value: created_at_asc
OrderBy ListFrontendsRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of frontends to return.
PageSize *uint32 `json:"-"`
}
// ZonedAPIListIPsRequest: zoned api list i ps request.
type ZonedAPIListIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: number of IP addresses to return.
PageSize *uint32 `json:"-"`
// IPAddress: IP address to filter for.
IPAddress *string `json:"-"`
// OrganizationID: organization ID to filter for, only Load Balancer IP addresses from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only Load Balancer IP addresses from this Project will be returned.
ProjectID *string `json:"-"`
// IPType: IP type to filter for.
// Default value: all
IPType ListIPsRequestIPType `json:"-"`
// Tags: tag to filter for, only IPs with one or more matching tags will be returned.
Tags []string `json:"-"`
}
// ZonedAPIListLBPrivateNetworksRequest: zoned api list lb private networks request.
type ZonedAPIListLBPrivateNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// OrderBy: sort order of Private Network objects in the response.
// Default value: created_at_asc
OrderBy ListPrivateNetworksRequestOrderBy `json:"-"`
// PageSize: number of objects to return.
PageSize *uint32 `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
}
// ZonedAPIListLBTypesRequest: zoned api list lb types request.
type ZonedAPIListLBTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of items to return.
PageSize *uint32 `json:"-"`
}
// ZonedAPIListLBsRequest: zoned api list l bs request.
type ZonedAPIListLBsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Name: load Balancer name to filter for.
Name *string `json:"-"`
// OrderBy: sort order of Load Balancers in the response.
// Default value: created_at_asc
OrderBy ListLBsRequestOrderBy `json:"-"`
// PageSize: number of Load Balancers to return.
PageSize *uint32 `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// OrganizationID: organization ID to filter for, only Load Balancers from this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for, only Load Balancers from this Project will be returned.
ProjectID *string `json:"-"`
// Tags: filter by tag, only Load Balancers with one or more matching tags will be returned.
Tags []string `json:"-"`
}
// ZonedAPIListRoutesRequest: zoned api list routes request.
type ZonedAPIListRoutesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order of routes in the response.
// Default value: created_at_asc
OrderBy ListRoutesRequestOrderBy `json:"-"`
// PageSize: the number of route objects to return.
PageSize *uint32 `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// FrontendID: frontend ID to filter for, only Routes from this Frontend will be returned.
FrontendID *string `json:"-"`
}
// ZonedAPIListSubscriberRequest: zoned api list subscriber request.
type ZonedAPIListSubscriberRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: sort order of subscribers in the response.
// Default value: created_at_asc
OrderBy ListSubscriberRequestOrderBy `json:"-"`
// Page: the page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: the number of items to return.
PageSize *uint32 `json:"-"`
// Name: subscriber name to search for.
Name *string `json:"-"`
// OrganizationID: filter subscribers by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter subscribers by Project ID.
ProjectID *string `json:"-"`
}
// ZonedAPIMigrateLBRequest: zoned api migrate lb request.
type ZonedAPIMigrateLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Type: load Balancer type to migrate to (use the List all Load Balancer offer types endpoint to get a list of available offer types).
Type string `json:"type"`
}
// ZonedAPIReleaseIPRequest: zoned api release ip request.
type ZonedAPIReleaseIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
}
// ZonedAPIRemoveBackendServersRequest: zoned api remove backend servers request.
type ZonedAPIRemoveBackendServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses to remove from backend servers.
ServerIP []string `json:"server_ip"`
}
// ZonedAPISetACLsRequest: zoned api set ac ls request.
type ZonedAPISetACLsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: frontend ID.
FrontendID string `json:"-"`
// ACLs: list of ACLs for this frontend. Any other existing ACLs on this frontend will be removed.
ACLs []*ACLSpec `json:"acls"`
}
// ZonedAPISetBackendServersRequest: zoned api set backend servers request.
type ZonedAPISetBackendServersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// ServerIP: list of IP addresses for backend servers. Any other existing backend servers will be removed.
ServerIP []string `json:"server_ip"`
}
// ZonedAPISubscribeToLBRequest: zoned api subscribe to lb request.
type ZonedAPISubscribeToLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"subscriber_id"`
}
// ZonedAPIUnsubscribeFromLBRequest: zoned api unsubscribe from lb request.
type ZonedAPIUnsubscribeFromLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
}
// ZonedAPIUpdateACLRequest: zoned api update acl request.
type ZonedAPIUpdateACLRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ACLID: ACL ID.
ACLID string `json:"-"`
// Name: ACL name.
Name string `json:"name"`
// Action: action to take when incoming traffic matches an ACL filter.
Action *ACLAction `json:"action"`
// Match: ACL match filter object. One of `ip_subnet` or `http_filter` & `http_filter_value` are required.
Match *ACLMatch `json:"match,omitempty"`
// Index: priority of this ACL (ACLs are applied in ascending order, 0 is the first ACL executed).
Index int32 `json:"index"`
// Description: ACL description.
Description *string `json:"description,omitempty"`
}
// ZonedAPIUpdateBackendRequest: zoned api update backend request.
type ZonedAPIUpdateBackendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// Name: backend name.
Name string `json:"name"`
// ForwardProtocol: protocol to be used by the backend when forwarding traffic to backend servers.
// Default value: tcp
ForwardProtocol Protocol `json:"forward_protocol"`
// ForwardPort: port to be used by the backend when forwarding traffic to backend servers.
ForwardPort int32 `json:"forward_port"`
// ForwardPortAlgorithm: load balancing algorithm to be used when determining which backend server to forward new traffic to.
// Default value: roundrobin
ForwardPortAlgorithm ForwardPortAlgorithm `json:"forward_port_algorithm"`
// StickySessions: defines whether to activate sticky sessions (binding a particular session to a particular backend server) and the method to use if so. None disables sticky sessions. Cookie-based uses an HTTP cookie to stick a session to a backend server. Table-based uses the source (client) IP address to stick a session to a backend server.
// Default value: none
StickySessions StickySessionsType `json:"sticky_sessions"`
// StickySessionsCookieName: cookie name for cookie-based sticky sessions.
StickySessionsCookieName string `json:"sticky_sessions_cookie_name"`
// Deprecated: SendProxyV2: deprecated in favor of proxy_protocol field.
SendProxyV2 *bool `json:"send_proxy_v2,omitempty"`
// TimeoutServer: maximum allowed time for a backend server to process a request.
TimeoutServer *time.Duration `json:"timeout_server,omitempty"`
// TimeoutConnect: maximum allowed time for establishing a connection to a backend server.
TimeoutConnect *time.Duration `json:"timeout_connect,omitempty"`
// TimeoutTunnel: maximum allowed tunnel inactivity time after Websocket is established (takes precedence over client and server timeout).
TimeoutTunnel *time.Duration `json:"timeout_tunnel,omitempty"`
// OnMarkedDownAction: action to take when a backend server is marked as down.
// Default value: on_marked_down_action_none
OnMarkedDownAction OnMarkedDownAction `json:"on_marked_down_action"`
// ProxyProtocol: protocol to use between the Load Balancer and backend servers. Allows the backend servers to be informed of the client's real IP address. The PROXY protocol must be supported by the backend servers' software.
// Default value: proxy_protocol_unknown
ProxyProtocol ProxyProtocol `json:"proxy_protocol"`
// FailoverHost: scaleway Object Storage bucket website to be served as failover if all backend servers are down, e.g. failover-website.s3-website.fr-par.scw.cloud.
FailoverHost *string `json:"failover_host,omitempty"`
// SslBridging: defines whether to enable SSL bridging between the Load Balancer and backend servers.
SslBridging *bool `json:"ssl_bridging,omitempty"`
// IgnoreSslServerVerify: defines whether the server certificate verification should be ignored.
IgnoreSslServerVerify *bool `json:"ignore_ssl_server_verify,omitempty"`
// RedispatchAttemptCount: whether to use another backend server on each attempt.
RedispatchAttemptCount *int32 `json:"redispatch_attempt_count,omitempty"`
// MaxRetries: number of retries when a backend server connection failed.
MaxRetries *int32 `json:"max_retries,omitempty"`
// MaxConnections: maximum number of connections allowed per backend server.
MaxConnections *int32 `json:"max_connections,omitempty"`
// TimeoutQueue: maximum time for a request to be left pending in queue when `max_connections` is reached.
TimeoutQueue *scw.Duration `json:"timeout_queue,omitempty"`
}
func (m *ZonedAPIUpdateBackendRequest) UnmarshalJSON(b []byte) error {
type tmpType ZonedAPIUpdateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = ZonedAPIUpdateBackendRequest(tmp.tmpType)
m.TimeoutServer = tmp.TmpTimeoutServer.Standard()
m.TimeoutConnect = tmp.TmpTimeoutConnect.Standard()
m.TimeoutTunnel = tmp.TmpTimeoutTunnel.Standard()
return nil
}
func (m ZonedAPIUpdateBackendRequest) MarshalJSON() ([]byte, error) {
type tmpType ZonedAPIUpdateBackendRequest
tmp := struct {
tmpType
TmpTimeoutServer *marshaler.Duration `json:"timeout_server,omitempty"`
TmpTimeoutConnect *marshaler.Duration `json:"timeout_connect,omitempty"`
TmpTimeoutTunnel *marshaler.Duration `json:"timeout_tunnel,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutServer: marshaler.NewDuration(m.TimeoutServer),
TmpTimeoutConnect: marshaler.NewDuration(m.TimeoutConnect),
TmpTimeoutTunnel: marshaler.NewDuration(m.TimeoutTunnel),
}
return json.Marshal(tmp)
}
// ZonedAPIUpdateCertificateRequest: zoned api update certificate request.
type ZonedAPIUpdateCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// CertificateID: certificate ID.
CertificateID string `json:"-"`
// Name: certificate name.
Name string `json:"name"`
}
// ZonedAPIUpdateFrontendRequest: zoned api update frontend request.
type ZonedAPIUpdateFrontendRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// FrontendID: frontend ID.
FrontendID string `json:"-"`
// Name: frontend name.
Name string `json:"name"`
// InboundPort: port the frontend should listen on.
InboundPort int32 `json:"inbound_port"`
// BackendID: backend ID (ID of the backend the frontend should pass traffic to).
BackendID string `json:"backend_id"`
// TimeoutClient: maximum allowed inactivity time on the client side.
TimeoutClient *time.Duration `json:"timeout_client,omitempty"`
// Deprecated: CertificateID: certificate ID, deprecated in favor of certificate_ids array.
CertificateID *string `json:"certificate_id,omitempty"`
// CertificateIDs: list of SSL/TLS certificate IDs to bind to the frontend.
CertificateIDs *[]string `json:"certificate_ids,omitempty"`
// EnableHTTP3: defines whether to enable HTTP/3 protocol on the frontend.
EnableHTTP3 bool `json:"enable_http3"`
}
func (m *ZonedAPIUpdateFrontendRequest) UnmarshalJSON(b []byte) error {
type tmpType ZonedAPIUpdateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = ZonedAPIUpdateFrontendRequest(tmp.tmpType)
m.TimeoutClient = tmp.TmpTimeoutClient.Standard()
return nil
}
func (m ZonedAPIUpdateFrontendRequest) MarshalJSON() ([]byte, error) {
type tmpType ZonedAPIUpdateFrontendRequest
tmp := struct {
tmpType
TmpTimeoutClient *marshaler.Duration `json:"timeout_client,omitempty"`
}{
tmpType: tmpType(m),
TmpTimeoutClient: marshaler.NewDuration(m.TimeoutClient),
}
return json.Marshal(tmp)
}
// ZonedAPIUpdateHealthCheckRequest: zoned api update health check request.
type ZonedAPIUpdateHealthCheckRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// BackendID: backend ID.
BackendID string `json:"-"`
// Port: port to use for the backend server health check.
Port int32 `json:"port"`
// CheckDelay: time to wait between two consecutive health checks.
CheckDelay *time.Duration `json:"check_delay,omitempty"`
// CheckTimeout: maximum time a backend server has to reply to the health check.
CheckTimeout *time.Duration `json:"check_timeout,omitempty"`
// CheckMaxRetries: number of consecutive unsuccessful health checks after which the server will be considered dead.
CheckMaxRetries int32 `json:"check_max_retries"`
// CheckSendProxy: defines whether proxy protocol should be activated for the health check.
CheckSendProxy bool `json:"check_send_proxy"`
// TCPConfig: object to configure a basic TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
TCPConfig *HealthCheckTCPConfig `json:"tcp_config,omitempty"`
// MysqlConfig: object to configure a MySQL health check. The check requires MySQL >=3.22 or <9.0. For older or newer versions, use a TCP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
MysqlConfig *HealthCheckMysqlConfig `json:"mysql_config,omitempty"`
// PgsqlConfig: object to configure a PostgreSQL health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
PgsqlConfig *HealthCheckPgsqlConfig `json:"pgsql_config,omitempty"`
// LdapConfig: object to configure an LDAP health check. The response is analyzed to find the LDAPv3 response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
LdapConfig *HealthCheckLdapConfig `json:"ldap_config,omitempty"`
// RedisConfig: object to configure a Redis health check. The response is analyzed to find the +PONG response message.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
RedisConfig *HealthCheckRedisConfig `json:"redis_config,omitempty"`
// HTTPConfig: object to configure an HTTP health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPConfig *HealthCheckHTTPConfig `json:"http_config,omitempty"`
// HTTPSConfig: object to configure an HTTPS health check.
// Precisely one of TCPConfig, MysqlConfig, PgsqlConfig, LdapConfig, RedisConfig, HTTPConfig, HTTPSConfig must be set.
HTTPSConfig *HealthCheckHTTPSConfig `json:"https_config,omitempty"`
// TransientCheckDelay: time to wait between two consecutive health checks when a backend server is in a transient state (going UP or DOWN).
TransientCheckDelay *scw.Duration `json:"transient_check_delay,omitempty"`
}
func (m *ZonedAPIUpdateHealthCheckRequest) UnmarshalJSON(b []byte) error {
type tmpType ZonedAPIUpdateHealthCheckRequest
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay,omitempty"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout,omitempty"`
}{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*m = ZonedAPIUpdateHealthCheckRequest(tmp.tmpType)
m.CheckDelay = tmp.TmpCheckDelay.Standard()
m.CheckTimeout = tmp.TmpCheckTimeout.Standard()
return nil
}
func (m ZonedAPIUpdateHealthCheckRequest) MarshalJSON() ([]byte, error) {
type tmpType ZonedAPIUpdateHealthCheckRequest
tmp := struct {
tmpType
TmpCheckDelay *marshaler.Duration `json:"check_delay,omitempty"`
TmpCheckTimeout *marshaler.Duration `json:"check_timeout,omitempty"`
}{
tmpType: tmpType(m),
TmpCheckDelay: marshaler.NewDuration(m.CheckDelay),
TmpCheckTimeout: marshaler.NewDuration(m.CheckTimeout),
}
return json.Marshal(tmp)
}
// ZonedAPIUpdateIPRequest: zoned api update ip request.
type ZonedAPIUpdateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: IP address ID.
IPID string `json:"-"`
// Reverse: reverse DNS (domain name) for the IP address.
Reverse *string `json:"reverse,omitempty"`
// LBID: ID of the server on which to attach the flexible IP.
LBID *string `json:"lb_id,omitempty"`
// Tags: list of tags for the IP.
Tags *[]string `json:"tags,omitempty"`
}
// ZonedAPIUpdateLBRequest: zoned api update lb request.
type ZonedAPIUpdateLBRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// LBID: load Balancer ID.
LBID string `json:"-"`
// Name: load Balancer name.
Name string `json:"name"`
// Description: load Balancer description.
Description string `json:"description"`
// Tags: list of tags for the Load Balancer.
Tags []string `json:"tags"`
// SslCompatibilityLevel: determines the minimal SSL version which needs to be supported on the client side, in an SSL/TLS offloading context. Intermediate is suitable for general-purpose servers with a variety of clients, recommended for almost all systems. Modern is suitable for services with clients that support TLS 1.3 and don't need backward compatibility. Old is compatible with a small number of very old clients and should be used only as a last resort.
// Default value: ssl_compatibility_level_unknown
SslCompatibilityLevel SSLCompatibilityLevel `json:"ssl_compatibility_level"`
}
// ZonedAPIUpdateRouteRequest: zoned api update route request.
type ZonedAPIUpdateRouteRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
// BackendID: ID of the target backend for the route.
BackendID string `json:"backend_id"`
// Match: object defining the match condition for a route to be applied. If an incoming client session matches the specified condition (i.e. it has a matching SNI value or HTTP Host header value), it will be passed to the target backend.
Match *RouteMatch `json:"match,omitempty"`
}
// ZonedAPIUpdateSubscriberRequest: zoned api update subscriber request.
type ZonedAPIUpdateSubscriberRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// SubscriberID: subscriber ID.
SubscriberID string `json:"-"`
// Name: subscriber name.
Name string `json:"name"`
// EmailConfig: email address configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
EmailConfig *SubscriberEmailConfig `json:"email_config,omitempty"`
// WebhookConfig: webhook URI configuration.
// Precisely one of EmailConfig, WebhookConfig must be set.
WebhookConfig *SubscriberWebhookConfig `json:"webhook_config,omitempty"`
}
// This API allows you to manage your Scaleway Load Balancer services.
type ZonedAPI struct {
client *scw.Client
}
// NewZonedAPI returns a ZonedAPI object from a Scaleway client.
func NewZonedAPI(client *scw.Client) *ZonedAPI {
return &ZonedAPI{
client: client,
}
}
func (s *ZonedAPI) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// ListLBs: List all Load Balancers in the specified zone, for a Scaleway Organization or Scaleway Project. By default, the Load Balancers returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *ZonedAPI) ListLBs(req *ZonedAPIListLBsRequest, opts ...scw.RequestOption) (*ListLBsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs",
Query: query,
}
var resp ListLBsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateLB: Create a new Load Balancer. Note that the Load Balancer will be created without frontends or backends; these must be created separately via the dedicated endpoints.
func (s *ZonedAPI) CreateLB(req *ZonedAPICreateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lb")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetLB: Retrieve information about an existing Load Balancer, specified by its Load Balancer ID. Its full details, including name, status and IP address, are returned in the response object.
func (s *ZonedAPI) GetLB(req *ZonedAPIGetLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "",
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateLB: Update the parameters of an existing Load Balancer, specified by its Load Balancer ID. Note that the request type is PUT and not PATCH. You must set all parameters.
func (s *ZonedAPI) UpdateLB(req *ZonedAPIUpdateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteLB: Delete an existing Load Balancer, specified by its Load Balancer ID. Deleting a Load Balancer is permanent, and cannot be undone. The Load Balancer's flexible IP address can either be deleted with the Load Balancer, or kept in your account for future use.
func (s *ZonedAPI) DeleteLB(req *ZonedAPIDeleteLBRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "release_ip", req.ReleaseIP)
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// MigrateLB: Migrate an existing Load Balancer from one commercial type to another. Allows you to scale your Load Balancer up or down in terms of bandwidth or multi-cloud provision.
func (s *ZonedAPI) MigrateLB(req *ZonedAPIMigrateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/migrate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List the Load Balancer flexible IP addresses held in the account (filtered by Organization ID or Project ID). It is also possible to search for a specific IP address.
func (s *ZonedAPI) ListIPs(req *ZonedAPIListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "ip_address", req.IPAddress)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "ip_type", req.IPType)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIP: Create a new Load Balancer flexible IP address, in the specified Scaleway Project. This can be attached to new Load Balancers created in the future.
func (s *ZonedAPI) CreateIP(req *ZonedAPICreateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIP: Retrieve the full details of a Load Balancer flexible IP address.
func (s *ZonedAPI) GetIP(req *ZonedAPIGetIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ReleaseIP: Delete a Load Balancer flexible IP address. This action is irreversible, and cannot be undone.
func (s *ZonedAPI) ReleaseIP(req *ZonedAPIReleaseIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateIP: Update the reverse DNS of a Load Balancer flexible IP address.
func (s *ZonedAPI) UpdateIP(req *ZonedAPIUpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListBackends: List all the backends of a Load Balancer, specified by its Load Balancer ID. By default, results are returned in ascending order by the creation date of each backend. The response is an array of backend objects, containing full details of each one including their configuration parameters such as protocol, port and forwarding algorithm.
func (s *ZonedAPI) ListBackends(req *ZonedAPIListBackendsRequest, opts ...scw.RequestOption) (*ListBackendsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/backends",
Query: query,
}
var resp ListBackendsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateBackend: Create a new backend for a given Load Balancer, specifying its full configuration including protocol, port and forwarding algorithm.
func (s *ZonedAPI) CreateBackend(req *ZonedAPICreateBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lbb")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/backends",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetBackend: Get the full details of a given backend, specified by its backend ID. The response contains the backend's full configuration parameters including protocol, port and forwarding algorithm.
func (s *ZonedAPI) GetBackend(req *ZonedAPIGetBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateBackend: Update a backend of a given Load Balancer, specified by its backend ID. Note that the request type is PUT and not PATCH. You must set all parameters.
func (s *ZonedAPI) UpdateBackend(req *ZonedAPIUpdateBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteBackend: Delete a backend of a given Load Balancer, specified by its backend ID. This action is irreversible and cannot be undone.
func (s *ZonedAPI) DeleteBackend(req *ZonedAPIDeleteBackendRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AddBackendServers: For a given backend specified by its backend ID, add a set of backend servers (identified by their IP addresses) it should forward traffic to. These will be appended to any existing set of backend servers for this backend.
func (s *ZonedAPI) AddBackendServers(req *ZonedAPIAddBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RemoveBackendServers: For a given backend specified by its backend ID, remove the specified backend servers (identified by their IP addresses) so that it no longer forwards traffic to them.
func (s *ZonedAPI) RemoveBackendServers(req *ZonedAPIRemoveBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetBackendServers: For a given backend specified by its backend ID, define the set of backend servers (identified by their IP addresses) that it should forward traffic to. Any existing backend servers configured for this backend will be removed.
func (s *ZonedAPI) SetBackendServers(req *ZonedAPISetBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHealthCheck: Update the configuration of the health check performed by a given backend to verify the health of its backend servers, identified by its backend ID. Note that the request type is PUT and not PATCH. You must set all parameters.
func (s *ZonedAPI) UpdateHealthCheck(req *ZonedAPIUpdateHealthCheckRequest, opts ...scw.RequestOption) (*HealthCheck, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/backends/" + fmt.Sprint(req.BackendID) + "/healthcheck",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp HealthCheck
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFrontends: List all the frontends of a Load Balancer, specified by its Load Balancer ID. By default, results are returned in ascending order by the creation date of each frontend. The response is an array of frontend objects, containing full details of each one including the port they listen on and the backend they are attached to.
func (s *ZonedAPI) ListFrontends(req *ZonedAPIListFrontendsRequest, opts ...scw.RequestOption) (*ListFrontendsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/frontends",
Query: query,
}
var resp ListFrontendsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateFrontend: Create a new frontend for a given Load Balancer, specifying its configuration including the port it should listen on and the backend to attach it to.
func (s *ZonedAPI) CreateFrontend(req *ZonedAPICreateFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lbf")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/frontends",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFrontend: Get the full details of a given frontend, specified by its frontend ID. The response contains the frontend's full configuration parameters including the backend it is attached to, the port it listens on, and any certificates it has.
func (s *ZonedAPI) GetFrontend(req *ZonedAPIGetFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateFrontend: Update a given frontend, specified by its frontend ID. You can update configuration parameters including its name and the port it listens on. Note that the request type is PUT and not PATCH. You must set all parameters.
func (s *ZonedAPI) UpdateFrontend(req *ZonedAPIUpdateFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteFrontend: Delete a given frontend, specified by its frontend ID. This action is irreversible and cannot be undone.
func (s *ZonedAPI) DeleteFrontend(req *ZonedAPIDeleteFrontendRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListRoutes: List all routes for a given frontend. The response is an array of routes, each one with a specified backend to direct to if a certain condition is matched (based on the value of the SNI field or HTTP Host header).
func (s *ZonedAPI) ListRoutes(req *ZonedAPIListRoutesRequest, opts ...scw.RequestOption) (*ListRoutesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "frontend_id", req.FrontendID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/routes",
Query: query,
}
var resp ListRoutesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRoute: Create a new route on a given frontend. To configure a route, specify the backend to direct to if a certain condition is matched (based on the value of the SNI field or HTTP Host header).
func (s *ZonedAPI) CreateRoute(req *ZonedAPICreateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/routes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRoute: Retrieve information about an existing route, specified by its route ID. Its full details, origin frontend, target backend and match condition, are returned in the response object.
func (s *ZonedAPI) GetRoute(req *ZonedAPIGetRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRoute: Update the configuration of an existing route, specified by its route ID.
func (s *ZonedAPI) UpdateRoute(req *ZonedAPIUpdateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRoute: Delete an existing route, specified by its route ID. Deleting a route is permanent, and cannot be undone.
func (s *ZonedAPI) DeleteRoute(req *ZonedAPIDeleteRouteRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Deprecated: GetLBStats: Get usage statistics of a given Load Balancer.
func (s *ZonedAPI) GetLBStats(req *ZonedAPIGetLBStatsRequest, opts ...scw.RequestOption) (*LBStats, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "backend_id", req.BackendID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/stats",
Query: query,
}
var resp LBStats
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListBackendStats: List information about your backend servers, including their state and the result of their last health check.
func (s *ZonedAPI) ListBackendStats(req *ZonedAPIListBackendStatsRequest, opts ...scw.RequestOption) (*ListBackendStatsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "backend_id", req.BackendID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/backend-stats",
Query: query,
}
var resp ListBackendStatsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListACLs: List the ACLs for a given frontend, specified by its frontend ID. The response is an array of ACL objects, each one representing an ACL that denies or allows traffic based on certain conditions.
func (s *ZonedAPI) ListACLs(req *ZonedAPIListACLsRequest, opts ...scw.RequestOption) (*ListACLResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "/acls",
Query: query,
}
var resp ListACLResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateACL: Create a new ACL for a given frontend. Each ACL must have a name, an action to perform (allow or deny), and a match rule (the action is carried out when the incoming traffic matches the rule).
func (s *ZonedAPI) CreateACL(req *ZonedAPICreateACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("acl")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetACL: Get information for a particular ACL, specified by its ACL ID. The response returns full details of the ACL, including its name, action, match rule and frontend.
func (s *ZonedAPI) GetACL(req *ZonedAPIGetACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateACL: Update a particular ACL, specified by its ACL ID. You can update details including its name, action and match rule.
func (s *ZonedAPI) UpdateACL(req *ZonedAPIUpdateACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteACL: Delete an ACL, specified by its ACL ID. Deleting an ACL is irreversible and cannot be undone.
func (s *ZonedAPI) DeleteACL(req *ZonedAPIDeleteACLRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// SetACLs: For a given frontend specified by its frontend ID, define and add the complete set of ACLS for that frontend. Any existing ACLs on this frontend will be removed.
func (s *ZonedAPI) SetACLs(req *ZonedAPISetACLsRequest, opts ...scw.RequestOption) (*SetACLsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/frontends/" + fmt.Sprint(req.FrontendID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetACLsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateCertificate: Generate a new SSL/TLS certificate for a given Load Balancer. You can choose to create a Let's Encrypt certificate, or import a custom certificate.
func (s *ZonedAPI) CreateCertificate(req *ZonedAPICreateCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("certificate")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/certificates",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListCertificates: List all the SSL/TLS certificates on a given Load Balancer. The response is an array of certificate objects, which are by default listed in ascending order of creation date.
func (s *ZonedAPI) ListCertificates(req *ZonedAPIListCertificatesRequest, opts ...scw.RequestOption) (*ListCertificatesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/certificates",
Query: query,
}
var resp ListCertificatesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCertificate: Get information for a particular SSL/TLS certificate, specified by its certificate ID. The response returns full details of the certificate, including its type, main domain name, and alternative domain names.
func (s *ZonedAPI) GetCertificate(req *ZonedAPIGetCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return nil, errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCertificate: Update the name of a particular SSL/TLS certificate, specified by its certificate ID.
func (s *ZonedAPI) UpdateCertificate(req *ZonedAPIUpdateCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return nil, errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCertificate: Delete an SSL/TLS certificate, specified by its certificate ID. Deleting a certificate is irreversible and cannot be undone.
func (s *ZonedAPI) DeleteCertificate(req *ZonedAPIDeleteCertificateRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListLBTypes: List all the different commercial Load Balancer types. The response includes an array of offer types, each with a name, description, and information about its stock availability.
func (s *ZonedAPI) ListLBTypes(req *ZonedAPIListLBTypesRequest, opts ...scw.RequestOption) (*ListLBTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lb-types",
Query: query,
}
var resp ListLBTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSubscriber: Create a new subscriber, either with an email configuration or a webhook configuration, for a specified Scaleway Project.
func (s *ZonedAPI) CreateSubscriber(req *ZonedAPICreateSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/subscribers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSubscriber: Retrieve information about an existing subscriber, specified by its subscriber ID. Its full details, including name and email/webhook configuration, are returned in the response object.
func (s *ZonedAPI) GetSubscriber(req *ZonedAPIGetSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return nil, errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/subscribers/" + fmt.Sprint(req.SubscriberID) + "",
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSubscriber: List all subscribers to Load Balancer alerts. By default, returns all subscribers to Load Balancer alerts for the Organization associated with the authentication token used for the request.
func (s *ZonedAPI) ListSubscriber(req *ZonedAPIListSubscriberRequest, opts ...scw.RequestOption) (*ListSubscriberResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/subscribers",
Query: query,
}
var resp ListSubscriberResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSubscriber: Update the parameters of a given subscriber (e.g. name, webhook configuration, email configuration), specified by its subscriber ID.
func (s *ZonedAPI) UpdateSubscriber(req *ZonedAPIUpdateSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return nil, errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/subscribers/" + fmt.Sprint(req.SubscriberID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSubscriber: Delete an existing subscriber, specified by its subscriber ID. Deleting a subscriber is permanent, and cannot be undone.
func (s *ZonedAPI) DeleteSubscriber(req *ZonedAPIDeleteSubscriberRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lb/subscription/" + fmt.Sprint(req.SubscriberID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// SubscribeToLB: Subscribe an existing subscriber to alerts for a given Load Balancer.
func (s *ZonedAPI) SubscribeToLB(req *ZonedAPISubscribeToLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lb/" + fmt.Sprint(req.LBID) + "/subscribe",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnsubscribeFromLB: Unsubscribe a subscriber from alerts for a given Load Balancer. The subscriber is not deleted, and can be resubscribed in the future if necessary.
func (s *ZonedAPI) UnsubscribeFromLB(req *ZonedAPIUnsubscribeFromLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lb/" + fmt.Sprint(req.LBID) + "/unsubscribe",
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListLBPrivateNetworks: List the Private Networks attached to a given Load Balancer, specified by its Load Balancer ID. The response is an array of Private Network objects, giving information including the status, configuration, name and creation date of each Private Network.
func (s *ZonedAPI) ListLBPrivateNetworks(req *ZonedAPIListLBPrivateNetworksRequest, opts ...scw.RequestOption) (*ListLBPrivateNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks",
Query: query,
}
var resp ListLBPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachPrivateNetwork: Attach a specified Load Balancer to a specified Private Network, defining a static or DHCP configuration for the Load Balancer on the network.
func (s *ZonedAPI) AttachPrivateNetwork(req *ZonedAPIAttachPrivateNetworkRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/attach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachPrivateNetwork: Detach a specified Load Balancer from a specified Private Network.
func (s *ZonedAPI) DetachPrivateNetwork(req *ZonedAPIDetachPrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return errors.New("field LBID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/zones/" + fmt.Sprint(req.Zone) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/detach",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// This API allows you to manage your Load Balancers.
type API struct {
client *scw.Client
}
// Deprecated: NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListLBs: List load balancers.
func (s *API) ListLBs(req *ListLBsRequest, opts ...scw.RequestOption) (*ListLBsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs",
Query: query,
}
var resp ListLBsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateLB: Create a load balancer.
func (s *API) CreateLB(req *CreateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lb")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetLB: Get a load balancer.
func (s *API) GetLB(req *GetLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "",
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateLB: Update a load balancer.
func (s *API) UpdateLB(req *UpdateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteLB: Delete a load balancer.
func (s *API) DeleteLB(req *DeleteLBRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "release_ip", req.ReleaseIP)
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// MigrateLB: Migrate a load balancer.
func (s *API) MigrateLB(req *MigrateLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/migrate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List IPs.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "ip_address", req.IPAddress)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "ip_type", req.IPType)
parameter.AddToQuery(query, "tags", req.Tags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIP: Create an IP.
func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIP: Get an IP.
func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ReleaseIP: Delete an IP.
func (s *API) ReleaseIP(req *ReleaseIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateIP: Update an IP.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListBackends: List backends in a given load balancer.
func (s *API) ListBackends(req *ListBackendsRequest, opts ...scw.RequestOption) (*ListBackendsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/backends",
Query: query,
}
var resp ListBackendsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateBackend: Create a backend in a given load balancer.
func (s *API) CreateBackend(req *CreateBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lbb")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/backends",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetBackend: Get a backend in a given load balancer.
func (s *API) GetBackend(req *GetBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateBackend: Update a backend in a given load balancer.
func (s *API) UpdateBackend(req *UpdateBackendRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteBackend: Delete a backend in a given load balancer.
func (s *API) DeleteBackend(req *DeleteBackendRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// AddBackendServers: Add a set of servers in a given backend.
func (s *API) AddBackendServers(req *AddBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RemoveBackendServers: Remove a set of servers for a given backend.
func (s *API) RemoveBackendServers(req *RemoveBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetBackendServers: Define all servers in a given backend.
func (s *API) SetBackendServers(req *SetBackendServersRequest, opts ...scw.RequestOption) (*Backend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "/servers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Backend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHealthCheck: Update an health check for a given backend.
func (s *API) UpdateHealthCheck(req *UpdateHealthCheckRequest, opts ...scw.RequestOption) (*HealthCheck, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackendID) == "" {
return nil, errors.New("field BackendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/backends/" + fmt.Sprint(req.BackendID) + "/healthcheck",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp HealthCheck
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFrontends: List frontends in a given load balancer.
func (s *API) ListFrontends(req *ListFrontendsRequest, opts ...scw.RequestOption) (*ListFrontendsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/frontends",
Query: query,
}
var resp ListFrontendsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateFrontend: Create a frontend in a given load balancer.
func (s *API) CreateFrontend(req *CreateFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("lbf")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/frontends",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetFrontend: Get a frontend.
func (s *API) GetFrontend(req *GetFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateFrontend: Update a frontend.
func (s *API) UpdateFrontend(req *UpdateFrontendRequest, opts ...scw.RequestOption) (*Frontend, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Frontend
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteFrontend: Delete a frontend.
func (s *API) DeleteFrontend(req *DeleteFrontendRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/frontends/" + fmt.Sprint(req.FrontendID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListRoutes: List all backend redirections.
func (s *API) ListRoutes(req *ListRoutesRequest, opts ...scw.RequestOption) (*ListRoutesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "frontend_id", req.FrontendID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/routes",
Query: query,
}
var resp ListRoutesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRoute: Create a backend redirection.
func (s *API) CreateRoute(req *CreateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/routes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRoute: Get single backend redirection.
func (s *API) GetRoute(req *GetRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRoute: Edit a backend redirection.
func (s *API) UpdateRoute(req *UpdateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRoute: Delete a backend redirection.
func (s *API) DeleteRoute(req *DeleteRouteRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// Deprecated: GetLBStats: Get usage statistics of a given load balancer.
func (s *API) GetLBStats(req *GetLBStatsRequest, opts ...scw.RequestOption) (*LBStats, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "backend_id", req.BackendID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/stats",
Query: query,
}
var resp LBStats
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListBackendStats: List backend server statistics.
func (s *API) ListBackendStats(req *ListBackendStatsRequest, opts ...scw.RequestOption) (*ListBackendStatsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "backend_id", req.BackendID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/backend-stats",
Query: query,
}
var resp ListBackendStatsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListACLs: List ACL for a given frontend.
func (s *API) ListACLs(req *ListACLsRequest, opts ...scw.RequestOption) (*ListACLResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/frontends/" + fmt.Sprint(req.FrontendID) + "/acls",
Query: query,
}
var resp ListACLResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateACL: Create an ACL for a given frontend.
func (s *API) CreateACL(req *CreateACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("acl")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.FrontendID) == "" {
return nil, errors.New("field FrontendID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/frontends/" + fmt.Sprint(req.FrontendID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetACL: Get an ACL.
func (s *API) GetACL(req *GetACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateACL: Update an ACL.
func (s *API) UpdateACL(req *UpdateACLRequest, opts ...scw.RequestOption) (*ACL, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ACL
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteACL: Delete an ACL.
func (s *API) DeleteACL(req *DeleteACLRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateCertificate: Generate a new TLS certificate using Let's Encrypt or import your certificate.
func (s *API) CreateCertificate(req *CreateCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("certificate")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/certificates",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListCertificates: List all TLS certificates on a given load balancer.
func (s *API) ListCertificates(req *ListCertificatesRequest, opts ...scw.RequestOption) (*ListCertificatesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/certificates",
Query: query,
}
var resp ListCertificatesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCertificate: Get a TLS certificate.
func (s *API) GetCertificate(req *GetCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return nil, errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCertificate: Update a TLS certificate.
func (s *API) UpdateCertificate(req *UpdateCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return nil, errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Certificate
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCertificate: Delete a TLS certificate.
func (s *API) DeleteCertificate(req *DeleteCertificateRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.CertificateID) == "" {
return errors.New("field CertificateID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/certificates/" + fmt.Sprint(req.CertificateID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListLBTypes: List all load balancer offer type.
func (s *API) ListLBTypes(req *ListLBTypesRequest, opts ...scw.RequestOption) (*ListLBTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lb-types",
Query: query,
}
var resp ListLBTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSubscriber: Create a subscriber, webhook or email.
func (s *API) CreateSubscriber(req *CreateSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/subscribers",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSubscriber: Get a subscriber.
func (s *API) GetSubscriber(req *GetSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return nil, errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/subscribers/" + fmt.Sprint(req.SubscriberID) + "",
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSubscriber: List all subscriber.
func (s *API) ListSubscriber(req *ListSubscriberRequest, opts ...scw.RequestOption) (*ListSubscriberResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/subscribers",
Query: query,
}
var resp ListSubscriberResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSubscriber: Update a subscriber.
func (s *API) UpdateSubscriber(req *UpdateSubscriberRequest, opts ...scw.RequestOption) (*Subscriber, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return nil, errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/subscribers/" + fmt.Sprint(req.SubscriberID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Subscriber
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSubscriber: Delete a subscriber.
func (s *API) DeleteSubscriber(req *DeleteSubscriberRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SubscriberID) == "" {
return errors.New("field SubscriberID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lb/subscriber/" + fmt.Sprint(req.SubscriberID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// SubscribeToLB: Subscribe a subscriber to a given load balancer.
func (s *API) SubscribeToLB(req *SubscribeToLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lb/" + fmt.Sprint(req.LBID) + "/subscribe",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnsubscribeFromLB: Unsubscribe a subscriber from a given load balancer.
func (s *API) UnsubscribeFromLB(req *UnsubscribeFromLBRequest, opts ...scw.RequestOption) (*LB, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lb/" + fmt.Sprint(req.LBID) + "/unsubscribe",
}
var resp LB
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListLBPrivateNetworks: List attached private network of load balancer.
func (s *API) ListLBPrivateNetworks(req *ListLBPrivateNetworksRequest, opts ...scw.RequestOption) (*ListLBPrivateNetworksResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks",
Query: query,
}
var resp ListLBPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AttachPrivateNetwork: Add load balancer on instance private network.
func (s *API) AttachPrivateNetwork(req *AttachPrivateNetworkRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return nil, errors.New("field LBID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/attach",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DetachPrivateNetwork: Remove load balancer of private network.
func (s *API) DetachPrivateNetwork(req *DetachPrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.LBID) == "" {
return errors.New("field LBID cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/lb/v1/regions/" + fmt.Sprint(req.Region) + "/lbs/" + fmt.Sprint(req.LBID) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/detach",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/v1/lb_utils.go 0000664 0000000 0000000 00000016526 14747113137 0026116 0 ustar 00root root 0000000 0000000 package lb
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 2 * time.Second
defaultTimeout = 5 * time.Minute
)
// WaitForLBRequest is used by WaitForLb method.
type WaitForLBRequest struct {
LBID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForLb waits for the lb to be in a "terminal state" before returning.
// This function can be used to wait for a lb to be ready for example.
func (s *API) WaitForLb(req *WaitForLBRequest, opts ...scw.RequestOption) (*LB, error) {
return waitForLb(req.Timeout, req.RetryInterval, func() (*LB, error) {
return s.GetLB(&GetLBRequest{
Region: req.Region,
LBID: req.LBID,
}, opts...)
})
}
// ZonedAPIWaitForLBRequest is used by WaitForLb method.
type ZonedAPIWaitForLBRequest struct {
LBID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForLb waits for the lb to be in a "terminal state" before returning.
// This function can be used to wait for a lb to be ready for example.
func (s *ZonedAPI) WaitForLb(req *ZonedAPIWaitForLBRequest, opts ...scw.RequestOption) (*LB, error) {
return waitForLb(req.Timeout, req.RetryInterval, func() (*LB, error) {
return s.GetLB(&ZonedAPIGetLBRequest{
Zone: req.Zone,
LBID: req.LBID,
}, opts...)
})
}
func waitForLb(timeout *time.Duration, retryInterval *time.Duration, getLB func() (*LB, error)) (*LB, error) {
t := defaultTimeout
if timeout != nil {
t = *timeout
}
r := defaultRetryInterval
if retryInterval != nil {
r = *retryInterval
}
terminalStatus := map[LBStatus]struct{}{
LBStatusReady: {},
LBStatusStopped: {},
LBStatusError: {},
LBStatusLocked: {},
}
lb, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := getLB()
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: t,
IntervalStrategy: async.LinearIntervalStrategy(r),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for lb failed")
}
return lb.(*LB), nil
}
// ZonedAPIWaitForLBInstancesRequest is used by WaitForLb method.
type ZonedAPIWaitForLBInstancesRequest struct {
LBID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForLbInstances waits for the lb to be in a "terminal state" and the attached instances before returning.
func (s *ZonedAPI) WaitForLbInstances(req *ZonedAPIWaitForLBInstancesRequest, opts ...scw.RequestOption) (*LB, error) {
return waitForLbInstances(req.Timeout, req.RetryInterval, func() (*LB, error) {
return s.GetLB(&ZonedAPIGetLBRequest{
Zone: req.Zone,
LBID: req.LBID,
}, opts...)
})
}
func waitForLbInstances(timeout *time.Duration, retryInterval *time.Duration, getLB func() (*LB, error)) (*LB, error) {
t := defaultTimeout
if timeout != nil {
t = *timeout
}
r := defaultRetryInterval
if retryInterval != nil {
r = *retryInterval
}
terminalLBStatus := map[LBStatus]struct{}{
LBStatusReady: {},
LBStatusStopped: {},
LBStatusError: {},
LBStatusLocked: {},
}
terminalInstanceStatus := map[InstanceStatus]struct{}{
InstanceStatusReady: {},
InstanceStatusStopped: {},
InstanceStatusError: {},
InstanceStatusLocked: {},
}
lb, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := getLB()
if err != nil {
return nil, false, err
}
_, isTerminal := terminalLBStatus[res.Status]
for _, i := range res.Instances {
_, isInstanceTerminal := terminalInstanceStatus[i.Status]
if !isInstanceTerminal {
return res, isTerminal, nil
}
}
return res, isTerminal, nil
},
Timeout: t,
IntervalStrategy: async.LinearIntervalStrategy(r),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for lb failed")
}
return lb.(*LB), nil
}
// ZonedAPIWaitForLBPNRequest is used by WaitForLBPN method.
type ZonedAPIWaitForLBPNRequest struct {
LBID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
func waitForPNLb(timeout *time.Duration, retryInterval *time.Duration, getPNs func() ([]*PrivateNetwork, error)) ([]*PrivateNetwork, error) {
t := defaultTimeout
if timeout != nil {
t = *timeout
}
r := defaultRetryInterval
if retryInterval != nil {
r = *retryInterval
}
terminalStatus := map[PrivateNetworkStatus]struct{}{
PrivateNetworkStatusReady: {},
PrivateNetworkStatusError: {},
}
pn, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
pns, err := getPNs()
for _, pn := range pns {
if err != nil {
return nil, false, err
}
// wait at the first not terminal state
_, isTerminal := terminalStatus[pn.Status]
if !isTerminal {
return pns, isTerminal, nil
}
}
return pns, true, nil
},
Timeout: t,
IntervalStrategy: async.LinearIntervalStrategy(r),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for attachment failed")
}
return pn.([]*PrivateNetwork), nil
}
// WaitForLBPN waits for the private_network attached status on a load balancer
// to be in a "terminal state" before returning.
// This function can be used to wait for an attached private_network to be ready for example.
func (s *ZonedAPI) WaitForLBPN(req *ZonedAPIWaitForLBPNRequest, opts ...scw.RequestOption) ([]*PrivateNetwork, error) {
return waitForPNLb(req.Timeout, req.RetryInterval, func() ([]*PrivateNetwork, error) {
lbPNs, err := s.ListLBPrivateNetworks(&ZonedAPIListLBPrivateNetworksRequest{
Zone: req.Zone,
LBID: req.LBID,
}, opts...)
if err != nil {
return nil, err
}
return lbPNs.PrivateNetwork, nil
})
}
// ZonedAPIWaitForLBCertificateRequest is used by WaitForLbCertificate method.
type ZonedAPIWaitForLBCertificateRequest struct {
CertID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForLBCertificate waits for the certificate to be in a "terminal state"
func (s *ZonedAPI) WaitForLBCertificate(req *ZonedAPIWaitForLBCertificateRequest, opts ...scw.RequestOption) (*Certificate, error) {
return waitForLBCertificate(req.Timeout, req.RetryInterval, func() (*Certificate, error) {
return s.GetCertificate(&ZonedAPIGetCertificateRequest{
Zone: req.Zone,
CertificateID: req.CertID,
}, opts...)
})
}
func waitForLBCertificate(timeout *time.Duration, retryInterval *time.Duration, getCertificate func() (*Certificate, error)) (*Certificate, error) {
t := defaultTimeout
if timeout != nil {
t = *timeout
}
r := defaultRetryInterval
if retryInterval != nil {
r = *retryInterval
}
terminalStatus := map[CertificateStatus]struct{}{
CertificateStatusError: {},
CertificateStatusReady: {},
}
crt, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := getCertificate()
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: t,
IntervalStrategy: async.LinearIntervalStrategy(r),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for lb failed")
}
return crt.(*Certificate), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0025575 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/lb/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000003503 14747113137 0027762 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/lb/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepLB(scwClient *scw.Client, zone scw.Zone) error {
lbAPI := lb.NewZonedAPI(scwClient)
logger.Warningf("sweeper: destroying the lbs in (%s)", zone)
listLBs, err := lbAPI.ListLBs(&lb.ZonedAPIListLBsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing lbs in (%s) in sweeper: %s", zone, err)
}
for _, l := range listLBs.LBs {
_, err := lbAPI.WaitForLbInstances(&lb.ZonedAPIWaitForLBInstancesRequest{
Zone: zone,
LBID: l.ID,
})
if err != nil {
return fmt.Errorf("error waiting for lb in sweeper: %s", err)
}
err = lbAPI.DeleteLB(&lb.ZonedAPIDeleteLBRequest{
LBID: l.ID,
ReleaseIP: true,
Zone: zone,
})
if err != nil {
return fmt.Errorf("error deleting lb in sweeper: %s", err)
}
}
return nil
}
func SweepIP(scwClient *scw.Client, zone scw.Zone) error {
lbAPI := lb.NewZonedAPI(scwClient)
logger.Warningf("sweeper: destroying the lb ips in zone (%s)", zone)
listIPs, err := lbAPI.ListIPs(&lb.ZonedAPIListIPsRequest{Zone: zone}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing lb ips in (%s) in sweeper: %s", zone, err)
}
for _, ip := range listIPs.IPs {
if ip.LBID == nil {
err := lbAPI.ReleaseIP(&lb.ZonedAPIReleaseIPRequest{
Zone: zone,
IPID: ip.ID,
})
if err != nil {
return fmt.Errorf("error deleting lb ip in sweeper: %s", err)
}
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&lb.ZonedAPI{}).Zones() {
err := SweepLB(scwClient, zone)
if err != nil {
return err
}
err = SweepIP(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/ 0000775 0000000 0000000 00000000000 14747113137 0025305 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/ 0000775 0000000 0000000 00000000000 14747113137 0025634 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/marketplace_sdk.go 0000664 0000000 0000000 00000046500 14747113137 0031321 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package marketplace provides methods and message types of the marketplace v2 API.
package marketplace
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListImagesRequestOrderBy string
const (
ListImagesRequestOrderByNameAsc = ListImagesRequestOrderBy("name_asc")
ListImagesRequestOrderByNameDesc = ListImagesRequestOrderBy("name_desc")
ListImagesRequestOrderByCreatedAtAsc = ListImagesRequestOrderBy("created_at_asc")
ListImagesRequestOrderByCreatedAtDesc = ListImagesRequestOrderBy("created_at_desc")
ListImagesRequestOrderByUpdatedAtAsc = ListImagesRequestOrderBy("updated_at_asc")
ListImagesRequestOrderByUpdatedAtDesc = ListImagesRequestOrderBy("updated_at_desc")
)
func (enum ListImagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListImagesRequestOrderBy) Values() []ListImagesRequestOrderBy {
return []ListImagesRequestOrderBy{
"name_asc",
"name_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListImagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListImagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListImagesRequestOrderBy(ListImagesRequestOrderBy(tmp).String())
return nil
}
type ListLocalImagesRequestOrderBy string
const (
ListLocalImagesRequestOrderByTypeAsc = ListLocalImagesRequestOrderBy("type_asc")
ListLocalImagesRequestOrderByTypeDesc = ListLocalImagesRequestOrderBy("type_desc")
ListLocalImagesRequestOrderByCreatedAtAsc = ListLocalImagesRequestOrderBy("created_at_asc")
ListLocalImagesRequestOrderByCreatedAtDesc = ListLocalImagesRequestOrderBy("created_at_desc")
)
func (enum ListLocalImagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "type_asc"
}
return string(enum)
}
func (enum ListLocalImagesRequestOrderBy) Values() []ListLocalImagesRequestOrderBy {
return []ListLocalImagesRequestOrderBy{
"type_asc",
"type_desc",
"created_at_asc",
"created_at_desc",
}
}
func (enum ListLocalImagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListLocalImagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListLocalImagesRequestOrderBy(ListLocalImagesRequestOrderBy(tmp).String())
return nil
}
type ListVersionsRequestOrderBy string
const (
ListVersionsRequestOrderByCreatedAtAsc = ListVersionsRequestOrderBy("created_at_asc")
ListVersionsRequestOrderByCreatedAtDesc = ListVersionsRequestOrderBy("created_at_desc")
)
func (enum ListVersionsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListVersionsRequestOrderBy) Values() []ListVersionsRequestOrderBy {
return []ListVersionsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListVersionsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListVersionsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListVersionsRequestOrderBy(ListVersionsRequestOrderBy(tmp).String())
return nil
}
type LocalImageType string
const (
// Unspecified image type.
LocalImageTypeUnknownType = LocalImageType("unknown_type")
// An image type that can be used to create volumes which are managed via the Instance API.
LocalImageTypeInstanceLocal = LocalImageType("instance_local")
// An image type that can be used to create volumes which are managed via the Scaleway Block Storage (SBS) API.
LocalImageTypeInstanceSbs = LocalImageType("instance_sbs")
)
func (enum LocalImageType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum LocalImageType) Values() []LocalImageType {
return []LocalImageType{
"unknown_type",
"instance_local",
"instance_sbs",
}
}
func (enum LocalImageType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LocalImageType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LocalImageType(LocalImageType(tmp).String())
return nil
}
// Category: category.
type Category struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}
// Image: image.
type Image struct {
// ID: UUID of this image.
ID string `json:"id"`
// Name: name of the image.
Name string `json:"name"`
// Description: text description of this image.
Description string `json:"description"`
// Logo: URL of this image's logo.
Logo string `json:"logo"`
// Categories: list of categories this image belongs to.
Categories []string `json:"categories"`
// CreatedAt: creation date of this image.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date of the last modification of this image.
UpdatedAt *time.Time `json:"updated_at"`
// ValidUntil: expiration date of this image.
ValidUntil *time.Time `json:"valid_until"`
// Label: typically an identifier for a distribution (ex. "ubuntu_focal").
// This label can be used in the image field of the server creation request.
Label string `json:"label"`
}
// LocalImage: local image.
type LocalImage struct {
// ID: version you will typically use to define an image in an API call.
ID string `json:"id"`
// CompatibleCommercialTypes: list of all commercial types that are compatible with this local image.
CompatibleCommercialTypes []string `json:"compatible_commercial_types"`
// Arch: supported architecture for this local image.
Arch string `json:"arch"`
// Zone: availability Zone where this local image is available.
Zone scw.Zone `json:"zone"`
// Label: this label can be used in the image field of the server creation request.
Label string `json:"label"`
// Type: type of this local image.
// Default value: unknown_type
Type LocalImageType `json:"type"`
}
// Version: version.
type Version struct {
// ID: UUID of this version.
ID string `json:"id"`
// Name: name of this version.
Name string `json:"name"`
// CreatedAt: creation date of this image version.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date of the last modification of this version.
UpdatedAt *time.Time `json:"updated_at"`
// PublishedAt: date this version was officially published.
PublishedAt *time.Time `json:"published_at"`
}
// GetCategoryRequest: get category request.
type GetCategoryRequest struct {
CategoryID string `json:"-"`
}
// GetImageRequest: get image request.
type GetImageRequest struct {
// ImageID: display the image name.
ImageID string `json:"-"`
}
// GetLocalImageRequest: get local image request.
type GetLocalImageRequest struct {
LocalImageID string `json:"-"`
}
// GetVersionRequest: get version request.
type GetVersionRequest struct {
VersionID string `json:"-"`
}
// ListCategoriesRequest: list categories request.
type ListCategoriesRequest struct {
PageSize *uint32 `json:"-"`
Page *int32 `json:"-"`
}
// ListCategoriesResponse: list categories response.
type ListCategoriesResponse struct {
Categories []*Category `json:"categories"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListCategoriesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListCategoriesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListCategoriesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Categories = append(r.Categories, results.Categories...)
r.TotalCount += uint32(len(results.Categories))
return uint32(len(results.Categories)), nil
}
// ListImagesRequest: list images request.
type ListImagesRequest struct {
// PageSize: a positive integer lower or equal to 100 to select the number of items to display.
PageSize *uint32 `json:"-"`
// Page: a positive integer to choose the page to display.
Page *int32 `json:"-"`
// OrderBy: ordering to use.
// Default value: name_asc
OrderBy ListImagesRequestOrderBy `json:"-"`
// Arch: choose for which machine architecture to return images.
Arch *string `json:"-"`
// Category: choose the category of images to get.
Category *string `json:"-"`
// IncludeEol: choose to include end-of-life images.
IncludeEol bool `json:"-"`
}
// ListImagesResponse: list images response.
type ListImagesResponse struct {
Images []*Image `json:"images"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListImagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Images = append(r.Images, results.Images...)
r.TotalCount += uint32(len(results.Images))
return uint32(len(results.Images)), nil
}
// ListLocalImagesRequest: list local images request.
type ListLocalImagesRequest struct {
// PageSize: a positive integer lower or equal to 100 to select the number of items to display.
PageSize *uint32 `json:"-"`
// Page: a positive integer to choose the page to display.
Page *int32 `json:"-"`
// OrderBy: ordering to use.
// Default value: type_asc
OrderBy ListLocalImagesRequestOrderBy `json:"-"`
// Zone: filter local images available on this Availability Zone.
Zone *scw.Zone `json:"-"`
// ImageID: filter by image id.
// Precisely one of ImageID, VersionID, ImageLabel must be set.
ImageID *string `json:"image_id,omitempty"`
// VersionID: filter by version id.
// Precisely one of ImageID, VersionID, ImageLabel must be set.
VersionID *string `json:"version_id,omitempty"`
// ImageLabel: filter by image label.
// Precisely one of ImageID, VersionID, ImageLabel must be set.
ImageLabel *string `json:"image_label,omitempty"`
// Type: filter by type.
// Default value: unknown_type
Type LocalImageType `json:"-"`
}
// ListLocalImagesResponse: list local images response.
type ListLocalImagesResponse struct {
LocalImages []*LocalImage `json:"local_images"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListLocalImagesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListLocalImagesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListLocalImagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.LocalImages = append(r.LocalImages, results.LocalImages...)
r.TotalCount += uint32(len(results.LocalImages))
return uint32(len(results.LocalImages)), nil
}
// ListVersionsRequest: list versions request.
type ListVersionsRequest struct {
ImageID string `json:"-"`
PageSize *uint32 `json:"-"`
Page *int32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListVersionsRequestOrderBy `json:"-"`
}
// ListVersionsResponse: list versions response.
type ListVersionsResponse struct {
Versions []*Version `json:"versions"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVersionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVersionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListVersionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Versions = append(r.Versions, results.Versions...)
r.TotalCount += uint32(len(results.Versions))
return uint32(len(results.Versions)), nil
}
// This API allows you to find available images for use when launching a Scaleway Instance.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// ListImages: List all available images on the marketplace, their UUID, CPU architecture and description.
func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "arch", req.Arch)
parameter.AddToQuery(query, "category", req.Category)
parameter.AddToQuery(query, "include_eol", req.IncludeEol)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/images",
Query: query,
}
var resp ListImagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetImage: Get detailed information about a marketplace image, specified by its `image_id` (UUID format).
func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*Image, error) {
var err error
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/images/" + fmt.Sprint(req.ImageID) + "",
}
var resp Image
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVersions: Get a list of all available version of an image, specified by its `image_id` (UUID format).
func (s *API) ListVersions(req *ListVersionsRequest, opts ...scw.RequestOption) (*ListVersionsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "image_id", req.ImageID)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/versions",
Query: query,
}
var resp ListVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetVersion: Get information such as the name, creation date, last update and published date for an image version specified by its `version_id` (UUID format).
func (s *API) GetVersion(req *GetVersionRequest, opts ...scw.RequestOption) (*Version, error) {
var err error
if fmt.Sprint(req.VersionID) == "" {
return nil, errors.New("field VersionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/versions/" + fmt.Sprint(req.VersionID) + "",
}
var resp Version
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListLocalImages: List information about local images in a specific Availability Zone, specified by its `image_id` (UUID format), `version_id` (UUID format) or `image_label`. Only one of these three parameters may be set.
func (s *API) ListLocalImages(req *ListLocalImagesRequest, opts ...scw.RequestOption) (*ListLocalImagesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
defaultZone, exist := s.client.GetDefaultZone()
if (req.Zone == nil || *req.Zone == "") && exist {
req.Zone = &defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "zone", req.Zone)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "image_id", req.ImageID)
parameter.AddToQuery(query, "version_id", req.VersionID)
parameter.AddToQuery(query, "image_label", req.ImageLabel)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/local-images",
Query: query,
}
var resp ListLocalImagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetLocalImage: Get detailed information about a local image, including compatible commercial types, supported architecture, labels and the Availability Zone of the image, specified by its `local_image_id` (UUID format).
func (s *API) GetLocalImage(req *GetLocalImageRequest, opts ...scw.RequestOption) (*LocalImage, error) {
var err error
if fmt.Sprint(req.LocalImageID) == "" {
return nil, errors.New("field LocalImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/local-images/" + fmt.Sprint(req.LocalImageID) + "",
}
var resp LocalImage
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListCategories: Get a list of all existing categories. The output can be paginated.
func (s *API) ListCategories(req *ListCategoriesRequest, opts ...scw.RequestOption) (*ListCategoriesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "page", req.Page)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/categories",
Query: query,
}
var resp ListCategoriesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCategory: Get information about a specific category of the marketplace catalog, specified by its `category_id` (UUID format).
func (s *API) GetCategory(req *GetCategoryRequest, opts ...scw.RequestOption) (*Category, error) {
var err error
if fmt.Sprint(req.CategoryID) == "" {
return nil, errors.New("field CategoryID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/marketplace/v2/categories/" + fmt.Sprint(req.CategoryID) + "",
}
var resp Category
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/marketplace_utils.go 0000664 0000000 0000000 00000004713 14747113137 0031700 0 ustar 00root root 0000000 0000000 package marketplace
import (
"strings"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// FindByLabel returns the first image with the given label in the image list
// Cannot find an image if it is not in the ListImagesResponse struct
// Use scw.WithAllPages when listing image to get all images
func (r *ListImagesResponse) FindByLabel(label string) *Image {
for _, image := range r.Images {
if image.Label == label {
return image
}
}
return nil
}
type GetImageByLabelRequest struct {
Label string
}
// GetImageByLabel returns the image with the given label
func (s *API) GetImageByLabel(req *GetImageByLabelRequest, opts ...scw.RequestOption) (*Image, error) {
listImagesRequest := &ListImagesRequest{}
opts = append(opts, scw.WithAllPages())
listImagesResponse, err := s.ListImages(listImagesRequest, opts...)
if err != nil {
return nil, err
}
image := listImagesResponse.FindByLabel(req.Label)
if image == nil {
return nil, errors.New("couldn't find a matching image for the given label (%s)", req.Label)
}
return image, nil
}
type GetLocalImageByLabelRequest struct {
ImageLabel string
Zone scw.Zone
CommercialType string
Type LocalImageType
}
// GetLocalImageByLabel returns the local image for the given image label in the given zone and compatible with given commercial type
func (s *API) GetLocalImageByLabel(req *GetLocalImageByLabelRequest, opts ...scw.RequestOption) (*LocalImage, error) {
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
req.CommercialType = strings.ToUpper(req.CommercialType)
resp, err := s.ListLocalImages(&ListLocalImagesRequest{
ImageLabel: scw.StringPtr(req.ImageLabel),
Zone: &req.Zone,
Type: req.Type,
}, opts...)
if err != nil {
return nil, err
}
for _, localImage := range resp.LocalImages {
if localImage.IsCompatible(req.CommercialType) {
return localImage, nil
}
}
return nil, errors.New("couldn't find a local image for the given zone (%s) and commercial type (%s)", req.Zone, req.CommercialType)
}
// IsCompatible returns true if a local image is compatible with the given instance type
// commercialType should be an uppercase string ex: DEV1-S
func (li *LocalImage) IsCompatible(commercialType string) bool {
for _, compatibleCommercialType := range li.CompatibleCommercialTypes {
if compatibleCommercialType == commercialType {
return true
}
}
return false
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/marketplace_utils_test.go 0000664 0000000 0000000 00000004104 14747113137 0032731 0 ustar 00root root 0000000 0000000 package marketplace
import (
"testing"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers"
"github.com/scaleway/scaleway-sdk-go/internal/testhelpers/httprecorder"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func TestGetImageByLabel(t *testing.T) {
client, r, err := httprecorder.CreateRecordedScwClient("go-vcr")
testhelpers.AssertNoError(t, err)
defer func() {
testhelpers.AssertNoError(t, r.Stop()) // Make sure recorder is stopped once done with it
}()
t.Run("matching input for GetLocalImageIDByLabel", func(t *testing.T) {
// Create SDK objects for Scaleway Instance product
marketplaceAPI := NewAPI(client)
image, err := marketplaceAPI.GetLocalImageByLabel(&GetLocalImageByLabelRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "DEV1-S",
ImageLabel: "ubuntu_focal",
})
testhelpers.AssertNoError(t, err)
// ubuntu_focal DEV1-S at par1: 68cf470e-6c35-4741-bbff-4ce788616461
testhelpers.Equals(t, "9c41e95b-add2-4ef8-b1b1-af8899748eda", image.ID)
})
t.Run("matching input for GetLocalImageIDByLabel with lowercase image label", func(t *testing.T) {
// Create SDK objects for Scaleway Instance product
marketplaceAPI := NewAPI(client)
image, err := marketplaceAPI.GetLocalImageByLabel(&GetLocalImageByLabelRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "dev1-s",
ImageLabel: "ubuntu_focal",
})
testhelpers.AssertNoError(t, err)
// ubuntu_focal DEV1-S at par1: 9c41e95b-add2-4ef8-b1b1-af8899748eda
testhelpers.Equals(t, "9c41e95b-add2-4ef8-b1b1-af8899748eda", image.ID)
})
t.Run("non-matching label for GetLocalImageIDByLabel", func(t *testing.T) {
// Create SDK objects for Scaleway Instance product
marketplaceAPI := NewAPI(client)
_, err := marketplaceAPI.GetLocalImageByLabel(&GetLocalImageByLabelRequest{
Zone: scw.ZoneFrPar1,
CommercialType: "DEV1-S",
ImageLabel: "foo-bar-image",
})
testhelpers.Assert(t, err != nil, "Should have error")
// testhelpers.Equals(t, "scaleway-sdk-go: couldn't find a matching image for the given label (foo-bar-image)", err.Error())
})
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/testdata/ 0000775 0000000 0000000 00000000000 14747113137 0027445 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/marketplace/v2/testdata/go-vcr.yaml 0000664 0000000 0000000 00000016302 14747113137 0031530 0 ustar 00root root 0000000 0000000 ---
version: 1
interactions:
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=ubuntu_focal&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"local_images":[{"id":"19f37e3e-d8c4-43cb-a739-7ccefec2a489","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"9c41e95b-add2-4ef8-b1b1-af8899748eda","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"1de03aca-1106-4152-bd36-f057c0cce9f1","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_sbs"},{"id":"60dd2959-89ce-4636-b54d-f1bb2ce9bde8","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_sbs"}],"total_count":4}'
headers:
Content-Length:
- "2328"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:25:02 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- 4e0ba02d-289f-4fb8-bb6d-42a1cf6e3f20
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=ubuntu_focal&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"local_images":[{"id":"19f37e3e-d8c4-43cb-a739-7ccefec2a489","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"9c41e95b-add2-4ef8-b1b1-af8899748eda","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_local"},{"id":"1de03aca-1106-4152-bd36-f057c0cce9f1","arch":"arm64","zone":"fr-par-1","compatible_commercial_types":["AMP2-C1","AMP2-C2","AMP2-C4","AMP2-C8","AMP2-C12","AMP2-C24","AMP2-C48","AMP2-C60","COPARM1-2C-8G","COPARM1-4C-16G","COPARM1-8C-32G","COPARM1-16C-64G","COPARM1-32C-128G"],"label":"ubuntu_focal","type":"instance_sbs"},{"id":"60dd2959-89ce-4636-b54d-f1bb2ce9bde8","arch":"x86_64","zone":"fr-par-1","compatible_commercial_types":["DEV1-L","DEV1-M","DEV1-S","DEV1-XL","GP1-L","GP1-M","GP1-S","GP1-XL","GP1-XS","START1-L","START1-M","START1-S","START1-XS","VC1L","VC1M","VC1S","X64-120GB","X64-15GB","X64-30GB","X64-60GB","ENT1-XXS","ENT1-XS","ENT1-S","ENT1-M","ENT1-L","ENT1-XL","ENT1-2XL","PRO2-XXS","PRO2-XS","PRO2-S","PRO2-M","PRO2-L","STARDUST1-S","PLAY2-MICRO","PLAY2-NANO","PLAY2-PICO","POP2-2C-8G","POP2-4C-16G","POP2-8C-32G","POP2-16C-64G","POP2-32C-128G","POP2-64C-256G","POP2-HM-2C-16G","POP2-HM-4C-32G","POP2-HM-8C-64G","POP2-HM-16C-128G","POP2-HM-32C-256G","POP2-HM-64C-512G","POP2-HC-2C-4G","POP2-HC-4C-8G","POP2-HC-8C-16G","POP2-HC-16C-32G","POP2-HC-32C-64G","POP2-HC-64C-128G"],"label":"ubuntu_focal","type":"instance_sbs"}],"total_count":4}'
headers:
Content-Length:
- "2328"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:25:02 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- e1436a38-a25d-4c68-93b7-879108cf308f
status: 200 OK
code: 200
duration: ""
- request:
body: ""
form: {}
headers:
User-Agent:
- scaleway-sdk-go/v1.0.0-beta.7+dev (go1.21.1; linux; amd64)
url: https://api.scaleway.com/marketplace/v2/local-images?image_label=foo-bar-image&order_by=type_asc&type=unknown_type&zone=fr-par-1
method: GET
response:
body: '{"message":"Not found","resource":"MarketplaceImage","resource_id":"foo-bar-image","type":"not_found"}'
headers:
Content-Length:
- "102"
Content-Security-Policy:
- default-src 'none'; frame-ancestors 'none'
Content-Type:
- application/json
Date:
- Fri, 05 Jul 2024 09:25:02 GMT
Server:
- Scaleway API Gateway (fr-par-3;edge01)
Strict-Transport-Security:
- max-age=63072000
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
X-Request-Id:
- f27c88fc-7cb7-4030-86be-3683efef5aaa
status: 404 Not Found
code: 404
duration: ""
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mnq/ 0000775 0000000 0000000 00000000000 14747113137 0023610 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mnq/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0025053 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mnq/v1beta1/mnq_sdk.go 0000664 0000000 0000000 00000156750 14747113137 0027054 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package mnq provides methods and message types of the mnq v1beta1 API.
package mnq
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListNatsAccountsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListNatsAccountsRequestOrderByCreatedAtAsc = ListNatsAccountsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListNatsAccountsRequestOrderByCreatedAtDesc = ListNatsAccountsRequestOrderBy("created_at_desc")
// Order by last update date (ascending chronological order).
ListNatsAccountsRequestOrderByUpdatedAtAsc = ListNatsAccountsRequestOrderBy("updated_at_asc")
// Order by last update date (descending chronological order).
ListNatsAccountsRequestOrderByUpdatedAtDesc = ListNatsAccountsRequestOrderBy("updated_at_desc")
// Order by name (ascending alphabetical order).
ListNatsAccountsRequestOrderByNameAsc = ListNatsAccountsRequestOrderBy("name_asc")
// Order by name (descending alphabetical order).
ListNatsAccountsRequestOrderByNameDesc = ListNatsAccountsRequestOrderBy("name_desc")
)
func (enum ListNatsAccountsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNatsAccountsRequestOrderBy) Values() []ListNatsAccountsRequestOrderBy {
return []ListNatsAccountsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListNatsAccountsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNatsAccountsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNatsAccountsRequestOrderBy(ListNatsAccountsRequestOrderBy(tmp).String())
return nil
}
type ListNatsCredentialsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListNatsCredentialsRequestOrderByCreatedAtAsc = ListNatsCredentialsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListNatsCredentialsRequestOrderByCreatedAtDesc = ListNatsCredentialsRequestOrderBy("created_at_desc")
// Order by last update date (ascending chronological order).
ListNatsCredentialsRequestOrderByUpdatedAtAsc = ListNatsCredentialsRequestOrderBy("updated_at_asc")
// Order by last update date (descending chronological order).
ListNatsCredentialsRequestOrderByUpdatedAtDesc = ListNatsCredentialsRequestOrderBy("updated_at_desc")
// Order by name (ascending alphabetical order).
ListNatsCredentialsRequestOrderByNameAsc = ListNatsCredentialsRequestOrderBy("name_asc")
// Order by name (descending alphabetical order).
ListNatsCredentialsRequestOrderByNameDesc = ListNatsCredentialsRequestOrderBy("name_desc")
)
func (enum ListNatsCredentialsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNatsCredentialsRequestOrderBy) Values() []ListNatsCredentialsRequestOrderBy {
return []ListNatsCredentialsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListNatsCredentialsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNatsCredentialsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNatsCredentialsRequestOrderBy(ListNatsCredentialsRequestOrderBy(tmp).String())
return nil
}
type ListSnsCredentialsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListSnsCredentialsRequestOrderByCreatedAtAsc = ListSnsCredentialsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListSnsCredentialsRequestOrderByCreatedAtDesc = ListSnsCredentialsRequestOrderBy("created_at_desc")
// Order by last update date (ascending chronological order).
ListSnsCredentialsRequestOrderByUpdatedAtAsc = ListSnsCredentialsRequestOrderBy("updated_at_asc")
// Order by last update date (descending chronological order).
ListSnsCredentialsRequestOrderByUpdatedAtDesc = ListSnsCredentialsRequestOrderBy("updated_at_desc")
// Order by name (ascending alphabetical order).
ListSnsCredentialsRequestOrderByNameAsc = ListSnsCredentialsRequestOrderBy("name_asc")
// Order by name (descending alphabetical order).
ListSnsCredentialsRequestOrderByNameDesc = ListSnsCredentialsRequestOrderBy("name_desc")
)
func (enum ListSnsCredentialsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSnsCredentialsRequestOrderBy) Values() []ListSnsCredentialsRequestOrderBy {
return []ListSnsCredentialsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListSnsCredentialsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSnsCredentialsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSnsCredentialsRequestOrderBy(ListSnsCredentialsRequestOrderBy(tmp).String())
return nil
}
type ListSqsCredentialsRequestOrderBy string
const (
// Order by creation date (ascending chronological order).
ListSqsCredentialsRequestOrderByCreatedAtAsc = ListSqsCredentialsRequestOrderBy("created_at_asc")
// Order by creation date (descending chronological order).
ListSqsCredentialsRequestOrderByCreatedAtDesc = ListSqsCredentialsRequestOrderBy("created_at_desc")
// Order by last update date (ascending chronological order).
ListSqsCredentialsRequestOrderByUpdatedAtAsc = ListSqsCredentialsRequestOrderBy("updated_at_asc")
// Order by last update date (descending chronological order).
ListSqsCredentialsRequestOrderByUpdatedAtDesc = ListSqsCredentialsRequestOrderBy("updated_at_desc")
// Order by name (ascending alphabetical order).
ListSqsCredentialsRequestOrderByNameAsc = ListSqsCredentialsRequestOrderBy("name_asc")
// Order by name (descending alphabetical order).
ListSqsCredentialsRequestOrderByNameDesc = ListSqsCredentialsRequestOrderBy("name_desc")
)
func (enum ListSqsCredentialsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSqsCredentialsRequestOrderBy) Values() []ListSqsCredentialsRequestOrderBy {
return []ListSqsCredentialsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListSqsCredentialsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSqsCredentialsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSqsCredentialsRequestOrderBy(ListSqsCredentialsRequestOrderBy(tmp).String())
return nil
}
type SnsInfoStatus string
const (
// Unknown status.
SnsInfoStatusUnknownStatus = SnsInfoStatus("unknown_status")
// Enabled status.
SnsInfoStatusEnabled = SnsInfoStatus("enabled")
// Disabled status.
SnsInfoStatusDisabled = SnsInfoStatus("disabled")
)
func (enum SnsInfoStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SnsInfoStatus) Values() []SnsInfoStatus {
return []SnsInfoStatus{
"unknown_status",
"enabled",
"disabled",
}
}
func (enum SnsInfoStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnsInfoStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnsInfoStatus(SnsInfoStatus(tmp).String())
return nil
}
type SqsInfoStatus string
const (
// Unknown status.
SqsInfoStatusUnknownStatus = SqsInfoStatus("unknown_status")
// Enabled status.
SqsInfoStatusEnabled = SqsInfoStatus("enabled")
// Disabled status.
SqsInfoStatusDisabled = SqsInfoStatus("disabled")
)
func (enum SqsInfoStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SqsInfoStatus) Values() []SqsInfoStatus {
return []SqsInfoStatus{
"unknown_status",
"enabled",
"disabled",
}
}
func (enum SqsInfoStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SqsInfoStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SqsInfoStatus(SqsInfoStatus(tmp).String())
return nil
}
// File: file.
type File struct {
// Name: file name.
Name string `json:"name"`
// Content: file content.
Content string `json:"content"`
}
// SnsPermissions: sns permissions.
type SnsPermissions struct {
// CanPublish: defines whether the credentials bearer can publish messages to the service (publish to Topics and Events topics).
CanPublish *bool `json:"can_publish"`
// CanReceive: defines whether the credentials bearer can receive messages from the service (configure subscriptions).
CanReceive *bool `json:"can_receive"`
// CanManage: defines whether the credentials bearer can manage the associated Topics and Events topics or subscriptions.
CanManage *bool `json:"can_manage"`
}
// SqsPermissions: sqs permissions.
type SqsPermissions struct {
// CanPublish: defines whether the credentials bearer can publish messages to the service (send messages to Queues queues).
CanPublish *bool `json:"can_publish"`
// CanReceive: defines whether the credentials bearer can receive messages from Queues queues.
CanReceive *bool `json:"can_receive"`
// CanManage: defines whether the credentials bearer can manage the associated Queues queues.
CanManage *bool `json:"can_manage"`
}
// NatsAccount: nats account.
type NatsAccount struct {
// ID: nATS account ID.
ID string `json:"id"`
// Name: nATS account name.
Name string `json:"name"`
// Endpoint: endpoint of the NATS service for this account.
Endpoint string `json:"endpoint"`
// ProjectID: project ID of the Project containing the NATS account.
ProjectID string `json:"project_id"`
// Region: region where the NATS account is deployed.
Region scw.Region `json:"region"`
// CreatedAt: nATS account creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: nATS account last modification date.
UpdatedAt *time.Time `json:"updated_at"`
}
// NatsCredentials: nats credentials.
type NatsCredentials struct {
// ID: ID of the credentials.
ID string `json:"id"`
// Name: name of the credentials.
Name string `json:"name"`
// NatsAccountID: nATS account containing the credentials.
NatsAccountID string `json:"nats_account_id"`
// CreatedAt: nATS credentials creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: nATS credentials last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Credentials: object containing the credentials file (Only returned by **Create Nats Credentials** call).
Credentials *File `json:"credentials"`
// Checksum: checksum of the credentials file.
Checksum string `json:"checksum"`
}
// SnsCredentials: sns credentials.
type SnsCredentials struct {
// ID: ID of the credentials.
ID string `json:"id"`
// Name: name of the credentials.
Name string `json:"name"`
// ProjectID: project ID of the Project containing the credentials.
ProjectID string `json:"project_id"`
// Region: region where the credentials exists.
Region scw.Region `json:"region"`
// CreatedAt: credentials creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: credentials last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// AccessKey: access key ID.
AccessKey string `json:"access_key"`
// SecretKey: secret key ID (Only returned by **Create Topics and Events Credentials** call).
SecretKey string `json:"secret_key"`
// SecretChecksum: checksum of the Secret key.
SecretChecksum string `json:"secret_checksum"`
// Permissions: permissions associated with these credentials.
Permissions *SnsPermissions `json:"permissions"`
}
// SqsCredentials: sqs credentials.
type SqsCredentials struct {
// ID: ID of the credentials.
ID string `json:"id"`
// Name: name of the credentials.
Name string `json:"name"`
// ProjectID: project ID of the Project containing the credentials.
ProjectID string `json:"project_id"`
// Region: region where the credentials exists.
Region scw.Region `json:"region"`
// CreatedAt: credentials creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: credentials last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// AccessKey: access key ID.
AccessKey string `json:"access_key"`
// SecretKey: secret key ID (Only returned by **Create Queues Credentials** call).
SecretKey string `json:"secret_key"`
// SecretChecksum: checksum of the Secret key.
SecretChecksum string `json:"secret_checksum"`
// Permissions: permissions associated with these credentials.
Permissions *SqsPermissions `json:"permissions"`
}
// ListNatsAccountsResponse: list nats accounts response.
type ListNatsAccountsResponse struct {
// TotalCount: total count of existing NATS accounts (matching any filters specified).
TotalCount uint64 `json:"total_count"`
// NatsAccounts: nATS accounts on this page.
NatsAccounts []*NatsAccount `json:"nats_accounts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNatsAccountsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNatsAccountsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListNatsAccountsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NatsAccounts = append(r.NatsAccounts, results.NatsAccounts...)
r.TotalCount += uint64(len(results.NatsAccounts))
return uint64(len(results.NatsAccounts)), nil
}
// ListNatsCredentialsResponse: list nats credentials response.
type ListNatsCredentialsResponse struct {
// TotalCount: total count of existing credentials (matching any filters specified).
TotalCount uint64 `json:"total_count"`
// NatsCredentials: credentials on this page.
NatsCredentials []*NatsCredentials `json:"nats_credentials"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNatsCredentialsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNatsCredentialsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListNatsCredentialsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NatsCredentials = append(r.NatsCredentials, results.NatsCredentials...)
r.TotalCount += uint64(len(results.NatsCredentials))
return uint64(len(results.NatsCredentials)), nil
}
// ListSnsCredentialsResponse: list sns credentials response.
type ListSnsCredentialsResponse struct {
// TotalCount: total count of existing credentials (matching any filters specified).
TotalCount uint64 `json:"total_count"`
// SnsCredentials: topics and Events credentials on this page.
SnsCredentials []*SnsCredentials `json:"sns_credentials"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnsCredentialsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnsCredentialsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSnsCredentialsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SnsCredentials = append(r.SnsCredentials, results.SnsCredentials...)
r.TotalCount += uint64(len(results.SnsCredentials))
return uint64(len(results.SnsCredentials)), nil
}
// ListSqsCredentialsResponse: list sqs credentials response.
type ListSqsCredentialsResponse struct {
// TotalCount: total count of existing credentials (matching any filters specified).
TotalCount uint64 `json:"total_count"`
// SqsCredentials: queues credentials on this page.
SqsCredentials []*SqsCredentials `json:"sqs_credentials"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSqsCredentialsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSqsCredentialsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSqsCredentialsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.SqsCredentials = append(r.SqsCredentials, results.SqsCredentials...)
r.TotalCount += uint64(len(results.SqsCredentials))
return uint64(len(results.SqsCredentials)), nil
}
// NatsAPICreateNatsAccountRequest: nats api create nats account request.
type NatsAPICreateNatsAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: nATS account name.
Name string `json:"name"`
// ProjectID: project containing the NATS account.
ProjectID string `json:"project_id"`
}
// NatsAPICreateNatsCredentialsRequest: nats api create nats credentials request.
type NatsAPICreateNatsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsAccountID: nATS account containing the credentials.
NatsAccountID string `json:"nats_account_id"`
// Name: name of the credentials.
Name string `json:"name"`
}
// NatsAPIDeleteNatsAccountRequest: nats api delete nats account request.
type NatsAPIDeleteNatsAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsAccountID: ID of the NATS account to delete.
NatsAccountID string `json:"-"`
}
// NatsAPIDeleteNatsCredentialsRequest: nats api delete nats credentials request.
type NatsAPIDeleteNatsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsCredentialsID: ID of the credentials to delete.
NatsCredentialsID string `json:"-"`
}
// NatsAPIGetNatsAccountRequest: nats api get nats account request.
type NatsAPIGetNatsAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsAccountID: ID of the NATS account to get.
NatsAccountID string `json:"-"`
}
// NatsAPIGetNatsCredentialsRequest: nats api get nats credentials request.
type NatsAPIGetNatsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsCredentialsID: ID of the credentials to get.
NatsCredentialsID string `json:"-"`
}
// NatsAPIListNatsAccountsRequest: nats api list nats accounts request.
type NatsAPIListNatsAccountsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: include only NATS accounts in this Project.
ProjectID *string `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of NATS accounts to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListNatsAccountsRequestOrderBy `json:"-"`
}
// NatsAPIListNatsCredentialsRequest: nats api list nats credentials request.
type NatsAPIListNatsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: include only NATS accounts in this Project.
ProjectID *string `json:"-"`
// NatsAccountID: include only credentials for this NATS account.
NatsAccountID *string `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of credentials to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListNatsCredentialsRequestOrderBy `json:"-"`
}
// NatsAPIUpdateNatsAccountRequest: nats api update nats account request.
type NatsAPIUpdateNatsAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NatsAccountID: ID of the NATS account to update.
NatsAccountID string `json:"-"`
// Name: nATS account name.
Name *string `json:"name,omitempty"`
}
// SnsAPIActivateSnsRequest: sns api activate sns request.
type SnsAPIActivateSnsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project on which to activate the Topics and Events service.
ProjectID string `json:"project_id"`
}
// SnsAPICreateSnsCredentialsRequest: sns api create sns credentials request.
type SnsAPICreateSnsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project containing the Topics and Events credentials.
ProjectID string `json:"project_id"`
// Name: name of the credentials.
Name string `json:"name"`
// Permissions: permissions associated with these credentials.
Permissions *SnsPermissions `json:"permissions,omitempty"`
}
// SnsAPIDeactivateSnsRequest: sns api deactivate sns request.
type SnsAPIDeactivateSnsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project on which to deactivate the Topics and Events service.
ProjectID string `json:"project_id"`
}
// SnsAPIDeleteSnsCredentialsRequest: sns api delete sns credentials request.
type SnsAPIDeleteSnsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnsCredentialsID: ID of the credentials to delete.
SnsCredentialsID string `json:"-"`
}
// SnsAPIGetSnsCredentialsRequest: sns api get sns credentials request.
type SnsAPIGetSnsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnsCredentialsID: ID of the Topics and Events credentials to get.
SnsCredentialsID string `json:"-"`
}
// SnsAPIGetSnsInfoRequest: sns api get sns info request.
type SnsAPIGetSnsInfoRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project to retrieve Topics and Events info from.
ProjectID string `json:"project_id"`
}
// SnsAPIListSnsCredentialsRequest: sns api list sns credentials request.
type SnsAPIListSnsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: include only Topics and Events credentials in this Project.
ProjectID *string `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of credentials to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListSnsCredentialsRequestOrderBy `json:"-"`
}
// SnsAPIUpdateSnsCredentialsRequest: sns api update sns credentials request.
type SnsAPIUpdateSnsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnsCredentialsID: ID of the Topics and Events credentials to update.
SnsCredentialsID string `json:"-"`
// Name: name of the credentials.
Name *string `json:"name,omitempty"`
// Permissions: permissions associated with these credentials.
Permissions *SnsPermissions `json:"permissions,omitempty"`
}
// SnsInfo: sns info.
type SnsInfo struct {
// ProjectID: project ID of the Project containing the service.
ProjectID string `json:"project_id"`
// Region: region of the service.
Region scw.Region `json:"region"`
// CreatedAt: topics and Events creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: topics and Events last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Status: topics and Events activation status.
// Default value: unknown_status
Status SnsInfoStatus `json:"status"`
// SnsEndpointURL: endpoint of the Topics and Events service for this region and project.
SnsEndpointURL string `json:"sns_endpoint_url"`
}
// SqsAPIActivateSqsRequest: sqs api activate sqs request.
type SqsAPIActivateSqsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project on which to activate the Queues service.
ProjectID string `json:"project_id"`
}
// SqsAPICreateSqsCredentialsRequest: sqs api create sqs credentials request.
type SqsAPICreateSqsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project containing the Queues credentials.
ProjectID string `json:"project_id"`
// Name: name of the credentials.
Name string `json:"name"`
// Permissions: permissions associated with these credentials.
Permissions *SqsPermissions `json:"permissions,omitempty"`
}
// SqsAPIDeactivateSqsRequest: sqs api deactivate sqs request.
type SqsAPIDeactivateSqsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project on which to deactivate the Queues service.
ProjectID string `json:"project_id"`
}
// SqsAPIDeleteSqsCredentialsRequest: sqs api delete sqs credentials request.
type SqsAPIDeleteSqsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SqsCredentialsID: ID of the credentials to delete.
SqsCredentialsID string `json:"-"`
}
// SqsAPIGetSqsCredentialsRequest: sqs api get sqs credentials request.
type SqsAPIGetSqsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SqsCredentialsID: ID of the Queues credentials to get.
SqsCredentialsID string `json:"-"`
}
// SqsAPIGetSqsInfoRequest: sqs api get sqs info request.
type SqsAPIGetSqsInfoRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: project to retrieve Queues info from.
ProjectID string `json:"project_id"`
}
// SqsAPIListSqsCredentialsRequest: sqs api list sqs credentials request.
type SqsAPIListSqsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: include only Queues credentials in this Project.
ProjectID *string `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: maximum number of credentials to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListSqsCredentialsRequestOrderBy `json:"-"`
}
// SqsAPIUpdateSqsCredentialsRequest: sqs api update sqs credentials request.
type SqsAPIUpdateSqsCredentialsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SqsCredentialsID: ID of the Queues credentials to update.
SqsCredentialsID string `json:"-"`
// Name: name of the credentials.
Name *string `json:"name,omitempty"`
// Permissions: permissions associated with these credentials.
Permissions *SqsPermissions `json:"permissions,omitempty"`
}
// SqsInfo: sqs info.
type SqsInfo struct {
// ProjectID: project ID of the Project containing the service.
ProjectID string `json:"project_id"`
// Region: region of the service.
Region scw.Region `json:"region"`
// CreatedAt: queues creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: queues last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Status: queues activation status.
// Default value: unknown_status
Status SqsInfoStatus `json:"status"`
// SqsEndpointURL: endpoint of the Queues service for this region and project.
SqsEndpointURL string `json:"sqs_endpoint_url"`
}
// This API allows you to manage Scaleway NATS accounts.
type NatsAPI struct {
client *scw.Client
}
// NewNatsAPI returns a NatsAPI object from a Scaleway client.
func NewNatsAPI(client *scw.Client) *NatsAPI {
return &NatsAPI{
client: client,
}
}
func (s *NatsAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms}
}
// CreateNatsAccount: Create a NATS account associated with a Project.
func (s *NatsAPI) CreateNatsAccount(req *NatsAPICreateNatsAccountRequest, opts ...scw.RequestOption) (*NatsAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("mnq")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-accounts",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp NatsAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNatsAccount: Delete a NATS account, specified by its NATS account ID. Note that deleting a NATS account is irreversible, and any credentials, streams, consumer and stored messages belonging to this NATS account will also be deleted.
func (s *NatsAPI) DeleteNatsAccount(req *NatsAPIDeleteNatsAccountRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NatsAccountID) == "" {
return errors.New("field NatsAccountID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-accounts/" + fmt.Sprint(req.NatsAccountID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateNatsAccount: Update the name of a NATS account, specified by its NATS account ID.
func (s *NatsAPI) UpdateNatsAccount(req *NatsAPIUpdateNatsAccountRequest, opts ...scw.RequestOption) (*NatsAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NatsAccountID) == "" {
return nil, errors.New("field NatsAccountID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-accounts/" + fmt.Sprint(req.NatsAccountID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp NatsAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNatsAccount: Retrieve information about an existing NATS account identified by its NATS account ID. Its full details, including name and endpoint, are returned in the response.
func (s *NatsAPI) GetNatsAccount(req *NatsAPIGetNatsAccountRequest, opts ...scw.RequestOption) (*NatsAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NatsAccountID) == "" {
return nil, errors.New("field NatsAccountID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-accounts/" + fmt.Sprint(req.NatsAccountID) + "",
}
var resp NatsAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNatsAccounts: List all NATS accounts in the specified region, for a Scaleway Organization or Project. By default, the NATS accounts returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *NatsAPI) ListNatsAccounts(req *NatsAPIListNatsAccountsRequest, opts ...scw.RequestOption) (*ListNatsAccountsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-accounts",
Query: query,
}
var resp ListNatsAccountsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateNatsCredentials: Create a set of credentials for a NATS account, specified by its NATS account ID.
func (s *NatsAPI) CreateNatsCredentials(req *NatsAPICreateNatsCredentialsRequest, opts ...scw.RequestOption) (*NatsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("mnq")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-credentials",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp NatsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNatsCredentials: Delete a set of credentials, specified by their credentials ID. Deleting credentials is irreversible and cannot be undone. The credentials can no longer be used to access the NATS account, and active connections using this credentials will be closed.
func (s *NatsAPI) DeleteNatsCredentials(req *NatsAPIDeleteNatsCredentialsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NatsCredentialsID) == "" {
return errors.New("field NatsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-credentials/" + fmt.Sprint(req.NatsCredentialsID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetNatsCredentials: Retrieve an existing set of credentials, identified by the `nats_credentials_id`. The credentials themselves are NOT returned, only their metadata (NATS account ID, credentials name, etc), are returned in the response.
func (s *NatsAPI) GetNatsCredentials(req *NatsAPIGetNatsCredentialsRequest, opts ...scw.RequestOption) (*NatsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NatsCredentialsID) == "" {
return nil, errors.New("field NatsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-credentials/" + fmt.Sprint(req.NatsCredentialsID) + "",
}
var resp NatsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNatsCredentials: List existing credentials in the specified NATS account. The response contains only the metadata for the credentials, not the credentials themselves, which are only returned after a **Create Credentials** call.
func (s *NatsAPI) ListNatsCredentials(req *NatsAPIListNatsCredentialsRequest, opts ...scw.RequestOption) (*ListNatsCredentialsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "nats_account_id", req.NatsAccountID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/nats-credentials",
Query: query,
}
var resp ListNatsCredentialsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your Scaleway Topics and Events.
type SnsAPI struct {
client *scw.Client
}
// NewSnsAPI returns a SnsAPI object from a Scaleway client.
func NewSnsAPI(client *scw.Client) *SnsAPI {
return &SnsAPI{
client: client,
}
}
func (s *SnsAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms}
}
// ActivateSns: Activate Topics and Events for the specified Project ID. Topics and Events must be activated before any usage. Activating Topics and Events does not trigger any billing, and you can deactivate at any time.
func (s *SnsAPI) ActivateSns(req *SnsAPIActivateSnsRequest, opts ...scw.RequestOption) (*SnsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/activate-sns",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SnsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnsInfo: Retrieve the Topics and Events information of the specified Project ID. Informations include the activation status and the Topics and Events API endpoint URL.
func (s *SnsAPI) GetSnsInfo(req *SnsAPIGetSnsInfoRequest, opts ...scw.RequestOption) (*SnsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-info",
Query: query,
}
var resp SnsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeactivateSns: Deactivate Topics and Events for the specified Project ID. You must delete all topics and credentials before this call or you need to set the force_delete parameter.
func (s *SnsAPI) DeactivateSns(req *SnsAPIDeactivateSnsRequest, opts ...scw.RequestOption) (*SnsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deactivate-sns",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SnsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnsCredentials: Create a set of credentials for Topics and Events, specified by a Project ID. Credentials give the bearer access to topics, and the level of permissions can be defined granularly.
func (s *SnsAPI) CreateSnsCredentials(req *SnsAPICreateSnsCredentialsRequest, opts ...scw.RequestOption) (*SnsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("mnq_sns")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-credentials",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SnsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnsCredentials: Delete a set of Topics and Events credentials, specified by their credentials ID. Deleting credentials is irreversible and cannot be undone. The credentials can then no longer be used to access Topics and Events.
func (s *SnsAPI) DeleteSnsCredentials(req *SnsAPIDeleteSnsCredentialsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnsCredentialsID) == "" {
return errors.New("field SnsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-credentials/" + fmt.Sprint(req.SnsCredentialsID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateSnsCredentials: Update a set of Topics and Events credentials. You can update the credentials' name, or their permissions.
func (s *SnsAPI) UpdateSnsCredentials(req *SnsAPIUpdateSnsCredentialsRequest, opts ...scw.RequestOption) (*SnsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnsCredentialsID) == "" {
return nil, errors.New("field SnsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-credentials/" + fmt.Sprint(req.SnsCredentialsID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SnsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnsCredentials: Retrieve an existing set of credentials, identified by the `credentials_id`. The credentials themselves, as well as their metadata (name, project ID etc), are returned in the response.
func (s *SnsAPI) GetSnsCredentials(req *SnsAPIGetSnsCredentialsRequest, opts ...scw.RequestOption) (*SnsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnsCredentialsID) == "" {
return nil, errors.New("field SnsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-credentials/" + fmt.Sprint(req.SnsCredentialsID) + "",
}
var resp SnsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSnsCredentials: List existing Topics and Events credentials in the specified region. The response contains only the metadata for the credentials, not the credentials themselves.
func (s *SnsAPI) ListSnsCredentials(req *SnsAPIListSnsCredentialsRequest, opts ...scw.RequestOption) (*ListSnsCredentialsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sns-credentials",
Query: query,
}
var resp ListSnsCredentialsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your Scaleway Queues.
type SqsAPI struct {
client *scw.Client
}
// NewSqsAPI returns a SqsAPI object from a Scaleway client.
func NewSqsAPI(client *scw.Client) *SqsAPI {
return &SqsAPI{
client: client,
}
}
func (s *SqsAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms}
}
// ActivateSqs: Activate Queues for the specified Project ID. Queues must be activated before any usage such as creating credentials and queues. Activating Queues does not trigger any billing, and you can deactivate at any time.
func (s *SqsAPI) ActivateSqs(req *SqsAPIActivateSqsRequest, opts ...scw.RequestOption) (*SqsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/activate-sqs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SqsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSqsInfo: Retrieve the Queues information of the specified Project ID. Informations include the activation status and the Queues API endpoint URL.
func (s *SqsAPI) GetSqsInfo(req *SqsAPIGetSqsInfoRequest, opts ...scw.RequestOption) (*SqsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-info",
Query: query,
}
var resp SqsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeactivateSqs: Deactivate Queues for the specified Project ID. You must delete all queues and credentials before this call or you need to set the force_delete parameter.
func (s *SqsAPI) DeactivateSqs(req *SqsAPIDeactivateSqsRequest, opts ...scw.RequestOption) (*SqsInfo, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/deactivate-sqs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SqsInfo
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSqsCredentials: Create a set of credentials for Queues, specified by a Project ID. Credentials give the bearer access to queues, and the level of permissions can be defined granularly.
func (s *SqsAPI) CreateSqsCredentials(req *SqsAPICreateSqsCredentialsRequest, opts ...scw.RequestOption) (*SqsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("mnq_sqs")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-credentials",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SqsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSqsCredentials: Delete a set of Queues credentials, specified by their credentials ID. Deleting credentials is irreversible and cannot be undone. The credentials can then no longer be used to access Queues.
func (s *SqsAPI) DeleteSqsCredentials(req *SqsAPIDeleteSqsCredentialsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SqsCredentialsID) == "" {
return errors.New("field SqsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-credentials/" + fmt.Sprint(req.SqsCredentialsID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpdateSqsCredentials: Update a set of Queues credentials. You can update the credentials' name, or their permissions.
func (s *SqsAPI) UpdateSqsCredentials(req *SqsAPIUpdateSqsCredentialsRequest, opts ...scw.RequestOption) (*SqsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SqsCredentialsID) == "" {
return nil, errors.New("field SqsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-credentials/" + fmt.Sprint(req.SqsCredentialsID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SqsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSqsCredentials: Retrieve an existing set of credentials, identified by the `credentials_id`. The credentials themselves, as well as their metadata (name, project ID etc), are returned in the response.
func (s *SqsAPI) GetSqsCredentials(req *SqsAPIGetSqsCredentialsRequest, opts ...scw.RequestOption) (*SqsCredentials, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SqsCredentialsID) == "" {
return nil, errors.New("field SqsCredentialsID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-credentials/" + fmt.Sprint(req.SqsCredentialsID) + "",
}
var resp SqsCredentials
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSqsCredentials: List existing Queues credentials in the specified region. The response contains only the metadata for the credentials, not the credentials themselves.
func (s *SqsAPI) ListSqsCredentials(req *SqsAPIListSqsCredentialsRequest, opts ...scw.RequestOption) (*ListSqsCredentialsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mnq/v1beta1/regions/" + fmt.Sprint(req.Region) + "/sqs-credentials",
Query: query,
}
var resp ListSqsCredentialsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mnq/v1beta1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026710 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mnq/v1beta1/sweepers/sweepers.go 0000664 0000000 0000000 00000013221 14747113137 0031073 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"strings"
accountSDK "github.com/scaleway/scaleway-sdk-go/api/account/v3"
mnq "github.com/scaleway/scaleway-sdk-go/api/mnq/v1beta1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepSQSCredentials(scwClient *scw.Client, region scw.Region) error {
mnqAPI := mnq.NewSqsAPI(scwClient)
projectID, _ := scwClient.GetDefaultProjectID()
logger.Warningf("sweeper: destroying the mnq sqs credentials in (%s)", region)
sqsInfo, err := mnqAPI.GetSqsInfo(&mnq.SqsAPIGetSqsInfoRequest{Region: region})
if err != nil {
return fmt.Errorf("error getting sns info in sweeper: %s", err)
}
if sqsInfo.Status == mnq.SqsInfoStatusDisabled {
logger.Infof("sqs is disabled, skipping")
return nil
}
listSqsCredentials, err := mnqAPI.ListSqsCredentials(
&mnq.SqsAPIListSqsCredentialsRequest{
Region: region,
ProjectID: scw.StringPtr(projectID),
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing sqs credentials in (%s) in sweeper: %s", region, err)
}
for _, credentials := range listSqsCredentials.SqsCredentials {
err := mnqAPI.DeleteSqsCredentials(&mnq.SqsAPIDeleteSqsCredentialsRequest{
SqsCredentialsID: credentials.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting sqs credentials in sweeper: %s", err)
}
}
return nil
}
func SweepSQS(scwClient *scw.Client, region scw.Region) error {
accountAPI := accountSDK.NewProjectAPI(scwClient)
mnqAPI := mnq.NewSqsAPI(scwClient)
logger.Warningf("sweeper: destroying the mnq sqss in (%s)", region)
listProjects, err := accountAPI.ListProjects(&accountSDK.ProjectAPIListProjectsRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
if !strings.HasPrefix(project.Name, "tf_tests") {
continue
}
_, err := mnqAPI.DeactivateSqs(&mnq.SqsAPIDeactivateSqsRequest{
Region: region,
ProjectID: project.ID,
})
if err != nil {
return err
}
}
return nil
}
func SweepSNSCredentials(scwClient *scw.Client, region scw.Region) error {
mnqAPI := mnq.NewSnsAPI(scwClient)
projectID, _ := scwClient.GetDefaultProjectID()
logger.Warningf("sweeper: destroying the mnq sns credentials in (%s)", region)
snsInfo, err := mnqAPI.GetSnsInfo(&mnq.SnsAPIGetSnsInfoRequest{Region: region})
if err != nil {
return fmt.Errorf("error getting sns info in sweeper: %s", err)
}
if snsInfo.Status == mnq.SnsInfoStatusDisabled {
logger.Infof("sns is disabled, skipping")
return nil
}
listSnsCredentials, err := mnqAPI.ListSnsCredentials(
&mnq.SnsAPIListSnsCredentialsRequest{
Region: region,
ProjectID: scw.StringPtr(projectID),
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing sns credentials in (%s) in sweeper: %s", region, err)
}
for _, credentials := range listSnsCredentials.SnsCredentials {
err := mnqAPI.DeleteSnsCredentials(&mnq.SnsAPIDeleteSnsCredentialsRequest{
SnsCredentialsID: credentials.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting sns credentials in sweeper: %s", err)
}
}
return nil
}
func SweepSNS(scwClient *scw.Client, region scw.Region) error {
accountAPI := accountSDK.NewProjectAPI(scwClient)
mnqAPI := mnq.NewSnsAPI(scwClient)
logger.Warningf("sweeper: destroying the mnq sns in (%s)", region)
listProjects, err := accountAPI.ListProjects(&accountSDK.ProjectAPIListProjectsRequest{}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("failed to list projects: %w", err)
}
for _, project := range listProjects.Projects {
if !strings.HasPrefix(project.Name, "tf_tests") {
continue
}
_, err := mnqAPI.DeactivateSns(&mnq.SnsAPIDeactivateSnsRequest{
Region: region,
ProjectID: project.ID,
})
if err != nil {
logger.Debugf("sweeper: error (%s)", err)
return err
}
}
return nil
}
func SweepNatsAccount(scwClient *scw.Client, region scw.Region) error {
mnqAPI := mnq.NewNatsAPI(scwClient)
logger.Warningf("sweeper: destroying the mnq nats accounts in (%s)", region)
listNatsAccounts, err := mnqAPI.ListNatsAccounts(
&mnq.NatsAPIListNatsAccountsRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing nats account in (%s) in sweeper: %s", region, err)
}
for _, account := range listNatsAccounts.NatsAccounts {
err := mnqAPI.DeleteNatsAccount(&mnq.NatsAPIDeleteNatsAccountRequest{
NatsAccountID: account.ID,
Region: region,
})
if err != nil {
logger.Warningf("sweeper: error (%s)", err)
return fmt.Errorf("error deleting nats account in sweeper: %s", err)
}
}
return nil
}
func SweepAllSNS(scwClient *scw.Client) error {
for _, region := range (&mnq.SnsAPI{}).Regions() {
err := SweepSNSCredentials(scwClient, region)
if err != nil {
return err
}
err = SweepSNS(scwClient, region)
if err != nil {
return err
}
}
return nil
}
func SweepAllSQS(scwClient *scw.Client) error {
for _, region := range (&mnq.SqsAPI{}).Regions() {
err := SweepSQSCredentials(scwClient, region)
if err != nil {
return err
}
err = SweepSQS(scwClient, region)
if err != nil {
return err
}
}
return nil
}
func SweepAllNats(scwClient *scw.Client) error {
for _, region := range (&mnq.NatsAPI{}).Regions() {
err := SweepNatsAccount(scwClient, region)
if err != nil {
return err
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
err := SweepAllSNS(scwClient)
if err != nil {
return err
}
err = SweepAllSQS(scwClient)
if err != nil {
return err
}
err = SweepAllNats(scwClient)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/ 0000775 0000000 0000000 00000000000 14747113137 0024442 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0026057 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/v1alpha1/mongodb_sdk.go 0000664 0000000 0000000 00000150517 14747113137 0030705 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package mongodb provides methods and message types of the mongodb v1alpha1 API.
package mongodb
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type InstanceStatus string
const (
InstanceStatusUnknownStatus = InstanceStatus("unknown_status")
InstanceStatusReady = InstanceStatus("ready")
InstanceStatusProvisioning = InstanceStatus("provisioning")
InstanceStatusConfiguring = InstanceStatus("configuring")
InstanceStatusDeleting = InstanceStatus("deleting")
InstanceStatusError = InstanceStatus("error")
InstanceStatusInitializing = InstanceStatus("initializing")
InstanceStatusLocked = InstanceStatus("locked")
InstanceStatusSnapshotting = InstanceStatus("snapshotting")
)
func (enum InstanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum InstanceStatus) Values() []InstanceStatus {
return []InstanceStatus{
"unknown_status",
"ready",
"provisioning",
"configuring",
"deleting",
"error",
"initializing",
"locked",
"snapshotting",
}
}
func (enum InstanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceStatus(InstanceStatus(tmp).String())
return nil
}
type ListInstancesRequestOrderBy string
const (
ListInstancesRequestOrderByCreatedAtAsc = ListInstancesRequestOrderBy("created_at_asc")
ListInstancesRequestOrderByCreatedAtDesc = ListInstancesRequestOrderBy("created_at_desc")
ListInstancesRequestOrderByNameAsc = ListInstancesRequestOrderBy("name_asc")
ListInstancesRequestOrderByNameDesc = ListInstancesRequestOrderBy("name_desc")
ListInstancesRequestOrderByStatusAsc = ListInstancesRequestOrderBy("status_asc")
ListInstancesRequestOrderByStatusDesc = ListInstancesRequestOrderBy("status_desc")
)
func (enum ListInstancesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInstancesRequestOrderBy) Values() []ListInstancesRequestOrderBy {
return []ListInstancesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
}
}
func (enum ListInstancesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInstancesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInstancesRequestOrderBy(ListInstancesRequestOrderBy(tmp).String())
return nil
}
type ListSnapshotsRequestOrderBy string
const (
ListSnapshotsRequestOrderByCreatedAtAsc = ListSnapshotsRequestOrderBy("created_at_asc")
ListSnapshotsRequestOrderByCreatedAtDesc = ListSnapshotsRequestOrderBy("created_at_desc")
ListSnapshotsRequestOrderByNameAsc = ListSnapshotsRequestOrderBy("name_asc")
ListSnapshotsRequestOrderByNameDesc = ListSnapshotsRequestOrderBy("name_desc")
ListSnapshotsRequestOrderByExpiresAtAsc = ListSnapshotsRequestOrderBy("expires_at_asc")
ListSnapshotsRequestOrderByExpiresAtDesc = ListSnapshotsRequestOrderBy("expires_at_desc")
)
func (enum ListSnapshotsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSnapshotsRequestOrderBy) Values() []ListSnapshotsRequestOrderBy {
return []ListSnapshotsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"expires_at_asc",
"expires_at_desc",
}
}
func (enum ListSnapshotsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSnapshotsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSnapshotsRequestOrderBy(ListSnapshotsRequestOrderBy(tmp).String())
return nil
}
type ListUsersRequestOrderBy string
const (
ListUsersRequestOrderByNameAsc = ListUsersRequestOrderBy("name_asc")
ListUsersRequestOrderByNameDesc = ListUsersRequestOrderBy("name_desc")
)
func (enum ListUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListUsersRequestOrderBy) Values() []ListUsersRequestOrderBy {
return []ListUsersRequestOrderBy{
"name_asc",
"name_desc",
}
}
func (enum ListUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListUsersRequestOrderBy(ListUsersRequestOrderBy(tmp).String())
return nil
}
type NodeTypeStock string
const (
NodeTypeStockUnknownStock = NodeTypeStock("unknown_stock")
NodeTypeStockLowStock = NodeTypeStock("low_stock")
NodeTypeStockOutOfStock = NodeTypeStock("out_of_stock")
NodeTypeStockAvailable = NodeTypeStock("available")
)
func (enum NodeTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown_stock"
}
return string(enum)
}
func (enum NodeTypeStock) Values() []NodeTypeStock {
return []NodeTypeStock{
"unknown_stock",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum NodeTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeStock(NodeTypeStock(tmp).String())
return nil
}
type SettingPropertyType string
const (
SettingPropertyTypeBOOLEAN = SettingPropertyType("BOOLEAN")
SettingPropertyTypeINT = SettingPropertyType("INT")
SettingPropertyTypeSTRING = SettingPropertyType("STRING")
SettingPropertyTypeFLOAT = SettingPropertyType("FLOAT")
)
func (enum SettingPropertyType) String() string {
if enum == "" {
// return default value if empty
return "BOOLEAN"
}
return string(enum)
}
func (enum SettingPropertyType) Values() []SettingPropertyType {
return []SettingPropertyType{
"BOOLEAN",
"INT",
"STRING",
"FLOAT",
}
}
func (enum SettingPropertyType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SettingPropertyType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SettingPropertyType(SettingPropertyType(tmp).String())
return nil
}
type SnapshotStatus string
const (
SnapshotStatusUnknownStatus = SnapshotStatus("unknown_status")
SnapshotStatusCreating = SnapshotStatus("creating")
SnapshotStatusReady = SnapshotStatus("ready")
SnapshotStatusRestoring = SnapshotStatus("restoring")
SnapshotStatusDeleting = SnapshotStatus("deleting")
SnapshotStatusError = SnapshotStatus("error")
SnapshotStatusLocked = SnapshotStatus("locked")
)
func (enum SnapshotStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SnapshotStatus) Values() []SnapshotStatus {
return []SnapshotStatus{
"unknown_status",
"creating",
"ready",
"restoring",
"deleting",
"error",
"locked",
}
}
func (enum SnapshotStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotStatus(SnapshotStatus(tmp).String())
return nil
}
type VolumeType string
const (
VolumeTypeUnknownType = VolumeType("unknown_type")
VolumeTypeSbs5k = VolumeType("sbs_5k")
VolumeTypeSbs15k = VolumeType("sbs_15k")
)
func (enum VolumeType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum VolumeType) Values() []VolumeType {
return []VolumeType{
"unknown_type",
"sbs_5k",
"sbs_15k",
}
}
func (enum VolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeType(VolumeType(tmp).String())
return nil
}
// EndpointPrivateNetworkDetails: Private Network details.
type EndpointPrivateNetworkDetails struct {
// PrivateNetworkID: UUID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
}
// EndpointPublicDetails: endpoint public details.
type EndpointPublicDetails struct {
}
// EndpointSpecPrivateNetworkDetails: endpoint spec private network details.
type EndpointSpecPrivateNetworkDetails struct {
// PrivateNetworkID: UUID of the Private Network.
PrivateNetworkID string `json:"private_network_id"`
}
// EndpointSpecPublicDetails: endpoint spec public details.
type EndpointSpecPublicDetails struct {
}
// Endpoint: endpoint.
type Endpoint struct {
// ID: UUID of the endpoint.
ID string `json:"id"`
// IPs: list of IPv4 addresses of the endpoint.
IPs []net.IP `json:"ips"`
// DNSRecords: list of DNS records of the endpoint.
DNSRecords []string `json:"dns_records"`
// Port: TCP port of the endpoint.
Port uint32 `json:"port"`
// PrivateNetwork: private Network endpoint details.
// Precisely one of PrivateNetwork, Public must be set.
PrivateNetwork *EndpointPrivateNetworkDetails `json:"private_network,omitempty"`
// Public: public endpoint details.
// Precisely one of PrivateNetwork, Public must be set.
Public *EndpointPublicDetails `json:"public,omitempty"`
}
// InstanceSetting: instance setting.
type InstanceSetting struct {
// Name: name of the settings.
Name string `json:"name"`
// Value: value of the settings.
Value string `json:"value"`
}
// Volume: volume.
type Volume struct {
// Type: type of volume where data is stored.
// Default value: unknown_type
Type VolumeType `json:"type"`
// Size: volume size.
Size scw.Size `json:"size"`
}
// NodeTypeVolumeType: node type volume type.
type NodeTypeVolumeType struct {
// Type: volume Type.
// Default value: unknown_type
Type VolumeType `json:"type"`
// Description: the description of the volume.
Description string `json:"description"`
// MinSize: mimimum size required for the volume.
MinSize scw.Size `json:"min_size"`
// MaxSize: maximum size required for the volume.
MaxSize scw.Size `json:"max_size"`
// ChunkSize: minimum increment level for a Block Storage volume size.
ChunkSize scw.Size `json:"chunk_size"`
}
// SnapshotVolumeType: snapshot volume type.
type SnapshotVolumeType struct {
// Type: default value: unknown_type
Type VolumeType `json:"type"`
}
// Setting: setting.
type Setting struct {
// Name: setting name from the database engine.
Name string `json:"name"`
// DefaultValue: value set when not specified.
DefaultValue string `json:"default_value"`
// HotConfigurable: setting can be applied without restarting.
HotConfigurable bool `json:"hot_configurable"`
// Description: setting description.
Description string `json:"description"`
// PropertyType: setting type.
// Default value: BOOLEAN
PropertyType SettingPropertyType `json:"property_type"`
// Unit: setting base unit.
Unit *string `json:"unit"`
// StringConstraint: validation regex for string type settings.
StringConstraint *string `json:"string_constraint"`
// IntMin: minimum value for int types.
IntMin *int32 `json:"int_min"`
// IntMax: maximum value for int types.
IntMax *int32 `json:"int_max"`
// FloatMin: minimum value for float types.
FloatMin *float32 `json:"float_min"`
// FloatMax: maximum value for float types.
FloatMax *float32 `json:"float_max"`
}
// EndpointSpec: endpoint spec.
type EndpointSpec struct {
// Precisely one of Public, PrivateNetwork must be set.
Public *EndpointSpecPublicDetails `json:"public,omitempty"`
// Precisely one of Public, PrivateNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetworkDetails `json:"private_network,omitempty"`
}
// CreateInstanceRequestVolumeDetails: create instance request volume details.
type CreateInstanceRequestVolumeDetails struct {
// VolumeSize: volume size.
VolumeSize scw.Size `json:"volume_size"`
// VolumeType: type of volume where data is stored.
// Default value: unknown_type
VolumeType VolumeType `json:"volume_type"`
}
// Instance: instance.
type Instance struct {
// ID: UUID of the Database Instance.
ID string `json:"id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// ProjectID: project ID the Database Instance belongs to.
ProjectID string `json:"project_id"`
// Status: status of the Database Instance.
// Default value: unknown_status
Status InstanceStatus `json:"status"`
// Version: mongoDBÂŽ engine version of the Database Instance.
Version string `json:"version"`
// Tags: list of tags applied to the Database Instance.
Tags []string `json:"tags"`
// Settings: advanced settings of the Database Instance.
Settings []*InstanceSetting `json:"settings"`
// NodeNumber: number of node in the Database Instance.
NodeNumber uint32 `json:"node_number"`
// NodeType: node type of the Database Instance.
NodeType string `json:"node_type"`
// Volume: volumes of the Database Instance.
Volume *Volume `json:"volume"`
// Endpoints: list of Database Instance endpoints.
Endpoints []*Endpoint `json:"endpoints"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// Region: region the Database Instance is in.
Region scw.Region `json:"region"`
}
// NodeType: node type.
type NodeType struct {
// Name: node type name identifier.
Name string `json:"name"`
// StockStatus: current stock status for the node type.
// Default value: unknown_stock
StockStatus NodeTypeStock `json:"stock_status"`
// Description: current specs of the offer.
Description string `json:"description"`
// Vcpus: number of virtual CPUs.
Vcpus uint32 `json:"vcpus"`
// Memory: quantity of RAM.
Memory scw.Size `json:"memory"`
// AvailableVolumeTypes: available storage options for the node type.
AvailableVolumeTypes []*NodeTypeVolumeType `json:"available_volume_types"`
// Disabled: the node type is currently disabled.
Disabled bool `json:"disabled"`
// Beta: the node type is currently in beta.
Beta bool `json:"beta"`
// InstanceRange: instance range associated with the node type offer.
InstanceRange string `json:"instance_range"`
}
// Snapshot: snapshot.
type Snapshot struct {
// ID: UUID of the snapshot.
ID string `json:"id"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// Name: name of the snapshot.
Name string `json:"name"`
// Status: status of the snapshot.
// Default value: unknown_status
Status SnapshotStatus `json:"status"`
// Size: size of the snapshot.
Size scw.Size `json:"size"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: updated date (must follow the ISO 8601 format).
UpdatedAt *time.Time `json:"updated_at"`
// InstanceName: name of the Database Instance of the snapshot.
InstanceName string `json:"instance_name"`
// NodeType: source node type.
NodeType string `json:"node_type"`
// VolumeType: type of volume where data is stored - sbs_5k or sbs_15k.
VolumeType *SnapshotVolumeType `json:"volume_type"`
// Region: region of the snapshot.
Region scw.Region `json:"region"`
}
// User: user.
type User struct {
// Name: name of the user (Length must be between 1 and 63 characters. First character must be an alphabet character (a-zA-Z). Only a-zA-Z0-9_$- characters are accepted).
Name string `json:"name"`
}
// Version: version.
type Version struct {
// Version: mongoDBÂŽ engine version.
Version string `json:"version"`
// EndOfLifeAt: date of End of Life.
EndOfLifeAt *time.Time `json:"end_of_life_at"`
// AvailableSettings: instance settings available to be updated.
AvailableSettings []*Setting `json:"available_settings"`
}
// RestoreSnapshotRequestVolumeDetails: restore snapshot request volume details.
type RestoreSnapshotRequestVolumeDetails struct {
// VolumeType: type of volume where data is stored.
// Default value: unknown_type
VolumeType VolumeType `json:"volume_type"`
}
// CreateEndpointRequest: create endpoint request.
type CreateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// Endpoint: endpointSpec used to expose your Database Instance.
Endpoint *EndpointSpec `json:"endpoint"`
}
// CreateInstanceRequest: create instance request.
type CreateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: the Project ID on which the Database Instance will be created.
ProjectID string `json:"project_id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// Version: version of the MongoDBÂŽ engine.
Version string `json:"version"`
// Tags: tags to apply to the Database Instance.
Tags []string `json:"tags"`
// NodeNumber: number of node to use for the Database Instance.
NodeNumber uint32 `json:"node_number"`
// NodeType: type of node to use for the Database Instance.
NodeType string `json:"node_type"`
// UserName: username created when the Database Instance is created.
UserName string `json:"user_name"`
// Password: password of the initial user.
Password string `json:"password"`
// Volume: instance volume information.
Volume *CreateInstanceRequestVolumeDetails `json:"volume,omitempty"`
// Endpoints: one or multiple EndpointSpec used to expose your Database Instance.
Endpoints []*EndpointSpec `json:"endpoints"`
}
// CreateSnapshotRequest: create snapshot request.
type CreateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to snapshot.
InstanceID string `json:"-"`
// Name: name of the snapshot.
Name string `json:"name"`
// ExpiresAt: expiration date of the snapshot (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateUserRequest: create user request.
type CreateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance the user belongs to.
InstanceID string `json:"-"`
// Name: name of the database user.
Name string `json:"name"`
// Password: password of the database user.
Password string `json:"password"`
}
// DeleteEndpointRequest: delete endpoint request.
type DeleteEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: UUID of the Endpoint to delete.
EndpointID string `json:"-"`
}
// DeleteInstanceRequest: delete instance request.
type DeleteInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete.
InstanceID string `json:"-"`
}
// DeleteSnapshotRequest: delete snapshot request.
type DeleteSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// DeleteUserRequest: delete user request.
type DeleteUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance the user belongs to.
InstanceID string `json:"-"`
// Name: name of the database user.
Name string `json:"-"`
}
// GetInstanceCertificateRequest: get instance certificate request.
type GetInstanceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetInstanceRequest: get instance request.
type GetInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetSnapshotRequest: get snapshot request.
type GetSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// ListInstancesRequest: list instances request.
type ListInstancesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Tags: list Database Instances that have a given tag.
Tags []string `json:"-"`
// Name: lists Database Instances that match a name pattern.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering Database Instance listings.
// Default value: created_at_asc
OrderBy ListInstancesRequestOrderBy `json:"-"`
// OrganizationID: organization ID of the Database Instance.
OrganizationID *string `json:"-"`
// ProjectID: project ID.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListInstancesResponse: list instances response.
type ListInstancesResponse struct {
// Instances: list of all Database Instances available in an Organization or Project.
Instances []*Instance `json:"instances"`
// TotalCount: total count of Database Instances available in an Organization or Project.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListInstancesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Instances = append(r.Instances, results.Instances...)
r.TotalCount += uint64(len(results.Instances))
return uint64(len(results.Instances)), nil
}
// ListNodeTypesRequest: list node types request.
type ListNodeTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IncludeDisabledTypes: defines whether or not to include disabled types.
IncludeDisabledTypes *bool `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListNodeTypesResponse: list node types response.
type ListNodeTypesResponse struct {
// NodeTypes: types of the node.
NodeTypes []*NodeType `json:"node_types"`
// TotalCount: total count of node-types available.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListNodeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NodeTypes = append(r.NodeTypes, results.NodeTypes...)
r.TotalCount += uint64(len(results.NodeTypes))
return uint64(len(results.NodeTypes)), nil
}
// ListSnapshotsRequest: list snapshots request.
type ListSnapshotsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: instance ID the snapshots belongs to.
InstanceID *string `json:"-"`
// Name: lists database snapshots that match a name pattern.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering snapshot listings.
// Default value: created_at_asc
OrderBy ListSnapshotsRequestOrderBy `json:"-"`
// OrganizationID: organization ID the snapshots belongs to.
OrganizationID *string `json:"-"`
// ProjectID: project ID to list the snapshots of.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListSnapshotsResponse: list snapshots response.
type ListSnapshotsResponse struct {
// Snapshots: list of all database snapshots available in an Organization or Project.
Snapshots []*Snapshot `json:"snapshots"`
// TotalCount: total count of database snapshots available in a Organization or Project.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSnapshotsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Snapshots = append(r.Snapshots, results.Snapshots...)
r.TotalCount += uint64(len(results.Snapshots))
return uint64(len(results.Snapshots)), nil
}
// ListUsersRequest: list users request.
type ListUsersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// Name: name of the user.
Name *string `json:"-"`
// OrderBy: criteria to use when requesting user listing.
// Default value: name_asc
OrderBy ListUsersRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListUsersResponse: list users response.
type ListUsersResponse struct {
// Users: list of users in a Database Instance.
Users []*User `json:"users"`
// TotalCount: total count of users present on a Database Instance.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Users = append(r.Users, results.Users...)
r.TotalCount += uint64(len(results.Users))
return uint64(len(results.Users)), nil
}
// ListVersionsRequest: list versions request.
type ListVersionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Version *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListVersionsResponse: list versions response.
type ListVersionsResponse struct {
// Versions: available MongoDBÂŽ engine version.
Versions []*Version `json:"versions"`
// TotalCount: total count of MongoDBÂŽ engine version available.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVersionsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVersionsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListVersionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Versions = append(r.Versions, results.Versions...)
r.TotalCount += uint64(len(results.Versions))
return uint64(len(results.Versions)), nil
}
// RestoreSnapshotRequest: restore snapshot request.
type RestoreSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
// InstanceName: name of the new Database Instance.
InstanceName string `json:"instance_name"`
// NodeType: node type to use for the new Database Instance.
NodeType string `json:"node_type"`
// NodeNumber: number of nodes to use for the new Database Instance.
NodeNumber uint32 `json:"node_number"`
// Volume: instance volume information.
Volume *RestoreSnapshotRequestVolumeDetails `json:"volume"`
}
// UpdateInstanceRequest: update instance request.
type UpdateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to update.
InstanceID string `json:"-"`
// Name: name of the Database Instance.
Name *string `json:"name,omitempty"`
// Tags: tags of a Database Instance.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateSnapshotRequest: update snapshot request.
type UpdateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the Snapshot.
SnapshotID string `json:"-"`
// Name: name of the snapshot.
Name *string `json:"name,omitempty"`
// ExpiresAt: expiration date of the snapshot (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// UpdateUserRequest: update user request.
type UpdateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance the user belongs to.
InstanceID string `json:"-"`
// Name: name of the database user.
Name string `json:"-"`
// Password: password of the database user.
Password *string `json:"password,omitempty"`
}
// UpgradeInstanceRequest: upgrade instance request.
type UpgradeInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to upgrade.
InstanceID string `json:"-"`
// VolumeSize: increase your Block Storage volume size.
// Precisely one of VolumeSize must be set.
VolumeSize *scw.Size `json:"volume_size,omitempty"`
}
// This API allows you to manage your Managed Databases for MongoDBÂŽ.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar}
}
// ListNodeTypes: List available node types.
func (s *API) ListNodeTypes(req *ListNodeTypesRequest, opts ...scw.RequestOption) (*ListNodeTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "include_disabled_types", req.IncludeDisabledTypes)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/node-types",
Query: query,
}
var resp ListNodeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListVersions: List available MongoDBÂŽ versions.
func (s *API) ListVersions(req *ListVersionsRequest, opts ...scw.RequestOption) (*ListVersionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "version", req.Version)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/versions",
Query: query,
}
var resp ListVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstances: List all MongoDBÂŽ Database Instances in the specified region. By default, the MongoDBÂŽ Database Instances returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `tags` and `name`. For the `name` parameter, the value you include will be checked against the whole name string to see if it includes the string you put in the parameter.
func (s *API) ListInstances(req *ListInstancesRequest, opts ...scw.RequestOption) (*ListInstancesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances",
Query: query,
}
var resp ListInstancesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstance: Retrieve information about a given MongoDBÂŽ Database Instance, specified by the `region` and `instance_id` parameters. Its full details, including name, status, IP address and port, are returned in the response object.
func (s *API) GetInstance(req *GetInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateInstance: Create a new MongoDBÂŽ Database Instance.
func (s *API) CreateInstance(req *CreateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("mgdb")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateInstance: Update the parameters of a MongoDBÂŽ Database Instance.
func (s *API) UpdateInstance(req *UpdateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstance: Delete a given MongoDBÂŽ Database Instance, specified by the `region` and `instance_id` parameters. Deleting a MongoDBÂŽ Database Instance is permanent, and cannot be undone. Note that upon deletion all your data will be lost.
func (s *API) DeleteInstance(req *DeleteInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradeInstance: Upgrade your current Database Instance specifications like volume size.
func (s *API) UpgradeInstance(req *UpgradeInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstanceCertificate: Retrieve the certificate of a given Database Instance, specified by the `instance_id` parameter.
func (s *API) GetInstanceCertificate(req *GetInstanceCertificateRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/certificate",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnapshot: Create a new snapshot of a Database Instance. You must define the `name` and `instance_id` parameters in the request.
func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/snapshots",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnapshot: Retrieve information about a given snapshot of a Database Instance. You must specify, in the endpoint, the `snapshot_id` parameter of the snapshot you want to retrieve.
func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSnapshot: Update the parameters of a snapshot of a Database Instance. You can update the `name` and `expires_at` parameters.
func (s *API) UpdateSnapshot(req *UpdateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestoreSnapshot: Restore a given snapshot of a Database Instance. You must specify, in the endpoint, the `snapshot_id` parameter of the snapshot you want to restore, the `instance_name` of the new Database Instance, `node_type` of the new Database Instance and `node_number` of the new Database Instance.
func (s *API) RestoreSnapshot(req *RestoreSnapshotRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "/restore",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSnapshots: List snapshots. You can include the `instance_id` or `project_id` in your query to get the list of snapshots for specific Database Instances and/or Projects. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "instance_id", req.InstanceID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/snapshots",
Query: query,
}
var resp ListSnapshotsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnapshot: Delete a given snapshot of a Database Instance. You must specify, in the endpoint, the `snapshot_id` parameter of the snapshot you want to delete.
func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListUsers: List all users of a given Database Instance.
func (s *API) ListUsers(req *ListUsersRequest, opts ...scw.RequestOption) (*ListUsersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
Query: query,
}
var resp ListUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateUser: Create an user on a Database Instance. You must define the `name`, `password` of the user and `instance_id` parameters in the request.
func (s *API) CreateUser(req *CreateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUser: Update the parameters of a user on a Database Instance. You can update the `password` parameter, but you cannot change the name of the user.
func (s *API) UpdateUser(req *UpdateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return nil, errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteUser: Delete an existing user on a Database Instance.
func (s *API) DeleteUser(req *DeleteUserRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// DeleteEndpoint: Delete the endpoint of a Database Instance. You must specify the `endpoint_id` parameter of the endpoint you want to delete. Note that you might need to update any environment configurations that point to the deleted endpoint.
func (s *API) DeleteEndpoint(req *DeleteEndpointRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateEndpoint: Create a new endpoint for a MongoDBÂŽ Database Instance. You can add `public_network` or `private_network` specifications to the body of the request.
func (s *API) CreateEndpoint(req *CreateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/mongodb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/v1alpha1/mongodb_utils.go 0000664 0000000 0000000 00000006026 14747113137 0031257 0 ustar 00root root 0000000 0000000 package mongodb
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultInstanceRetryInterval = 15 * time.Second
defaultInstanceTimeout = 15 * time.Minute
)
// WaitForInstanceRequest is used by WaitForInstance method.
type WaitForInstanceRequest struct {
InstanceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
type WaitForSnapshotRequest struct {
InstanceID string
SnapshotID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForInstance waits for the instance to be in a "terminal state" before returning.
// This function can be used to wait for an instance to be ready or in another final state.
func (s *API) WaitForInstance(req *WaitForInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
timeout := defaultInstanceTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultInstanceRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[InstanceStatus]struct{}{
InstanceStatusReady: {},
InstanceStatusLocked: {},
InstanceStatusError: {},
}
instance, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetInstance(&GetInstanceRequest{
Region: req.Region,
InstanceID: req.InstanceID,
}, opts...)
if err != nil {
return nil, false, err
}
// Check if the instance has reached a terminal state
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for instance failed")
}
return instance.(*Instance), nil
}
// WaitForSnapshot waits for the snapshot to reach a "terminal state" before returning.
func (s *API) WaitForSnapshot(req *WaitForSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
timeout := defaultInstanceTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultInstanceRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[SnapshotStatus]struct{}{
SnapshotStatusReady: {},
SnapshotStatusError: {},
SnapshotStatusLocked: {},
}
snapshot, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
getSnapshotResponse, err := s.GetSnapshot(&GetSnapshotRequest{
Region: req.Region,
SnapshotID: req.SnapshotID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[getSnapshotResponse.Status]
return getSnapshotResponse, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for snapshot failed")
}
return snapshot.(*Snapshot), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027714 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/mongodb/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000002105 14747113137 0032076 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
mongodb "github.com/scaleway/scaleway-sdk-go/api/mongodb/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepInstances(scwClient *scw.Client, region scw.Region) error {
mongodbAPI := mongodb.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the mongodb instance in (%s)", region)
listInstance, err := mongodbAPI.ListInstances(&mongodb.ListInstancesRequest{
Region: region,
})
if err != nil {
return fmt.Errorf("error listing mongodb instance in (%s) in sweeper: %w", region, err)
}
for _, instance := range listInstance.Instances {
_, err := mongodbAPI.DeleteInstance(&mongodb.DeleteInstanceRequest{
Region: region,
InstanceID: instance.ID,
})
if err != nil {
return fmt.Errorf("error deleting mongodb instance in sweeper: %w", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&mongodb.API{}).Regions() {
err := SweepInstances(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/qaas/ 0000775 0000000 0000000 00000000000 14747113137 0023742 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/qaas/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025357 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/qaas/v1alpha1/qaas_sdk.go 0000664 0000000 0000000 00000172202 14747113137 0027500 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package qaas provides methods and message types of the qaas v1alpha1 API.
package qaas
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ApplicationType string
const (
ApplicationTypeUnknownType = ApplicationType("unknown_type")
// Variational Quantum Eigensolver is a type hybrid algorithm to find the ground state of a given physical system.
ApplicationTypeVqe = ApplicationType("vqe")
)
func (enum ApplicationType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum ApplicationType) Values() []ApplicationType {
return []ApplicationType{
"unknown_type",
"vqe",
}
}
func (enum ApplicationType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ApplicationType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ApplicationType(ApplicationType(tmp).String())
return nil
}
type JobStatus string
const (
JobStatusUnknownStatus = JobStatus("unknown_status")
JobStatusWaiting = JobStatus("waiting")
JobStatusError = JobStatus("error")
JobStatusRunning = JobStatus("running")
JobStatusCompleted = JobStatus("completed")
JobStatusCancelling = JobStatus("cancelling")
JobStatusCancelled = JobStatus("cancelled")
)
func (enum JobStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum JobStatus) Values() []JobStatus {
return []JobStatus{
"unknown_status",
"waiting",
"error",
"running",
"completed",
"cancelling",
"cancelled",
}
}
func (enum JobStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *JobStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = JobStatus(JobStatus(tmp).String())
return nil
}
type ListApplicationsRequestOrderBy string
const (
ListApplicationsRequestOrderByNameAsc = ListApplicationsRequestOrderBy("name_asc")
ListApplicationsRequestOrderByNameDesc = ListApplicationsRequestOrderBy("name_desc")
ListApplicationsRequestOrderByTypeAsc = ListApplicationsRequestOrderBy("type_asc")
ListApplicationsRequestOrderByTypeDesc = ListApplicationsRequestOrderBy("type_desc")
)
func (enum ListApplicationsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListApplicationsRequestOrderBy) Values() []ListApplicationsRequestOrderBy {
return []ListApplicationsRequestOrderBy{
"name_asc",
"name_desc",
"type_asc",
"type_desc",
}
}
func (enum ListApplicationsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListApplicationsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListApplicationsRequestOrderBy(ListApplicationsRequestOrderBy(tmp).String())
return nil
}
type ListJobResultsRequestOrderBy string
const (
ListJobResultsRequestOrderByCreatedAtDesc = ListJobResultsRequestOrderBy("created_at_desc")
ListJobResultsRequestOrderByCreatedAtAsc = ListJobResultsRequestOrderBy("created_at_asc")
)
func (enum ListJobResultsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListJobResultsRequestOrderBy) Values() []ListJobResultsRequestOrderBy {
return []ListJobResultsRequestOrderBy{
"created_at_desc",
"created_at_asc",
}
}
func (enum ListJobResultsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListJobResultsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListJobResultsRequestOrderBy(ListJobResultsRequestOrderBy(tmp).String())
return nil
}
type ListJobsRequestOrderBy string
const (
ListJobsRequestOrderByCreatedAtDesc = ListJobsRequestOrderBy("created_at_desc")
ListJobsRequestOrderByCreatedAtAsc = ListJobsRequestOrderBy("created_at_asc")
ListJobsRequestOrderByStatusAsc = ListJobsRequestOrderBy("status_asc")
ListJobsRequestOrderByStatusDesc = ListJobsRequestOrderBy("status_desc")
ListJobsRequestOrderByPlatformNameAsc = ListJobsRequestOrderBy("platform_name_asc")
ListJobsRequestOrderByPlatformNameDesc = ListJobsRequestOrderBy("platform_name_desc")
ListJobsRequestOrderByNameAsc = ListJobsRequestOrderBy("name_asc")
ListJobsRequestOrderByNameDesc = ListJobsRequestOrderBy("name_desc")
ListJobsRequestOrderBySessionNameAsc = ListJobsRequestOrderBy("session_name_asc")
ListJobsRequestOrderBySessionNameDesc = ListJobsRequestOrderBy("session_name_desc")
)
func (enum ListJobsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListJobsRequestOrderBy) Values() []ListJobsRequestOrderBy {
return []ListJobsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"status_asc",
"status_desc",
"platform_name_asc",
"platform_name_desc",
"name_asc",
"name_desc",
"session_name_asc",
"session_name_desc",
}
}
func (enum ListJobsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListJobsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListJobsRequestOrderBy(ListJobsRequestOrderBy(tmp).String())
return nil
}
type ListPlatformsRequestOrderBy string
const (
ListPlatformsRequestOrderByNameAsc = ListPlatformsRequestOrderBy("name_asc")
ListPlatformsRequestOrderByNameDesc = ListPlatformsRequestOrderBy("name_desc")
ListPlatformsRequestOrderByProviderNameAsc = ListPlatformsRequestOrderBy("provider_name_asc")
ListPlatformsRequestOrderByProviderNameDesc = ListPlatformsRequestOrderBy("provider_name_desc")
ListPlatformsRequestOrderByTypeAsc = ListPlatformsRequestOrderBy("type_asc")
ListPlatformsRequestOrderByTypeDesc = ListPlatformsRequestOrderBy("type_desc")
ListPlatformsRequestOrderByTechnologyAsc = ListPlatformsRequestOrderBy("technology_asc")
ListPlatformsRequestOrderByTechnologyDesc = ListPlatformsRequestOrderBy("technology_desc")
ListPlatformsRequestOrderByBackendNameAsc = ListPlatformsRequestOrderBy("backend_name_asc")
ListPlatformsRequestOrderByBackendNameDesc = ListPlatformsRequestOrderBy("backend_name_desc")
)
func (enum ListPlatformsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListPlatformsRequestOrderBy) Values() []ListPlatformsRequestOrderBy {
return []ListPlatformsRequestOrderBy{
"name_asc",
"name_desc",
"provider_name_asc",
"provider_name_desc",
"type_asc",
"type_desc",
"technology_asc",
"technology_desc",
"backend_name_asc",
"backend_name_desc",
}
}
func (enum ListPlatformsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPlatformsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPlatformsRequestOrderBy(ListPlatformsRequestOrderBy(tmp).String())
return nil
}
type ListProcessResultsRequestOrderBy string
const (
ListProcessResultsRequestOrderByCreatedAtDesc = ListProcessResultsRequestOrderBy("created_at_desc")
ListProcessResultsRequestOrderByCreatedAtAsc = ListProcessResultsRequestOrderBy("created_at_asc")
)
func (enum ListProcessResultsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListProcessResultsRequestOrderBy) Values() []ListProcessResultsRequestOrderBy {
return []ListProcessResultsRequestOrderBy{
"created_at_desc",
"created_at_asc",
}
}
func (enum ListProcessResultsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListProcessResultsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListProcessResultsRequestOrderBy(ListProcessResultsRequestOrderBy(tmp).String())
return nil
}
type ListProcessesRequestOrderBy string
const (
ListProcessesRequestOrderByCreatedAtDesc = ListProcessesRequestOrderBy("created_at_desc")
ListProcessesRequestOrderByCreatedAtAsc = ListProcessesRequestOrderBy("created_at_asc")
ListProcessesRequestOrderByNameAsc = ListProcessesRequestOrderBy("name_asc")
ListProcessesRequestOrderByNameDesc = ListProcessesRequestOrderBy("name_desc")
ListProcessesRequestOrderByStartedAtAsc = ListProcessesRequestOrderBy("started_at_asc")
ListProcessesRequestOrderByStartedAtDesc = ListProcessesRequestOrderBy("started_at_desc")
ListProcessesRequestOrderByStatusAsc = ListProcessesRequestOrderBy("status_asc")
ListProcessesRequestOrderByStatusDesc = ListProcessesRequestOrderBy("status_desc")
)
func (enum ListProcessesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListProcessesRequestOrderBy) Values() []ListProcessesRequestOrderBy {
return []ListProcessesRequestOrderBy{
"created_at_desc",
"created_at_asc",
"name_asc",
"name_desc",
"started_at_asc",
"started_at_desc",
"status_asc",
"status_desc",
}
}
func (enum ListProcessesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListProcessesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListProcessesRequestOrderBy(ListProcessesRequestOrderBy(tmp).String())
return nil
}
type ListSessionACLsRequestOrderBy string
const (
ListSessionACLsRequestOrderByAccessAsc = ListSessionACLsRequestOrderBy("access_asc")
ListSessionACLsRequestOrderByAccessDesc = ListSessionACLsRequestOrderBy("access_desc")
)
func (enum ListSessionACLsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "access_asc"
}
return string(enum)
}
func (enum ListSessionACLsRequestOrderBy) Values() []ListSessionACLsRequestOrderBy {
return []ListSessionACLsRequestOrderBy{
"access_asc",
"access_desc",
}
}
func (enum ListSessionACLsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSessionACLsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSessionACLsRequestOrderBy(ListSessionACLsRequestOrderBy(tmp).String())
return nil
}
type ListSessionsRequestOrderBy string
const (
ListSessionsRequestOrderByNameAsc = ListSessionsRequestOrderBy("name_asc")
ListSessionsRequestOrderByNameDesc = ListSessionsRequestOrderBy("name_desc")
ListSessionsRequestOrderByStartedAtAsc = ListSessionsRequestOrderBy("started_at_asc")
ListSessionsRequestOrderByStartedAtDesc = ListSessionsRequestOrderBy("started_at_desc")
ListSessionsRequestOrderByStatusAsc = ListSessionsRequestOrderBy("status_asc")
ListSessionsRequestOrderByStatusDesc = ListSessionsRequestOrderBy("status_desc")
ListSessionsRequestOrderByCreatedAtDesc = ListSessionsRequestOrderBy("created_at_desc")
ListSessionsRequestOrderByCreatedAtAsc = ListSessionsRequestOrderBy("created_at_asc")
)
func (enum ListSessionsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListSessionsRequestOrderBy) Values() []ListSessionsRequestOrderBy {
return []ListSessionsRequestOrderBy{
"name_asc",
"name_desc",
"started_at_asc",
"started_at_desc",
"status_asc",
"status_desc",
"created_at_desc",
"created_at_asc",
}
}
func (enum ListSessionsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSessionsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSessionsRequestOrderBy(ListSessionsRequestOrderBy(tmp).String())
return nil
}
type PlatformAvailability string
const (
PlatformAvailabilityUnknownAvailability = PlatformAvailability("unknown_availability")
PlatformAvailabilityAvailable = PlatformAvailability("available")
PlatformAvailabilityShortage = PlatformAvailability("shortage")
PlatformAvailabilityScarce = PlatformAvailability("scarce")
)
func (enum PlatformAvailability) String() string {
if enum == "" {
// return default value if empty
return "unknown_availability"
}
return string(enum)
}
func (enum PlatformAvailability) Values() []PlatformAvailability {
return []PlatformAvailability{
"unknown_availability",
"available",
"shortage",
"scarce",
}
}
func (enum PlatformAvailability) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlatformAvailability) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlatformAvailability(PlatformAvailability(tmp).String())
return nil
}
type PlatformTechnology string
const (
PlatformTechnologyUnknownTechnology = PlatformTechnology("unknown_technology")
PlatformTechnologyPhotonic = PlatformTechnology("photonic")
PlatformTechnologyGeneralPurpose = PlatformTechnology("general_purpose")
)
func (enum PlatformTechnology) String() string {
if enum == "" {
// return default value if empty
return "unknown_technology"
}
return string(enum)
}
func (enum PlatformTechnology) Values() []PlatformTechnology {
return []PlatformTechnology{
"unknown_technology",
"photonic",
"general_purpose",
}
}
func (enum PlatformTechnology) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlatformTechnology) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlatformTechnology(PlatformTechnology(tmp).String())
return nil
}
type PlatformType string
const (
PlatformTypeUnknownType = PlatformType("unknown_type")
PlatformTypeSimulator = PlatformType("simulator")
PlatformTypeQpu = PlatformType("qpu")
)
func (enum PlatformType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum PlatformType) Values() []PlatformType {
return []PlatformType{
"unknown_type",
"simulator",
"qpu",
}
}
func (enum PlatformType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlatformType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlatformType(PlatformType(tmp).String())
return nil
}
type ProcessStatus string
const (
ProcessStatusUnknownStatus = ProcessStatus("unknown_status")
ProcessStatusError = ProcessStatus("error")
ProcessStatusStarting = ProcessStatus("starting")
ProcessStatusRunning = ProcessStatus("running")
ProcessStatusCompleted = ProcessStatus("completed")
ProcessStatusCancelling = ProcessStatus("cancelling")
ProcessStatusCancelled = ProcessStatus("cancelled")
)
func (enum ProcessStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum ProcessStatus) Values() []ProcessStatus {
return []ProcessStatus{
"unknown_status",
"error",
"starting",
"running",
"completed",
"cancelling",
"cancelled",
}
}
func (enum ProcessStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ProcessStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ProcessStatus(ProcessStatus(tmp).String())
return nil
}
type SessionAccess string
const (
SessionAccessUnknownAccess = SessionAccess("unknown_access")
SessionAccessFull = SessionAccess("full")
SessionAccessReadSession = SessionAccess("read_session")
SessionAccessReadWriteSession = SessionAccess("read_write_session")
SessionAccessReadJobResult = SessionAccess("read_job_result")
SessionAccessReadJobCircuit = SessionAccess("read_job_circuit")
SessionAccessReadJob = SessionAccess("read_job")
SessionAccessReadWriteJob = SessionAccess("read_write_job")
)
func (enum SessionAccess) String() string {
if enum == "" {
// return default value if empty
return "unknown_access"
}
return string(enum)
}
func (enum SessionAccess) Values() []SessionAccess {
return []SessionAccess{
"unknown_access",
"full",
"read_session",
"read_write_session",
"read_job_result",
"read_job_circuit",
"read_job",
"read_write_job",
}
}
func (enum SessionAccess) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SessionAccess) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SessionAccess(SessionAccess(tmp).String())
return nil
}
type SessionOriginType string
const (
SessionOriginTypeUnknownOriginType = SessionOriginType("unknown_origin_type")
SessionOriginTypeCustomer = SessionOriginType("customer")
SessionOriginTypeProcess = SessionOriginType("process")
)
func (enum SessionOriginType) String() string {
if enum == "" {
// return default value if empty
return "unknown_origin_type"
}
return string(enum)
}
func (enum SessionOriginType) Values() []SessionOriginType {
return []SessionOriginType{
"unknown_origin_type",
"customer",
"process",
}
}
func (enum SessionOriginType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SessionOriginType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SessionOriginType(SessionOriginType(tmp).String())
return nil
}
type SessionStatus string
const (
SessionStatusUnknownStatus = SessionStatus("unknown_status")
SessionStatusRunning = SessionStatus("running")
SessionStatusStopped = SessionStatus("stopped")
SessionStatusStarting = SessionStatus("starting")
SessionStatusStopping = SessionStatus("stopping")
)
func (enum SessionStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SessionStatus) Values() []SessionStatus {
return []SessionStatus{
"unknown_status",
"running",
"stopped",
"starting",
"stopping",
}
}
func (enum SessionStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SessionStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SessionStatus(SessionStatus(tmp).String())
return nil
}
// PlatformHardware: platform hardware.
type PlatformHardware struct {
// Name: product name of the hardware.
Name string `json:"name"`
// Vcpus: number of vCPUs available.
Vcpus uint32 `json:"vcpus"`
// Gpus: number of GPUs available (0 if no GPU).
Gpus uint32 `json:"gpus"`
// GpusNetwork: network topology of GPUs (PCIe, NVLink...).
GpusNetwork string `json:"gpus_network"`
// RAM: amount of RAM available in byte.
RAM uint64 `json:"ram"`
// Vram: amount of VRAM available in byte (0 if no GPU).
Vram uint64 `json:"vram"`
}
// JobCircuit: job circuit.
type JobCircuit struct {
// PercevalCircuit: circuit generated by Perceval that should be executed.
// Precisely one of PercevalCircuit, QiskitCircuit must be set.
PercevalCircuit *string `json:"perceval_circuit,omitempty"`
// QiskitCircuit: circuit generated by Qiskit that should be executed.
// Precisely one of PercevalCircuit, QiskitCircuit must be set.
QiskitCircuit *string `json:"qiskit_circuit,omitempty"`
}
// Application: application.
type Application struct {
// ID: unique ID of the application.
ID string `json:"id"`
// Name: name of the application.
Name string `json:"name"`
// Type: type of the application.
// Default value: unknown_type
Type ApplicationType `json:"type"`
// CompatiblePlatformIDs: list of compatible platform (by IDs) able to run this application.
CompatiblePlatformIDs []string `json:"compatible_platform_ids"`
// InputTemplate: JSON format describing the expected input.
InputTemplate string `json:"input_template"`
}
// JobResult: job result.
type JobResult struct {
// JobID: ID of the parent job.
JobID string `json:"job_id"`
// Result: result in JSON format.
Result *string `json:"result"`
// URL: URL to download a large result (optional).
URL *string `json:"url"`
// CreatedAt: creation time of the result.
CreatedAt *time.Time `json:"created_at"`
}
// Job: job.
type Job struct {
// ID: unique ID of the job.
ID string `json:"id"`
// Name: job name.
Name string `json:"name"`
// Tags: tags of the job.
Tags *[]string `json:"tags"`
// SessionID: session ID in which the job is executed.
SessionID string `json:"session_id"`
// CreatedAt: time at which the job was created.
CreatedAt *time.Time `json:"created_at"`
// StartedAt: time at which the job was started.
StartedAt *time.Time `json:"started_at"`
// UpdatedAt: time at which the job was updated.
UpdatedAt *time.Time `json:"updated_at"`
// Status: job status.
// Default value: unknown_status
Status JobStatus `json:"status"`
// ProgressMessage: last progress message, if the job has started.
ProgressMessage *string `json:"progress_message"`
// JobDuration: duration of the job, if the job is finished.
JobDuration *scw.Duration `json:"job_duration"`
// ResultDistribution: result of the job, if the job is finished.
ResultDistribution *string `json:"result_distribution"`
}
// Platform: platform.
type Platform struct {
// ID: unique ID of the platform.
ID string `json:"id"`
// Version: verison of the platform.
Version string `json:"version"`
// Name: name of the platform.
Name string `json:"name"`
// ProviderName: provider name of the platform.
ProviderName string `json:"provider_name"`
// BackendName: name of the running backend over the platform (ascella, qsim, aer...).
BackendName string `json:"backend_name"`
// Type: type of the platform.
// Default value: unknown_type
Type PlatformType `json:"type"`
// Technology: technology used by the platform.
// Default value: unknown_technology
Technology PlatformTechnology `json:"technology"`
// MaxQubitCount: estimated maximum number of qubits supported by the platform.
MaxQubitCount uint32 `json:"max_qubit_count"`
// Availability: availability of the platform.
// Default value: unknown_availability
Availability PlatformAvailability `json:"availability"`
// Metadata: metadata provided by the platform.
Metadata string `json:"metadata"`
// PricePerHour: price to be payed per hour (excluding free tiers).
PricePerHour *scw.Money `json:"price_per_hour"`
// Hardware: specifications of the underlying hardware.
Hardware *PlatformHardware `json:"hardware"`
}
// ProcessResult: process result.
type ProcessResult struct {
// ProcessID: ID of the parent process.
ProcessID string `json:"process_id"`
// Result: result in JSON format.
Result string `json:"result"`
// CreatedAt: creation time of the result.
CreatedAt *time.Time `json:"created_at"`
}
// Process: process.
type Process struct {
// ID: unique ID of the process.
ID string `json:"id"`
// Name: name of the process.
Name string `json:"name"`
// ApplicationID: application ID for which the process has been created.
ApplicationID *string `json:"application_id"`
// PlatformID: platform ID for which the process has been created.
PlatformID *string `json:"platform_id"`
// AttachedSessionIDs: list of sessions generated by the process.
AttachedSessionIDs []string `json:"attached_session_ids"`
// CreatedAt: tme at which the process was created.
CreatedAt *time.Time `json:"created_at"`
// StartedAt: time at which the process started.
StartedAt *time.Time `json:"started_at"`
// UpdatedAt: time at which the process was updated.
UpdatedAt *time.Time `json:"updated_at"`
// FinishedAt: time at which the process was finished.
FinishedAt *time.Time `json:"finished_at"`
// Status: status of the process.
// Default value: unknown_status
Status ProcessStatus `json:"status"`
// ProjectID: project ID in which the process has been created.
ProjectID string `json:"project_id"`
// Tags: tags of the process.
Tags []string `json:"tags"`
// Progress: progress of the process, from 0 to 1.
Progress *uint32 `json:"progress"`
// ProgressMessage: any progress of the process.
ProgressMessage *string `json:"progress_message"`
// Input: input payload of the process as JSON string.
Input *string `json:"input"`
}
// Session: session.
type Session struct {
// ID: unique ID of the session.
ID string `json:"id"`
// Name: name of the session.
Name string `json:"name"`
// PlatformID: platform ID for which the session has been created.
PlatformID string `json:"platform_id"`
// CreatedAt: the time at which the session was created.
CreatedAt *time.Time `json:"created_at"`
// StartedAt: the time at which the session started.
StartedAt *time.Time `json:"started_at"`
// UpdatedAt: the time at which the session was updated.
UpdatedAt *time.Time `json:"updated_at"`
// TerminatedAt: the time at which the session was terminated.
TerminatedAt *time.Time `json:"terminated_at"`
// MaxIDleDuration: maximum idle time before the session ends.
MaxIDleDuration *scw.Duration `json:"max_idle_duration"`
// MaxDuration: maximum duration before the session ends.
MaxDuration *scw.Duration `json:"max_duration"`
// WaitingJobCount: number of waiting jobs linked to the session.
WaitingJobCount uint64 `json:"waiting_job_count"`
// FinishedJobCount: number of finished jobs linked to the session.
FinishedJobCount uint64 `json:"finished_job_count"`
// Status: status of the session.
// Default value: unknown_status
Status SessionStatus `json:"status"`
// ProjectID: project ID in which the session has been created.
ProjectID string `json:"project_id"`
// Tags: tags of the session.
Tags *[]string `json:"tags"`
// DeduplicationID: deduplication ID of the session.
DeduplicationID string `json:"deduplication_id"`
// OriginType: resource type that creates the session.
// Default value: unknown_origin_type
OriginType SessionOriginType `json:"origin_type"`
// OriginID: unique ID of the session's origin resource (if exists).
OriginID *string `json:"origin_id"`
// ProgressMessage: any progress of the session.
ProgressMessage *string `json:"progress_message"`
}
// CancelJobRequest: cancel job request.
type CancelJobRequest struct {
// JobID: unique ID of the job.
JobID string `json:"-"`
}
// CancelProcessRequest: cancel process request.
type CancelProcessRequest struct {
// ProcessID: unique ID of the process.
ProcessID string `json:"-"`
}
// CreateJobRequest: create job request.
type CreateJobRequest struct {
// Name: name of the job.
Name string `json:"name"`
// Tags: tags of the job.
Tags *[]string `json:"tags,omitempty"`
// SessionID: session in which the job is executed.
SessionID string `json:"session_id"`
// Circuit: quantum circuit that should be executed.
Circuit *JobCircuit `json:"circuit"`
// MaxDuration: maximum duration of the job.
MaxDuration *scw.Duration `json:"max_duration,omitempty"`
}
// CreateProcessRequest: create process request.
type CreateProcessRequest struct {
// ProjectID: ID of the project in which the process was created.
ProjectID string `json:"project_id"`
// PlatformID: ID of the platform for which the process was created.
PlatformID *string `json:"platform_id,omitempty"`
// ApplicationID: ID of the application for which the process was created.
ApplicationID *string `json:"application_id,omitempty"`
// Name: name of the process.
Name string `json:"name"`
// Input: process parameters in JSON format.
Input *string `json:"input,omitempty"`
// Tags: tags of the process.
Tags []string `json:"tags"`
}
// CreateSessionRequest: create session request.
type CreateSessionRequest struct {
// ProjectID: ID of the Project in which the session was created.
ProjectID string `json:"project_id"`
// PlatformID: ID of the Platform for which the session was created.
PlatformID string `json:"platform_id"`
// Name: name of the session.
Name *string `json:"name,omitempty"`
// MaxIDleDuration: maximum idle duration before the session ends.
MaxIDleDuration *scw.Duration `json:"max_idle_duration,omitempty"`
// MaxDuration: maximum duration before the session ends.
MaxDuration *scw.Duration `json:"max_duration,omitempty"`
// Tags: tags of the session.
Tags *[]string `json:"tags,omitempty"`
// DeduplicationID: deduplication ID of the session.
DeduplicationID *string `json:"deduplication_id,omitempty"`
}
// DeleteJobRequest: delete job request.
type DeleteJobRequest struct {
// JobID: unique ID of the job.
JobID string `json:"-"`
}
// DeleteProcessRequest: delete process request.
type DeleteProcessRequest struct {
// ProcessID: unique ID of the process.
ProcessID string `json:"-"`
}
// DeleteSessionRequest: delete session request.
type DeleteSessionRequest struct {
// SessionID: unique ID of the session.
SessionID string `json:"-"`
}
// GetApplicationRequest: get application request.
type GetApplicationRequest struct {
// ApplicationID: unique ID of the application.
ApplicationID string `json:"-"`
}
// GetJobCircuitRequest: get job circuit request.
type GetJobCircuitRequest struct {
// JobID: unique ID of the job.
JobID string `json:"-"`
}
// GetJobRequest: get job request.
type GetJobRequest struct {
// JobID: unique ID of the job you want to get.
JobID string `json:"-"`
}
// GetPlatformRequest: get platform request.
type GetPlatformRequest struct {
// PlatformID: unique ID of the platform.
PlatformID string `json:"-"`
}
// GetProcessRequest: get process request.
type GetProcessRequest struct {
// ProcessID: unique ID of the process.
ProcessID string `json:"-"`
}
// GetSessionRequest: get session request.
type GetSessionRequest struct {
// SessionID: unique ID of the session.
SessionID string `json:"-"`
}
// ListApplicationsRequest: list applications request.
type ListApplicationsRequest struct {
// Name: list applications with this name.
Name *string `json:"-"`
// ApplicationType: list applications with this type.
// Default value: unknown_type
ApplicationType ApplicationType `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of applications a to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned applications.
// Default value: name_asc
OrderBy ListApplicationsRequestOrderBy `json:"-"`
}
// ListApplicationsResponse: list applications response.
type ListApplicationsResponse struct {
// TotalCount: total number of applications.
TotalCount uint64 `json:"total_count"`
// Applications: list of applications.
Applications []*Application `json:"applications"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListApplicationsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListApplicationsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListApplicationsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Applications = append(r.Applications, results.Applications...)
r.TotalCount += uint64(len(results.Applications))
return uint64(len(results.Applications)), nil
}
// ListJobResultsRequest: list job results request.
type ListJobResultsRequest struct {
// JobID: ID of the job.
JobID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of results to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned results.
// Default value: created_at_desc
OrderBy ListJobResultsRequestOrderBy `json:"-"`
}
// ListJobResultsResponse: list job results response.
type ListJobResultsResponse struct {
// TotalCount: total number of results.
TotalCount uint64 `json:"total_count"`
// JobResults: list of results.
JobResults []*JobResult `json:"job_results"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJobResultsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJobResultsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJobResultsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.JobResults = append(r.JobResults, results.JobResults...)
r.TotalCount += uint64(len(results.JobResults))
return uint64(len(results.JobResults)), nil
}
// ListJobsRequest: list jobs request.
type ListJobsRequest struct {
// SessionID: list jobs with this session ID.
// Precisely one of SessionID, ProjectID must be set.
SessionID *string `json:"session_id,omitempty"`
// ProjectID: list jobs with this project ID.
// Precisely one of SessionID, ProjectID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Tags: list jobs with these tags.
Tags []string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of jobs to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned jobs.
// Default value: created_at_desc
OrderBy ListJobsRequestOrderBy `json:"-"`
}
// ListJobsResponse: list jobs response.
type ListJobsResponse struct {
// TotalCount: total number of jobs.
TotalCount uint64 `json:"total_count"`
// Jobs: list of jobs.
Jobs []*Job `json:"jobs"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListJobsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListJobsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListJobsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Jobs = append(r.Jobs, results.Jobs...)
r.TotalCount += uint64(len(results.Jobs))
return uint64(len(results.Jobs)), nil
}
// ListPlatformsRequest: list platforms request.
type ListPlatformsRequest struct {
// ProviderName: list platforms with this provider name.
ProviderName *string `json:"-"`
// BackendName: list platforms with this backend name.
BackendName *string `json:"-"`
// Name: list platforms with this name.
Name *string `json:"-"`
// PlatformType: list platforms with this type.
// Default value: unknown_type
PlatformType PlatformType `json:"-"`
// PlatformTechnology: list platforms with this technology.
// Default value: unknown_technology
PlatformTechnology PlatformTechnology `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of platforms to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned platforms.
// Default value: name_asc
OrderBy ListPlatformsRequestOrderBy `json:"-"`
}
// ListPlatformsResponse: list platforms response.
type ListPlatformsResponse struct {
// TotalCount: total number of platforms.
TotalCount uint64 `json:"total_count"`
// Platforms: list of platforms.
Platforms []*Platform `json:"platforms"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPlatformsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPlatformsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPlatformsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Platforms = append(r.Platforms, results.Platforms...)
r.TotalCount += uint64(len(results.Platforms))
return uint64(len(results.Platforms)), nil
}
// ListProcessResultsRequest: list process results request.
type ListProcessResultsRequest struct {
// ProcessID: ID of the process.
ProcessID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of results to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned results.
// Default value: created_at_desc
OrderBy ListProcessResultsRequestOrderBy `json:"-"`
}
// ListProcessResultsResponse: list process results response.
type ListProcessResultsResponse struct {
// TotalCount: total number of results.
TotalCount uint64 `json:"total_count"`
// ProcessResults: list of results.
ProcessResults []*ProcessResult `json:"process_results"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListProcessResultsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListProcessResultsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListProcessResultsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ProcessResults = append(r.ProcessResults, results.ProcessResults...)
r.TotalCount += uint64(len(results.ProcessResults))
return uint64(len(results.ProcessResults)), nil
}
// ListProcessesRequest: list processes request.
type ListProcessesRequest struct {
// ApplicationID: list processes that have been created for this application.
ApplicationID *string `json:"-"`
// Tags: list processes with these tags.
Tags []string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of processes to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned processes.
// Default value: created_at_desc
OrderBy ListProcessesRequestOrderBy `json:"-"`
// ProjectID: list processes belonging to this project ID.
ProjectID string `json:"-"`
}
// ListProcessesResponse: list processes response.
type ListProcessesResponse struct {
// TotalCount: total number of processes.
TotalCount uint64 `json:"total_count"`
// Processes: list of processes.
Processes []*Process `json:"processes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListProcessesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListProcessesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListProcessesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Processes = append(r.Processes, results.Processes...)
r.TotalCount += uint64(len(results.Processes))
return uint64(len(results.Processes)), nil
}
// ListSessionACLsRequest: list session ac ls request.
type ListSessionACLsRequest struct {
SessionID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: access_asc
OrderBy ListSessionACLsRequestOrderBy `json:"-"`
}
// ListSessionACLsResponse: list session ac ls response.
type ListSessionACLsResponse struct {
TotalCount uint64 `json:"total_count"`
ACLs []SessionAccess `json:"acls"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSessionACLsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSessionACLsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSessionACLsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ACLs = append(r.ACLs, results.ACLs...)
r.TotalCount += uint64(len(results.ACLs))
return uint64(len(results.ACLs)), nil
}
// ListSessionsRequest: list sessions request.
type ListSessionsRequest struct {
// PlatformID: list sessions that have been created for this platform.
PlatformID *string `json:"-"`
// Tags: list sessions with these tags.
Tags []string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: maximum number of sessions to return per page.
PageSize *uint32 `json:"-"`
// OrderBy: sort order of the returned sessions.
// Default value: name_asc
OrderBy ListSessionsRequestOrderBy `json:"-"`
// ProjectID: list sessions belonging to this project ID.
ProjectID string `json:"-"`
}
// ListSessionsResponse: list sessions response.
type ListSessionsResponse struct {
// TotalCount: total number of sessions.
TotalCount uint64 `json:"total_count"`
// Sessions: list of sessions.
Sessions []*Session `json:"sessions"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSessionsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSessionsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSessionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Sessions = append(r.Sessions, results.Sessions...)
r.TotalCount += uint64(len(results.Sessions))
return uint64(len(results.Sessions)), nil
}
// TerminateSessionRequest: terminate session request.
type TerminateSessionRequest struct {
// SessionID: unique ID of the session.
SessionID string `json:"-"`
}
// UpdateJobRequest: update job request.
type UpdateJobRequest struct {
// JobID: unique ID of the job.
JobID string `json:"-"`
// Name: name of the job.
Name *string `json:"name,omitempty"`
// Tags: tags of the job.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateProcessRequest: update process request.
type UpdateProcessRequest struct {
// ProcessID: unique ID of the process.
ProcessID string `json:"-"`
// Name: name of the process.
Name *string `json:"name,omitempty"`
// Tags: tags of the process.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateSessionRequest: update session request.
type UpdateSessionRequest struct {
// SessionID: unique ID of the session.
SessionID string `json:"-"`
// Name: name of the session.
Name *string `json:"name,omitempty"`
// MaxIDleDuration: maximum idle duration before the session ends.
MaxIDleDuration *scw.Duration `json:"max_idle_duration,omitempty"`
// MaxDuration: maximum time before the session ends.
MaxDuration *scw.Duration `json:"max_duration,omitempty"`
// Tags: tags of the session.
Tags *[]string `json:"tags,omitempty"`
}
// This API allows you to manage Scaleway Quantum as a Service.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// GetJob: Retrieve information about the provided **job ID**, such as status, payload, and result.
func (s *API) GetJob(req *GetJobRequest, opts ...scw.RequestOption) (*Job, error) {
var err error
if fmt.Sprint(req.JobID) == "" {
return nil, errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "",
}
var resp Job
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobs: Retrieve information about all jobs within a given project or session.
func (s *API) ListJobs(req *ListJobsRequest, opts ...scw.RequestOption) (*ListJobsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.SessionID == nil && req.ProjectID == nil {
req.ProjectID = &defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "session_id", req.SessionID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/jobs",
Query: query,
}
var resp ListJobsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListJobResults: Retrieve all intermediate and final results of a job.
func (s *API) ListJobResults(req *ListJobResultsRequest, opts ...scw.RequestOption) (*ListJobResultsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.JobID) == "" {
return nil, errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "/results",
Query: query,
}
var resp ListJobResultsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateJob: Create a job to be executed inside a session.
func (s *API) CreateJob(req *CreateJobRequest, opts ...scw.RequestOption) (*Job, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/jobs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Job
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateJob: Update job information about the provided **job ID**.
func (s *API) UpdateJob(req *UpdateJobRequest, opts ...scw.RequestOption) (*Job, error) {
var err error
if fmt.Sprint(req.JobID) == "" {
return nil, errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Job
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CancelJob: Cancel the job corresponding to the provided **job ID**.
func (s *API) CancelJob(req *CancelJobRequest, opts ...scw.RequestOption) (*Job, error) {
var err error
if fmt.Sprint(req.JobID) == "" {
return nil, errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "/cancel",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Job
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteJob: Delete the job corresponding to the provided **job ID**.
func (s *API) DeleteJob(req *DeleteJobRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.JobID) == "" {
return errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetJobCircuit: Retrieve the circuit of the provided **job ID**.
func (s *API) GetJobCircuit(req *GetJobCircuitRequest, opts ...scw.RequestOption) (*JobCircuit, error) {
var err error
if fmt.Sprint(req.JobID) == "" {
return nil, errors.New("field JobID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/jobs/" + fmt.Sprint(req.JobID) + "/circuit",
}
var resp JobCircuit
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPlatform: Retrieve information about the provided **platform ID**, such as provider name, technology, and type.
func (s *API) GetPlatform(req *GetPlatformRequest, opts ...scw.RequestOption) (*Platform, error) {
var err error
if fmt.Sprint(req.PlatformID) == "" {
return nil, errors.New("field PlatformID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/platforms/" + fmt.Sprint(req.PlatformID) + "",
}
var resp Platform
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPlatforms: Retrieve information about all platforms.
func (s *API) ListPlatforms(req *ListPlatformsRequest, opts ...scw.RequestOption) (*ListPlatformsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "provider_name", req.ProviderName)
parameter.AddToQuery(query, "backend_name", req.BackendName)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "platform_type", req.PlatformType)
parameter.AddToQuery(query, "platform_technology", req.PlatformTechnology)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/platforms",
Query: query,
}
var resp ListPlatformsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSession: Retrieve information about the provided **session ID**, such as name, status, and number of executed jobs.
func (s *API) GetSession(req *GetSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if fmt.Sprint(req.SessionID) == "" {
return nil, errors.New("field SessionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/sessions/" + fmt.Sprint(req.SessionID) + "",
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSessions: Retrieve information about all sessions.
func (s *API) ListSessions(req *ListSessionsRequest, opts ...scw.RequestOption) (*ListSessionsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "platform_id", req.PlatformID)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/sessions",
Query: query,
}
var resp ListSessionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSession: Create a dedicated session for the specified platform.
func (s *API) CreateSession(req *CreateSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/sessions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSession: Update session information of the provided **session ID**.
func (s *API) UpdateSession(req *UpdateSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if fmt.Sprint(req.SessionID) == "" {
return nil, errors.New("field SessionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/qaas/v1alpha1/sessions/" + fmt.Sprint(req.SessionID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// TerminateSession: Terminate a session by its unique ID and cancel all its attached jobs.
func (s *API) TerminateSession(req *TerminateSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if fmt.Sprint(req.SessionID) == "" {
return nil, errors.New("field SessionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/sessions/" + fmt.Sprint(req.SessionID) + "/terminate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSession: Delete a session by its unique ID and delete all its attached jobs.
func (s *API) DeleteSession(req *DeleteSessionRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.SessionID) == "" {
return errors.New("field SessionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/qaas/v1alpha1/sessions/" + fmt.Sprint(req.SessionID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListSessionACLs:
func (s *API) ListSessionACLs(req *ListSessionACLsRequest, opts ...scw.RequestOption) (*ListSessionACLsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.SessionID) == "" {
return nil, errors.New("field SessionID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/sessions/" + fmt.Sprint(req.SessionID) + "/acls",
Query: query,
}
var resp ListSessionACLsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateProcess: Create a new process for the specified application on a specified platform.
func (s *API) CreateProcess(req *CreateProcessRequest, opts ...scw.RequestOption) (*Process, error) {
var err error
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/processes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Process
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetProcess: Retrieve information about the provided **process ID**, such as name, status and progress.
func (s *API) GetProcess(req *GetProcessRequest, opts ...scw.RequestOption) (*Process, error) {
var err error
if fmt.Sprint(req.ProcessID) == "" {
return nil, errors.New("field ProcessID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/processes/" + fmt.Sprint(req.ProcessID) + "",
}
var resp Process
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListProcesses: Retrieve information about all processes.
func (s *API) ListProcesses(req *ListProcessesRequest, opts ...scw.RequestOption) (*ListProcessesResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "application_id", req.ApplicationID)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/processes",
Query: query,
}
var resp ListProcessesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateProcess: Update process information of the provided **process ID**.
func (s *API) UpdateProcess(req *UpdateProcessRequest, opts ...scw.RequestOption) (*Process, error) {
var err error
if fmt.Sprint(req.ProcessID) == "" {
return nil, errors.New("field ProcessID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/qaas/v1alpha1/processes/" + fmt.Sprint(req.ProcessID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Process
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CancelProcess: Cancel a process by its unique ID. Intermediate results are still available.
func (s *API) CancelProcess(req *CancelProcessRequest, opts ...scw.RequestOption) (*Process, error) {
var err error
if fmt.Sprint(req.ProcessID) == "" {
return nil, errors.New("field ProcessID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/qaas/v1alpha1/processes/" + fmt.Sprint(req.ProcessID) + "/cancel",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Process
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteProcess: Delete a process by its unique ID and delete all its data.
func (s *API) DeleteProcess(req *DeleteProcessRequest, opts ...scw.RequestOption) error {
var err error
if fmt.Sprint(req.ProcessID) == "" {
return errors.New("field ProcessID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/qaas/v1alpha1/processes/" + fmt.Sprint(req.ProcessID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListProcessResults: Retrieve all intermediate and final result of a process.
func (s *API) ListProcessResults(req *ListProcessResultsRequest, opts ...scw.RequestOption) (*ListProcessResultsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.ProcessID) == "" {
return nil, errors.New("field ProcessID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/processes/" + fmt.Sprint(req.ProcessID) + "/results",
Query: query,
}
var resp ListProcessResultsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetApplication: Retrieve information about the provided **applcation ID**, such as name, type and compatible platforms.
func (s *API) GetApplication(req *GetApplicationRequest, opts ...scw.RequestOption) (*Application, error) {
var err error
if fmt.Sprint(req.ApplicationID) == "" {
return nil, errors.New("field ApplicationID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/applications/" + fmt.Sprint(req.ApplicationID) + "",
}
var resp Application
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListApplications: Retrieve information about all applications.
func (s *API) ListApplications(req *ListApplicationsRequest, opts ...scw.RequestOption) (*ListApplicationsResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "application_type", req.ApplicationType)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/qaas/v1alpha1/applications",
Query: query,
}
var resp ListApplicationsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/ 0000775 0000000 0000000 00000000000 14747113137 0023564 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024112 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/v1/rdb_sdk.go 0000664 0000000 0000000 00000444277 14747113137 0026073 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package rdb provides methods and message types of the rdb v1 API.
package rdb
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ACLRuleAction string
const (
ACLRuleActionAllow = ACLRuleAction("allow")
ACLRuleActionDeny = ACLRuleAction("deny")
)
func (enum ACLRuleAction) String() string {
if enum == "" {
// return default value if empty
return "allow"
}
return string(enum)
}
func (enum ACLRuleAction) Values() []ACLRuleAction {
return []ACLRuleAction{
"allow",
"deny",
}
}
func (enum ACLRuleAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleAction(ACLRuleAction(tmp).String())
return nil
}
type ACLRuleDirection string
const (
ACLRuleDirectionInbound = ACLRuleDirection("inbound")
ACLRuleDirectionOutbound = ACLRuleDirection("outbound")
)
func (enum ACLRuleDirection) String() string {
if enum == "" {
// return default value if empty
return "inbound"
}
return string(enum)
}
func (enum ACLRuleDirection) Values() []ACLRuleDirection {
return []ACLRuleDirection{
"inbound",
"outbound",
}
}
func (enum ACLRuleDirection) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleDirection) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleDirection(ACLRuleDirection(tmp).String())
return nil
}
type ACLRuleProtocol string
const (
ACLRuleProtocolTCP = ACLRuleProtocol("tcp")
ACLRuleProtocolUDP = ACLRuleProtocol("udp")
ACLRuleProtocolIcmp = ACLRuleProtocol("icmp")
)
func (enum ACLRuleProtocol) String() string {
if enum == "" {
// return default value if empty
return "tcp"
}
return string(enum)
}
func (enum ACLRuleProtocol) Values() []ACLRuleProtocol {
return []ACLRuleProtocol{
"tcp",
"udp",
"icmp",
}
}
func (enum ACLRuleProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ACLRuleProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ACLRuleProtocol(ACLRuleProtocol(tmp).String())
return nil
}
type DatabaseBackupStatus string
const (
DatabaseBackupStatusUnknown = DatabaseBackupStatus("unknown")
DatabaseBackupStatusCreating = DatabaseBackupStatus("creating")
DatabaseBackupStatusReady = DatabaseBackupStatus("ready")
DatabaseBackupStatusRestoring = DatabaseBackupStatus("restoring")
DatabaseBackupStatusDeleting = DatabaseBackupStatus("deleting")
DatabaseBackupStatusError = DatabaseBackupStatus("error")
DatabaseBackupStatusExporting = DatabaseBackupStatus("exporting")
DatabaseBackupStatusLocked = DatabaseBackupStatus("locked")
)
func (enum DatabaseBackupStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DatabaseBackupStatus) Values() []DatabaseBackupStatus {
return []DatabaseBackupStatus{
"unknown",
"creating",
"ready",
"restoring",
"deleting",
"error",
"exporting",
"locked",
}
}
func (enum DatabaseBackupStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DatabaseBackupStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DatabaseBackupStatus(DatabaseBackupStatus(tmp).String())
return nil
}
type EndpointPrivateNetworkDetailsProvisioningMode string
const (
EndpointPrivateNetworkDetailsProvisioningModeStatic = EndpointPrivateNetworkDetailsProvisioningMode("static")
EndpointPrivateNetworkDetailsProvisioningModeIpam = EndpointPrivateNetworkDetailsProvisioningMode("ipam")
)
func (enum EndpointPrivateNetworkDetailsProvisioningMode) String() string {
if enum == "" {
// return default value if empty
return "static"
}
return string(enum)
}
func (enum EndpointPrivateNetworkDetailsProvisioningMode) Values() []EndpointPrivateNetworkDetailsProvisioningMode {
return []EndpointPrivateNetworkDetailsProvisioningMode{
"static",
"ipam",
}
}
func (enum EndpointPrivateNetworkDetailsProvisioningMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EndpointPrivateNetworkDetailsProvisioningMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EndpointPrivateNetworkDetailsProvisioningMode(EndpointPrivateNetworkDetailsProvisioningMode(tmp).String())
return nil
}
type EngineSettingPropertyType string
const (
EngineSettingPropertyTypeBOOLEAN = EngineSettingPropertyType("BOOLEAN")
EngineSettingPropertyTypeINT = EngineSettingPropertyType("INT")
EngineSettingPropertyTypeSTRING = EngineSettingPropertyType("STRING")
EngineSettingPropertyTypeFLOAT = EngineSettingPropertyType("FLOAT")
)
func (enum EngineSettingPropertyType) String() string {
if enum == "" {
// return default value if empty
return "BOOLEAN"
}
return string(enum)
}
func (enum EngineSettingPropertyType) Values() []EngineSettingPropertyType {
return []EngineSettingPropertyType{
"BOOLEAN",
"INT",
"STRING",
"FLOAT",
}
}
func (enum EngineSettingPropertyType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EngineSettingPropertyType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EngineSettingPropertyType(EngineSettingPropertyType(tmp).String())
return nil
}
type InstanceLogStatus string
const (
InstanceLogStatusUnknown = InstanceLogStatus("unknown")
InstanceLogStatusReady = InstanceLogStatus("ready")
InstanceLogStatusCreating = InstanceLogStatus("creating")
InstanceLogStatusError = InstanceLogStatus("error")
)
func (enum InstanceLogStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum InstanceLogStatus) Values() []InstanceLogStatus {
return []InstanceLogStatus{
"unknown",
"ready",
"creating",
"error",
}
}
func (enum InstanceLogStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceLogStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceLogStatus(InstanceLogStatus(tmp).String())
return nil
}
type InstanceStatus string
const (
InstanceStatusUnknown = InstanceStatus("unknown")
InstanceStatusReady = InstanceStatus("ready")
InstanceStatusProvisioning = InstanceStatus("provisioning")
InstanceStatusConfiguring = InstanceStatus("configuring")
InstanceStatusDeleting = InstanceStatus("deleting")
InstanceStatusError = InstanceStatus("error")
InstanceStatusAutohealing = InstanceStatus("autohealing")
InstanceStatusLocked = InstanceStatus("locked")
InstanceStatusInitializing = InstanceStatus("initializing")
InstanceStatusDiskFull = InstanceStatus("disk_full")
InstanceStatusBackuping = InstanceStatus("backuping")
InstanceStatusSnapshotting = InstanceStatus("snapshotting")
InstanceStatusRestarting = InstanceStatus("restarting")
)
func (enum InstanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum InstanceStatus) Values() []InstanceStatus {
return []InstanceStatus{
"unknown",
"ready",
"provisioning",
"configuring",
"deleting",
"error",
"autohealing",
"locked",
"initializing",
"disk_full",
"backuping",
"snapshotting",
"restarting",
}
}
func (enum InstanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *InstanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = InstanceStatus(InstanceStatus(tmp).String())
return nil
}
type ListDatabaseBackupsRequestOrderBy string
const (
ListDatabaseBackupsRequestOrderByCreatedAtAsc = ListDatabaseBackupsRequestOrderBy("created_at_asc")
ListDatabaseBackupsRequestOrderByCreatedAtDesc = ListDatabaseBackupsRequestOrderBy("created_at_desc")
ListDatabaseBackupsRequestOrderByNameAsc = ListDatabaseBackupsRequestOrderBy("name_asc")
ListDatabaseBackupsRequestOrderByNameDesc = ListDatabaseBackupsRequestOrderBy("name_desc")
ListDatabaseBackupsRequestOrderByStatusAsc = ListDatabaseBackupsRequestOrderBy("status_asc")
ListDatabaseBackupsRequestOrderByStatusDesc = ListDatabaseBackupsRequestOrderBy("status_desc")
)
func (enum ListDatabaseBackupsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDatabaseBackupsRequestOrderBy) Values() []ListDatabaseBackupsRequestOrderBy {
return []ListDatabaseBackupsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"status_asc",
"status_desc",
}
}
func (enum ListDatabaseBackupsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabaseBackupsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabaseBackupsRequestOrderBy(ListDatabaseBackupsRequestOrderBy(tmp).String())
return nil
}
type ListDatabasesRequestOrderBy string
const (
ListDatabasesRequestOrderByNameAsc = ListDatabasesRequestOrderBy("name_asc")
ListDatabasesRequestOrderByNameDesc = ListDatabasesRequestOrderBy("name_desc")
ListDatabasesRequestOrderBySizeAsc = ListDatabasesRequestOrderBy("size_asc")
ListDatabasesRequestOrderBySizeDesc = ListDatabasesRequestOrderBy("size_desc")
)
func (enum ListDatabasesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListDatabasesRequestOrderBy) Values() []ListDatabasesRequestOrderBy {
return []ListDatabasesRequestOrderBy{
"name_asc",
"name_desc",
"size_asc",
"size_desc",
}
}
func (enum ListDatabasesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabasesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabasesRequestOrderBy(ListDatabasesRequestOrderBy(tmp).String())
return nil
}
type ListInstanceLogsRequestOrderBy string
const (
ListInstanceLogsRequestOrderByCreatedAtAsc = ListInstanceLogsRequestOrderBy("created_at_asc")
ListInstanceLogsRequestOrderByCreatedAtDesc = ListInstanceLogsRequestOrderBy("created_at_desc")
)
func (enum ListInstanceLogsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInstanceLogsRequestOrderBy) Values() []ListInstanceLogsRequestOrderBy {
return []ListInstanceLogsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListInstanceLogsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInstanceLogsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInstanceLogsRequestOrderBy(ListInstanceLogsRequestOrderBy(tmp).String())
return nil
}
type ListInstancesRequestOrderBy string
const (
ListInstancesRequestOrderByCreatedAtAsc = ListInstancesRequestOrderBy("created_at_asc")
ListInstancesRequestOrderByCreatedAtDesc = ListInstancesRequestOrderBy("created_at_desc")
ListInstancesRequestOrderByNameAsc = ListInstancesRequestOrderBy("name_asc")
ListInstancesRequestOrderByNameDesc = ListInstancesRequestOrderBy("name_desc")
ListInstancesRequestOrderByRegion = ListInstancesRequestOrderBy("region")
ListInstancesRequestOrderByStatusAsc = ListInstancesRequestOrderBy("status_asc")
ListInstancesRequestOrderByStatusDesc = ListInstancesRequestOrderBy("status_desc")
)
func (enum ListInstancesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListInstancesRequestOrderBy) Values() []ListInstancesRequestOrderBy {
return []ListInstancesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"region",
"status_asc",
"status_desc",
}
}
func (enum ListInstancesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListInstancesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListInstancesRequestOrderBy(ListInstancesRequestOrderBy(tmp).String())
return nil
}
type ListPrivilegesRequestOrderBy string
const (
ListPrivilegesRequestOrderByUserNameAsc = ListPrivilegesRequestOrderBy("user_name_asc")
ListPrivilegesRequestOrderByUserNameDesc = ListPrivilegesRequestOrderBy("user_name_desc")
ListPrivilegesRequestOrderByDatabaseNameAsc = ListPrivilegesRequestOrderBy("database_name_asc")
ListPrivilegesRequestOrderByDatabaseNameDesc = ListPrivilegesRequestOrderBy("database_name_desc")
)
func (enum ListPrivilegesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "user_name_asc"
}
return string(enum)
}
func (enum ListPrivilegesRequestOrderBy) Values() []ListPrivilegesRequestOrderBy {
return []ListPrivilegesRequestOrderBy{
"user_name_asc",
"user_name_desc",
"database_name_asc",
"database_name_desc",
}
}
func (enum ListPrivilegesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPrivilegesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPrivilegesRequestOrderBy(ListPrivilegesRequestOrderBy(tmp).String())
return nil
}
type ListSnapshotsRequestOrderBy string
const (
ListSnapshotsRequestOrderByCreatedAtAsc = ListSnapshotsRequestOrderBy("created_at_asc")
ListSnapshotsRequestOrderByCreatedAtDesc = ListSnapshotsRequestOrderBy("created_at_desc")
ListSnapshotsRequestOrderByNameAsc = ListSnapshotsRequestOrderBy("name_asc")
ListSnapshotsRequestOrderByNameDesc = ListSnapshotsRequestOrderBy("name_desc")
ListSnapshotsRequestOrderByExpiresAtAsc = ListSnapshotsRequestOrderBy("expires_at_asc")
ListSnapshotsRequestOrderByExpiresAtDesc = ListSnapshotsRequestOrderBy("expires_at_desc")
)
func (enum ListSnapshotsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSnapshotsRequestOrderBy) Values() []ListSnapshotsRequestOrderBy {
return []ListSnapshotsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"expires_at_asc",
"expires_at_desc",
}
}
func (enum ListSnapshotsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSnapshotsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSnapshotsRequestOrderBy(ListSnapshotsRequestOrderBy(tmp).String())
return nil
}
type ListUsersRequestOrderBy string
const (
ListUsersRequestOrderByNameAsc = ListUsersRequestOrderBy("name_asc")
ListUsersRequestOrderByNameDesc = ListUsersRequestOrderBy("name_desc")
ListUsersRequestOrderByIsAdminAsc = ListUsersRequestOrderBy("is_admin_asc")
ListUsersRequestOrderByIsAdminDesc = ListUsersRequestOrderBy("is_admin_desc")
)
func (enum ListUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListUsersRequestOrderBy) Values() []ListUsersRequestOrderBy {
return []ListUsersRequestOrderBy{
"name_asc",
"name_desc",
"is_admin_asc",
"is_admin_desc",
}
}
func (enum ListUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListUsersRequestOrderBy(ListUsersRequestOrderBy(tmp).String())
return nil
}
type MaintenanceStatus string
const (
MaintenanceStatusUnknown = MaintenanceStatus("unknown")
MaintenanceStatusPending = MaintenanceStatus("pending")
MaintenanceStatusDone = MaintenanceStatus("done")
MaintenanceStatusCanceled = MaintenanceStatus("canceled")
MaintenanceStatusOngoing = MaintenanceStatus("ongoing")
)
func (enum MaintenanceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum MaintenanceStatus) Values() []MaintenanceStatus {
return []MaintenanceStatus{
"unknown",
"pending",
"done",
"canceled",
"ongoing",
}
}
func (enum MaintenanceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *MaintenanceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = MaintenanceStatus(MaintenanceStatus(tmp).String())
return nil
}
type NodeTypeGeneration string
const (
NodeTypeGenerationUnknownGeneration = NodeTypeGeneration("unknown_generation")
NodeTypeGenerationGenerationV1 = NodeTypeGeneration("generation_v1")
NodeTypeGenerationGenerationV2 = NodeTypeGeneration("generation_v2")
)
func (enum NodeTypeGeneration) String() string {
if enum == "" {
// return default value if empty
return "unknown_generation"
}
return string(enum)
}
func (enum NodeTypeGeneration) Values() []NodeTypeGeneration {
return []NodeTypeGeneration{
"unknown_generation",
"generation_v1",
"generation_v2",
}
}
func (enum NodeTypeGeneration) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeGeneration) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeGeneration(NodeTypeGeneration(tmp).String())
return nil
}
type NodeTypeStock string
const (
NodeTypeStockUnknown = NodeTypeStock("unknown")
NodeTypeStockLowStock = NodeTypeStock("low_stock")
NodeTypeStockOutOfStock = NodeTypeStock("out_of_stock")
NodeTypeStockAvailable = NodeTypeStock("available")
)
func (enum NodeTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NodeTypeStock) Values() []NodeTypeStock {
return []NodeTypeStock{
"unknown",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum NodeTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeStock(NodeTypeStock(tmp).String())
return nil
}
type Permission string
const (
PermissionReadonly = Permission("readonly")
PermissionReadwrite = Permission("readwrite")
PermissionAll = Permission("all")
PermissionCustom = Permission("custom")
PermissionNone = Permission("none")
)
func (enum Permission) String() string {
if enum == "" {
// return default value if empty
return "readonly"
}
return string(enum)
}
func (enum Permission) Values() []Permission {
return []Permission{
"readonly",
"readwrite",
"all",
"custom",
"none",
}
}
func (enum Permission) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Permission) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Permission(Permission(tmp).String())
return nil
}
type ReadReplicaStatus string
const (
ReadReplicaStatusUnknown = ReadReplicaStatus("unknown")
ReadReplicaStatusProvisioning = ReadReplicaStatus("provisioning")
ReadReplicaStatusInitializing = ReadReplicaStatus("initializing")
ReadReplicaStatusReady = ReadReplicaStatus("ready")
ReadReplicaStatusDeleting = ReadReplicaStatus("deleting")
ReadReplicaStatusError = ReadReplicaStatus("error")
ReadReplicaStatusLocked = ReadReplicaStatus("locked")
ReadReplicaStatusConfiguring = ReadReplicaStatus("configuring")
ReadReplicaStatusPromoting = ReadReplicaStatus("promoting")
)
func (enum ReadReplicaStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ReadReplicaStatus) Values() []ReadReplicaStatus {
return []ReadReplicaStatus{
"unknown",
"provisioning",
"initializing",
"ready",
"deleting",
"error",
"locked",
"configuring",
"promoting",
}
}
func (enum ReadReplicaStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ReadReplicaStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ReadReplicaStatus(ReadReplicaStatus(tmp).String())
return nil
}
type SnapshotStatus string
const (
SnapshotStatusUnknown = SnapshotStatus("unknown")
SnapshotStatusCreating = SnapshotStatus("creating")
SnapshotStatusReady = SnapshotStatus("ready")
SnapshotStatusRestoring = SnapshotStatus("restoring")
SnapshotStatusDeleting = SnapshotStatus("deleting")
SnapshotStatusError = SnapshotStatus("error")
SnapshotStatusLocked = SnapshotStatus("locked")
)
func (enum SnapshotStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum SnapshotStatus) Values() []SnapshotStatus {
return []SnapshotStatus{
"unknown",
"creating",
"ready",
"restoring",
"deleting",
"error",
"locked",
}
}
func (enum SnapshotStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SnapshotStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SnapshotStatus(SnapshotStatus(tmp).String())
return nil
}
type StorageClass string
const (
StorageClassUnknownStorageClass = StorageClass("unknown_storage_class")
StorageClassLssd = StorageClass("lssd")
StorageClassBssd = StorageClass("bssd")
StorageClassSbs = StorageClass("sbs")
)
func (enum StorageClass) String() string {
if enum == "" {
// return default value if empty
return "unknown_storage_class"
}
return string(enum)
}
func (enum StorageClass) Values() []StorageClass {
return []StorageClass{
"unknown_storage_class",
"lssd",
"bssd",
"sbs",
}
}
func (enum StorageClass) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *StorageClass) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = StorageClass(StorageClass(tmp).String())
return nil
}
type VolumeType string
const (
VolumeTypeLssd = VolumeType("lssd")
VolumeTypeBssd = VolumeType("bssd")
VolumeTypeSbs5k = VolumeType("sbs_5k")
VolumeTypeSbs15k = VolumeType("sbs_15k")
)
func (enum VolumeType) String() string {
if enum == "" {
// return default value if empty
return "lssd"
}
return string(enum)
}
func (enum VolumeType) Values() []VolumeType {
return []VolumeType{
"lssd",
"bssd",
"sbs_5k",
"sbs_15k",
}
}
func (enum VolumeType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *VolumeType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = VolumeType(VolumeType(tmp).String())
return nil
}
// EndpointDirectAccessDetails: endpoint direct access details.
type EndpointDirectAccessDetails struct {
}
// EndpointLoadBalancerDetails: endpoint load balancer details.
type EndpointLoadBalancerDetails struct {
}
// EndpointPrivateNetworkDetails: endpoint private network details.
type EndpointPrivateNetworkDetails struct {
// PrivateNetworkID: UUID of the private network.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: cIDR notation of the endpoint IPv4 address.
ServiceIP scw.IPNet `json:"service_ip"`
// Zone: private network zone.
Zone scw.Zone `json:"zone"`
// ProvisioningMode: how endpoint ips are provisioned.
// Default value: static
ProvisioningMode EndpointPrivateNetworkDetailsProvisioningMode `json:"provisioning_mode"`
}
// EndpointSpecPrivateNetworkIpamConfig: endpoint spec private network ipam config.
type EndpointSpecPrivateNetworkIpamConfig struct {
}
// ReadReplicaEndpointSpecPrivateNetworkIpamConfig: read replica endpoint spec private network ipam config.
type ReadReplicaEndpointSpecPrivateNetworkIpamConfig struct {
}
// EngineSetting: engine setting.
type EngineSetting struct {
// Name: setting name from the database engine.
Name string `json:"name"`
// DefaultValue: value set when not specified.
DefaultValue string `json:"default_value"`
// HotConfigurable: setting can be applied without restarting.
HotConfigurable bool `json:"hot_configurable"`
// Description: setting description.
Description string `json:"description"`
// PropertyType: setting type.
// Default value: BOOLEAN
PropertyType EngineSettingPropertyType `json:"property_type"`
// Unit: setting base unit.
Unit *string `json:"unit"`
// StringConstraint: validation regex for string type settings.
StringConstraint *string `json:"string_constraint"`
// IntMin: minimum value for int types.
IntMin *int32 `json:"int_min"`
// IntMax: maximum value for int types.
IntMax *int32 `json:"int_max"`
// FloatMin: minimum value for float types.
FloatMin *float32 `json:"float_min"`
// FloatMax: maximum value for float types.
FloatMax *float32 `json:"float_max"`
}
// Endpoint: endpoint.
type Endpoint struct {
// ID: UUID of the endpoint.
ID string `json:"id"`
// IP: iPv4 address of the endpoint.
// Precisely one of IP, Hostname must be set.
IP *net.IP `json:"ip,omitempty"`
// Port: TCP port of the endpoint.
Port uint32 `json:"port"`
// Name: name of the endpoint.
Name *string `json:"name"`
// PrivateNetwork: private Network details. One maximum per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
PrivateNetwork *EndpointPrivateNetworkDetails `json:"private_network,omitempty"`
// LoadBalancer: load balancer details. Public endpoint for Database Instance which is systematically present. One per Database Instance.
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
LoadBalancer *EndpointLoadBalancerDetails `json:"load_balancer,omitempty"`
// DirectAccess: direct access details. Public endpoint reserved for Read Replicas. One per Read Replica.
// Precisely one of PrivateNetwork, LoadBalancer, DirectAccess must be set.
DirectAccess *EndpointDirectAccessDetails `json:"direct_access,omitempty"`
// Hostname: hostname of the endpoint.
// Precisely one of IP, Hostname must be set.
Hostname *string `json:"hostname,omitempty"`
}
// EndpointSpecLoadBalancer: endpoint spec load balancer.
type EndpointSpecLoadBalancer struct {
}
// EndpointSpecPrivateNetwork: endpoint spec private network.
type EndpointSpecPrivateNetwork struct {
// PrivateNetworkID: UUID of the Private Network to be connected to the Database Instance.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: endpoint IPv4 address with a CIDR notation. Refer to the official Scaleway documentation to learn more about IP and subnet limitations.
// Precisely one of ServiceIP, IpamConfig must be set.
ServiceIP *scw.IPNet `json:"service_ip,omitempty"`
// IpamConfig: automated configuration of your Private Network endpoint with Scaleway IPAM service. One at the most per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of ServiceIP, IpamConfig must be set.
IpamConfig *EndpointSpecPrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
}
// ReadReplicaEndpointSpecDirectAccess: read replica endpoint spec direct access.
type ReadReplicaEndpointSpecDirectAccess struct {
}
// ReadReplicaEndpointSpecPrivateNetwork: read replica endpoint spec private network.
type ReadReplicaEndpointSpecPrivateNetwork struct {
// PrivateNetworkID: UUID of the Private Network to be connected to the Read Replica.
PrivateNetworkID string `json:"private_network_id"`
// ServiceIP: endpoint IPv4 address with a CIDR notation. Refer to the official Scaleway documentation to learn more about IP and subnet limitations.
// Precisely one of ServiceIP, IpamConfig must be set.
ServiceIP *scw.IPNet `json:"service_ip,omitempty"`
// IpamConfig: automated configuration of your Private Network endpoint with Scaleway IPAM service. One at the most per Database Instance or Read Replica (a Database Instance and its Read Replica can have different private networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of ServiceIP, IpamConfig must be set.
IpamConfig *ReadReplicaEndpointSpecPrivateNetworkIpamConfig `json:"ipam_config,omitempty"`
}
// EngineVersion: engine version.
type EngineVersion struct {
// Version: database engine version.
Version string `json:"version"`
// Name: database engine name.
Name string `json:"name"`
// EndOfLife: end of life date.
EndOfLife *time.Time `json:"end_of_life"`
// AvailableSettings: engine settings available to be set.
AvailableSettings []*EngineSetting `json:"available_settings"`
// Disabled: disabled versions cannot be created.
Disabled bool `json:"disabled"`
// Beta: beta status of engine version.
Beta bool `json:"beta"`
// AvailableInitSettings: engine settings available to be set at database initialization.
AvailableInitSettings []*EngineSetting `json:"available_init_settings"`
}
// BackupSchedule: backup schedule.
type BackupSchedule struct {
// Frequency: frequency of the backup schedule (in hours).
Frequency uint32 `json:"frequency"`
// Retention: default retention period of backups (in days).
Retention uint32 `json:"retention"`
// Disabled: defines whether the backup schedule feature is disabled.
Disabled bool `json:"disabled"`
// NextRunAt: next run of the backup schedule (accurate to 10 minutes).
NextRunAt *time.Time `json:"next_run_at"`
}
// EncryptionAtRest: encryption at rest.
type EncryptionAtRest struct {
Enabled bool `json:"enabled"`
}
// InstanceSetting: instance setting.
type InstanceSetting struct {
Name string `json:"name"`
Value string `json:"value"`
}
// LogsPolicy: logs policy.
type LogsPolicy struct {
// MaxAgeRetention: max age (in days) of remote logs to keep on the Database Instance.
MaxAgeRetention *uint32 `json:"max_age_retention"`
// TotalDiskRetention: max disk size of remote logs to keep on the Database Instance.
TotalDiskRetention *scw.Size `json:"total_disk_retention"`
}
// Maintenance: maintenance.
type Maintenance struct {
// StartsAt: start date of the maintenance window.
StartsAt *time.Time `json:"starts_at"`
// StopsAt: end date of the maintenance window.
StopsAt *time.Time `json:"stops_at"`
// ClosedAt: closed maintenance date.
ClosedAt *time.Time `json:"closed_at"`
// Reason: maintenance information message.
Reason string `json:"reason"`
// Status: status of the maintenance.
// Default value: unknown
Status MaintenanceStatus `json:"status"`
// ForcedAt: time when Scaleway-side maintenance will be applied.
ForcedAt *time.Time `json:"forced_at"`
}
// ReadReplica: read replica.
type ReadReplica struct {
// ID: UUID of the Read Replica.
ID string `json:"id"`
// Endpoints: display Read Replica connection information.
Endpoints []*Endpoint `json:"endpoints"`
// Status: read replica status.
// Default value: unknown
Status ReadReplicaStatus `json:"status"`
// Region: region the Read Replica is in.
Region scw.Region `json:"region"`
// SameZone: whether the replica is in the same availability zone as the main instance nodes or not.
SameZone bool `json:"same_zone"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
}
// UpgradableVersion: upgradable version.
type UpgradableVersion struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
MinorVersion string `json:"minor_version"`
}
// Volume: volume.
type Volume struct {
// Type: default value: lssd
Type VolumeType `json:"type"`
Size scw.Size `json:"size"`
// Class: default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// NodeTypeVolumeConstraintSizes: node type volume constraint sizes.
type NodeTypeVolumeConstraintSizes struct {
// MinSize: [deprecated] Mimimum size required for the Volume.
MinSize scw.Size `json:"min_size"`
// MaxSize: [deprecated] Maximum size required for the Volume.
MaxSize scw.Size `json:"max_size"`
}
// NodeTypeVolumeType: node type volume type.
type NodeTypeVolumeType struct {
// Type: volume Type.
// Default value: lssd
Type VolumeType `json:"type"`
// Description: the description of the Volume.
Description string `json:"description"`
// MinSize: mimimum size required for the Volume.
MinSize scw.Size `json:"min_size"`
// MaxSize: maximum size required for the Volume.
MaxSize scw.Size `json:"max_size"`
// ChunkSize: minimum increment level for a Block Storage volume size.
ChunkSize scw.Size `json:"chunk_size"`
// Class: the storage class of the volume.
// Default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// SnapshotVolumeType: snapshot volume type.
type SnapshotVolumeType struct {
// Type: default value: lssd
Type VolumeType `json:"type"`
// Class: default value: unknown_storage_class
Class StorageClass `json:"class"`
}
// ACLRuleRequest: acl rule request.
type ACLRuleRequest struct {
IP scw.IPNet `json:"ip"`
Description string `json:"description"`
}
// ACLRule: acl rule.
type ACLRule struct {
IP scw.IPNet `json:"ip"`
// Deprecated
Port *uint32 `json:"port,omitempty"`
// Protocol: default value: tcp
Protocol ACLRuleProtocol `json:"protocol"`
// Direction: default value: inbound
Direction ACLRuleDirection `json:"direction"`
// Action: default value: allow
Action ACLRuleAction `json:"action"`
Description string `json:"description"`
}
// EndpointSpec: endpoint spec.
type EndpointSpec struct {
// LoadBalancer: load balancer endpoint specifications. Public endpoint for Database Instance which is systematically present. One per RDB instance.
// Precisely one of LoadBalancer, PrivateNetwork must be set.
LoadBalancer *EndpointSpecLoadBalancer `json:"load_balancer,omitempty"`
// PrivateNetwork: private Network endpoint specifications. One maximum per Database Instance or Read Replica (a Database Instance and its Read Replica can have different Private Networks). Cannot be updated (has to be deleted and recreated).
// Precisely one of LoadBalancer, PrivateNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetwork `json:"private_network,omitempty"`
}
// ReadReplicaEndpointSpec: read replica endpoint spec.
type ReadReplicaEndpointSpec struct {
// DirectAccess: direct access endpoint specifications. Public endpoint reserved for Read Replicas. One per Read Replica.
// Precisely one of DirectAccess, PrivateNetwork must be set.
DirectAccess *ReadReplicaEndpointSpecDirectAccess `json:"direct_access,omitempty"`
// PrivateNetwork: private Network endpoint specifications. One at the most per Read Replica. Cannot be updated (has to be deleted and recreated).
// Precisely one of DirectAccess, PrivateNetwork must be set.
PrivateNetwork *ReadReplicaEndpointSpecPrivateNetwork `json:"private_network,omitempty"`
}
// DatabaseBackup: database backup.
type DatabaseBackup struct {
// ID: UUID of the database backup.
ID string `json:"id"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// DatabaseName: name of backed up database.
DatabaseName string `json:"database_name"`
// Name: name of the backup.
Name string `json:"name"`
// Status: status of the backup.
// Default value: unknown
Status DatabaseBackupStatus `json:"status"`
// Size: size of the database backup.
Size *scw.Size `json:"size"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: updated date (must follow the ISO 8601 format).
UpdatedAt *time.Time `json:"updated_at"`
// InstanceName: name of the Database Instance of the backup.
InstanceName string `json:"instance_name"`
// DownloadURL: URL you can download the backup from.
DownloadURL *string `json:"download_url"`
// DownloadURLExpiresAt: expiration date of the download link.
DownloadURLExpiresAt *time.Time `json:"download_url_expires_at"`
// Region: region of the database backup.
Region scw.Region `json:"region"`
// SameRegion: store logical backups in the same region as the source Database Instance.
SameRegion bool `json:"same_region"`
}
// DatabaseEngine: database engine.
type DatabaseEngine struct {
// Name: engine name.
Name string `json:"name"`
// LogoURL: engine logo URL.
LogoURL string `json:"logo_url"`
// Versions: available versions.
Versions []*EngineVersion `json:"versions"`
// Region: region of this Database Instance.
Region scw.Region `json:"region"`
}
// Database: database.
type Database struct {
// Name: name of the database.
Name string `json:"name"`
// Owner: name of the database owner.
Owner string `json:"owner"`
// Managed: defines whether the database is managed or not.
Managed bool `json:"managed"`
// Size: size of the database.
Size scw.Size `json:"size"`
}
// ListInstanceLogsDetailsResponseInstanceLogDetail: list instance logs details response instance log detail.
type ListInstanceLogsDetailsResponseInstanceLogDetail struct {
LogName string `json:"log_name"`
Size uint64 `json:"size"`
}
// InstanceLog: instance log.
type InstanceLog struct {
// DownloadURL: presigned Object Storage URL to download your log file.
DownloadURL *string `json:"download_url"`
// ID: UUID of the Database Instance log.
ID string `json:"id"`
// Status: status of the logs in a Database Instance.
// Default value: unknown
Status InstanceLogStatus `json:"status"`
// NodeName: name of the underlying node.
NodeName string `json:"node_name"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// Region: region the Database Instance is in.
Region scw.Region `json:"region"`
}
// Instance: instance.
type Instance struct {
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// Volume: volumes of the Database Instance.
Volume *Volume `json:"volume"`
// Region: region the Database Instance is in.
Region scw.Region `json:"region"`
// ID: UUID of the Database Instance.
ID string `json:"id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// OrganizationID: organization ID the Database Instance belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the Database Instance belongs to.
ProjectID string `json:"project_id"`
// Status: status of the Database Instance.
// Default value: unknown
Status InstanceStatus `json:"status"`
// Engine: database engine of the database (PostgreSQL, MySQL, ...).
Engine string `json:"engine"`
// UpgradableVersion: available database engine versions for upgrade.
UpgradableVersion []*UpgradableVersion `json:"upgradable_version"`
// Deprecated: Endpoint: endpoint of the Database Instance.
Endpoint *Endpoint `json:"endpoint,omitempty"`
// Tags: list of tags applied to the Database Instance.
Tags []string `json:"tags"`
// Settings: advanced settings of the Database Instance.
Settings []*InstanceSetting `json:"settings"`
// BackupSchedule: backup schedule of the Database Instance.
BackupSchedule *BackupSchedule `json:"backup_schedule"`
// IsHaCluster: defines whether or not High-Availability is enabled.
IsHaCluster bool `json:"is_ha_cluster"`
// ReadReplicas: read Replicas of the Database Instance.
ReadReplicas []*ReadReplica `json:"read_replicas"`
// NodeType: node type of the Database Instance.
NodeType string `json:"node_type"`
// InitSettings: list of engine settings to be set at database initialization.
InitSettings []*InstanceSetting `json:"init_settings"`
// Endpoints: list of Database Instance endpoints.
Endpoints []*Endpoint `json:"endpoints"`
// LogsPolicy: logs policy of the Database Instance.
LogsPolicy *LogsPolicy `json:"logs_policy"`
// BackupSameRegion: store logical backups in the same region as the Database Instance.
BackupSameRegion bool `json:"backup_same_region"`
// Maintenances: list of Database Instance maintenance events.
Maintenances []*Maintenance `json:"maintenances"`
// Encryption: encryption at rest settings for your Database Instance.
Encryption *EncryptionAtRest `json:"encryption"`
}
// NodeType: node type.
type NodeType struct {
// Name: node Type name identifier.
Name string `json:"name"`
// StockStatus: current stock status for the Node Type.
// Default value: unknown
StockStatus NodeTypeStock `json:"stock_status"`
// Description: current specs of the offer.
Description string `json:"description"`
// Vcpus: number of virtual CPUs.
Vcpus uint32 `json:"vcpus"`
// Memory: quantity of RAM.
Memory scw.Size `json:"memory"`
// Deprecated: VolumeConstraint: [deprecated] Node Type volume constraints.
VolumeConstraint *NodeTypeVolumeConstraintSizes `json:"volume_constraint,omitempty"`
// Deprecated: IsBssdCompatible: the Node Type is compliant with Block Storage.
IsBssdCompatible *bool `json:"is_bssd_compatible,omitempty"`
// Disabled: the Node Type is currently disabled.
Disabled bool `json:"disabled"`
// Beta: the Node Type is currently in beta.
Beta bool `json:"beta"`
// AvailableVolumeTypes: available storage options for the Node Type.
AvailableVolumeTypes []*NodeTypeVolumeType `json:"available_volume_types"`
// IsHaRequired: the Node Type can be used only with high availability option.
IsHaRequired bool `json:"is_ha_required"`
// Generation: generation associated with the NodeType offer.
// Default value: unknown_generation
Generation NodeTypeGeneration `json:"generation"`
// InstanceRange: instance range associated with the NodeType offer.
InstanceRange string `json:"instance_range"`
// Region: region the Node Type is in.
Region scw.Region `json:"region"`
}
// Privilege: privilege.
type Privilege struct {
// Permission: permission (Read, Read/Write, All, Custom).
// Default value: readonly
Permission Permission `json:"permission"`
// DatabaseName: name of the database.
DatabaseName string `json:"database_name"`
// UserName: name of the user.
UserName string `json:"user_name"`
}
// Snapshot: snapshot.
type Snapshot struct {
// ID: UUID of the snapshot.
ID string `json:"id"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// Name: name of the snapshot.
Name string `json:"name"`
// Status: status of the snapshot.
// Default value: unknown
Status SnapshotStatus `json:"status"`
// Size: size of the snapshot.
Size *scw.Size `json:"size"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at"`
// CreatedAt: creation date (must follow the ISO 8601 format).
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: updated date (must follow the ISO 8601 format).
UpdatedAt *time.Time `json:"updated_at"`
// InstanceName: name of the Database Instance of the snapshot.
InstanceName string `json:"instance_name"`
// NodeType: source node type.
NodeType string `json:"node_type"`
// VolumeType: type of volume where data is stored (lssd, bssd or sbs).
VolumeType *SnapshotVolumeType `json:"volume_type"`
// Region: region of this snapshot.
Region scw.Region `json:"region"`
}
// User: user.
type User struct {
// Name: name of the user (Length must be between 1 and 63 characters for PostgreSQL and between 1 and 32 characters for MySQL. First character must be an alphabet character (a-zA-Z). Your username cannot start with '_rdb' or in PostgreSQL, 'pg_'. Only a-zA-Z0-9_$- characters are accepted).
Name string `json:"name"`
// IsAdmin: defines whether or not a user got administrative privileges on the Database Instance.
IsAdmin bool `json:"is_admin"`
}
// UpgradeInstanceRequestMajorUpgradeWorkflow: upgrade instance request major upgrade workflow.
type UpgradeInstanceRequestMajorUpgradeWorkflow struct {
// UpgradableVersionID: this will create a new Database Instance with same specifications as the current one and perform a Database Engine upgrade.
UpgradableVersionID string `json:"upgradable_version_id"`
// WithEndpoints: at the end of the migration procedure this option let you migrate all your database endpoint to the upgraded instance.
WithEndpoints bool `json:"with_endpoints"`
}
// AddInstanceACLRulesRequest: add instance acl rules request.
type AddInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to add ACL rules to.
InstanceID string `json:"-"`
// Rules: ACL rules to add to the Database Instance.
Rules []*ACLRuleRequest `json:"rules"`
}
// AddInstanceACLRulesResponse: add instance acl rules response.
type AddInstanceACLRulesResponse struct {
// Rules: ACL Rules enabled for the Database Instance.
Rules []*ACLRule `json:"rules"`
}
// AddInstanceSettingsRequest: add instance settings request.
type AddInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to add settings to.
InstanceID string `json:"-"`
// Settings: settings to add to the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// AddInstanceSettingsResponse: add instance settings response.
type AddInstanceSettingsResponse struct {
// Settings: settings available on the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// ApplyInstanceMaintenanceRequest: apply instance maintenance request.
type ApplyInstanceMaintenanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to apply maintenance.
InstanceID string `json:"-"`
}
// CloneInstanceRequest: clone instance request.
type CloneInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to clone.
InstanceID string `json:"-"`
// Name: name of the Database Instance clone.
Name string `json:"name"`
// NodeType: node type of the clone.
NodeType *string `json:"node_type,omitempty"`
}
// CreateDatabaseBackupRequest: create database backup request.
type CreateDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"instance_id"`
// DatabaseName: name of the database you want to back up.
DatabaseName string `json:"database_name"`
// Name: name of the backup.
Name string `json:"name"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateDatabaseRequest: create database request.
type CreateDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where to create the database.
InstanceID string `json:"-"`
// Name: name of the database.
Name string `json:"name"`
}
// CreateEndpointRequest: create endpoint request.
type CreateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you to which you want to add an endpoint.
InstanceID string `json:"-"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec *EndpointSpec `json:"endpoint_spec,omitempty"`
}
// CreateInstanceFromSnapshotRequest: create instance from snapshot request.
type CreateInstanceFromSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: block snapshot of the Database Instance.
SnapshotID string `json:"-"`
// InstanceName: name of the Database Instance created with the snapshot.
InstanceName string `json:"instance_name"`
// IsHaCluster: defines whether or not High-Availability is enabled on the new Database Instance.
IsHaCluster *bool `json:"is_ha_cluster,omitempty"`
// NodeType: the node type used to restore the snapshot.
NodeType *string `json:"node_type,omitempty"`
}
// CreateInstanceRequest: create instance request.
type CreateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Deprecated: OrganizationID: please use project_id instead.
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: the Project ID on which the Database Instance will be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// Name: name of the Database Instance.
Name string `json:"name"`
// Engine: database engine of the Database Instance (PostgreSQL, MySQL, ...).
Engine string `json:"engine"`
// UserName: username created when the Database Instance is created.
UserName string `json:"user_name"`
// Password: password of the user. Password must be between 8 and 128 characters, contain at least one digit, one uppercase, one lowercase and one special character.
Password string `json:"password"`
// NodeType: type of node to use for the Database Instance.
NodeType string `json:"node_type"`
// IsHaCluster: defines whether or not High-Availability is enabled.
IsHaCluster bool `json:"is_ha_cluster"`
// DisableBackup: defines whether or not backups are disabled.
DisableBackup bool `json:"disable_backup"`
// Tags: tags to apply to the Database Instance.
Tags []string `json:"tags"`
// InitSettings: list of engine settings to be set upon Database Instance initialization.
InitSettings []*InstanceSetting `json:"init_settings"`
// VolumeType: type of volume where data is stored (lssd, bssd, ...).
// Default value: lssd
VolumeType VolumeType `json:"volume_type"`
// VolumeSize: volume size when volume_type is not lssd.
VolumeSize scw.Size `json:"volume_size"`
// InitEndpoints: one or multiple EndpointSpec used to expose your Database Instance. A load_balancer public endpoint is systematically created.
InitEndpoints []*EndpointSpec `json:"init_endpoints"`
// BackupSameRegion: defines whether to or not to store logical backups in the same region as the Database Instance.
BackupSameRegion bool `json:"backup_same_region"`
// Encryption: encryption at rest settings for your Database Instance.
Encryption *EncryptionAtRest `json:"encryption,omitempty"`
}
// CreateReadReplicaEndpointRequest: create read replica endpoint request.
type CreateReadReplicaEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec []*ReadReplicaEndpointSpec `json:"endpoint_spec"`
}
// CreateReadReplicaRequest: create read replica request.
type CreateReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to create a Read Replica from.
InstanceID string `json:"instance_id"`
// EndpointSpec: specification of the endpoint you want to create.
EndpointSpec []*ReadReplicaEndpointSpec `json:"endpoint_spec"`
// SameZone: defines whether to create the replica in the same availability zone as the main instance nodes or not.
SameZone *bool `json:"same_zone,omitempty"`
}
// CreateSnapshotRequest: create snapshot request.
type CreateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// Name: name of the snapshot.
Name string `json:"name"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateUserRequest: create user request.
type CreateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance in which you want to create a user.
InstanceID string `json:"-"`
// Name: name of the user you want to create.
Name string `json:"name"`
// Password: password of the user you want to create. Password must be between 8 and 128 characters, contain at least one digit, one uppercase, one lowercase and one special character.
Password string `json:"password"`
// IsAdmin: defines whether the user will have administrative privileges.
IsAdmin bool `json:"is_admin"`
}
// DeleteDatabaseBackupRequest: delete database backup request.
type DeleteDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseBackupID: UUID of the database backup to delete.
DatabaseBackupID string `json:"-"`
}
// DeleteDatabaseRequest: delete database request.
type DeleteDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where to delete the database.
InstanceID string `json:"-"`
// Name: name of the database to delete.
Name string `json:"-"`
}
// DeleteEndpointRequest: delete endpoint request.
type DeleteEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: this endpoint can also be used to delete a Read Replica endpoint.
EndpointID string `json:"-"`
}
// DeleteInstanceACLRulesRequest: delete instance acl rules request.
type DeleteInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to delete an ACL rule from.
InstanceID string `json:"-"`
// ACLRuleIPs: IP addresses defined in the ACL rules of the Database Instance.
ACLRuleIPs []string `json:"acl_rule_ips"`
}
// DeleteInstanceACLRulesResponse: delete instance acl rules response.
type DeleteInstanceACLRulesResponse struct {
// Rules: IP addresses defined in the ACL rules of the Database Instance.
Rules []*ACLRule `json:"rules"`
}
// DeleteInstanceRequest: delete instance request.
type DeleteInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete.
InstanceID string `json:"-"`
}
// DeleteInstanceSettingsRequest: delete instance settings request.
type DeleteInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete settings from.
InstanceID string `json:"-"`
// SettingNames: settings names to delete.
SettingNames []string `json:"setting_names"`
}
// DeleteInstanceSettingsResponse: delete instance settings response.
type DeleteInstanceSettingsResponse struct {
// Settings: settings names to delete from the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// DeleteReadReplicaRequest: delete read replica request.
type DeleteReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// DeleteSnapshotRequest: delete snapshot request.
type DeleteSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot to delete.
SnapshotID string `json:"-"`
}
// DeleteUserRequest: delete user request.
type DeleteUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to delete the user from.
InstanceID string `json:"-"`
// Name: name of the user.
Name string `json:"-"`
}
// ExportDatabaseBackupRequest: export database backup request.
type ExportDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseBackupID: UUID of the database backup you want to export.
DatabaseBackupID string `json:"-"`
}
// GetDatabaseBackupRequest: get database backup request.
type GetDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseBackupID: UUID of the database backup.
DatabaseBackupID string `json:"-"`
}
// GetEndpointRequest: get endpoint request.
type GetEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: UUID of the endpoint you want to get.
EndpointID string `json:"-"`
}
// GetInstanceCertificateRequest: get instance certificate request.
type GetInstanceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetInstanceLogRequest: get instance log request.
type GetInstanceLogRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceLogID: UUID of the instance_log you want.
InstanceLogID string `json:"-"`
}
// GetInstanceMetricsRequest: get instance metrics request.
type GetInstanceMetricsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// StartDate: start date to gather metrics from.
StartDate *time.Time `json:"-"`
// EndDate: end date to gather metrics from.
EndDate *time.Time `json:"-"`
// MetricName: name of the metric to gather.
MetricName *string `json:"-"`
}
// GetInstanceRequest: get instance request.
type GetInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
}
// GetReadReplicaRequest: get read replica request.
type GetReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// GetSnapshotRequest: get snapshot request.
type GetSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot.
SnapshotID string `json:"-"`
}
// InstanceMetrics: instance metrics.
type InstanceMetrics struct {
// Timeseries: time series of metrics of a Database Instance.
Timeseries []*scw.TimeSeries `json:"timeseries"`
}
// ListDatabaseBackupsRequest: list database backups request.
type ListDatabaseBackupsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the database backups.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering database backups listing.
// Default value: created_at_asc
OrderBy ListDatabaseBackupsRequestOrderBy `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID *string `json:"-"`
// OrganizationID: organization ID of the Organization the database backups belong to.
OrganizationID *string `json:"-"`
// ProjectID: project ID of the Project the database backups belong to.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListDatabaseBackupsResponse: list database backups response.
type ListDatabaseBackupsResponse struct {
// DatabaseBackups: list of database backups.
DatabaseBackups []*DatabaseBackup `json:"database_backups"`
// TotalCount: total count of database backups available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabaseBackupsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabaseBackupsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDatabaseBackupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.DatabaseBackups = append(r.DatabaseBackups, results.DatabaseBackups...)
r.TotalCount += uint32(len(results.DatabaseBackups))
return uint32(len(results.DatabaseBackups)), nil
}
// ListDatabaseEnginesRequest: list database engines request.
type ListDatabaseEnginesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the database engine.
Name *string `json:"-"`
// Version: version of the database engine.
Version *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListDatabaseEnginesResponse: list database engines response.
type ListDatabaseEnginesResponse struct {
// Engines: list of the available database engines.
Engines []*DatabaseEngine `json:"engines"`
// TotalCount: total count of database engines available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabaseEnginesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabaseEnginesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDatabaseEnginesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Engines = append(r.Engines, results.Engines...)
r.TotalCount += uint32(len(results.Engines))
return uint32(len(results.Engines)), nil
}
// ListDatabasesRequest: list databases request.
type ListDatabasesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to list the databases of.
InstanceID string `json:"-"`
// Name: name of the database.
Name *string `json:"-"`
// Managed: defines whether or not the database is managed.
Managed *bool `json:"-"`
// Owner: user that owns this database.
Owner *string `json:"-"`
// OrderBy: criteria to use when ordering database listing.
// Default value: name_asc
OrderBy ListDatabasesRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListDatabasesResponse: list databases response.
type ListDatabasesResponse struct {
// Databases: list of the databases.
Databases []*Database `json:"databases"`
// TotalCount: total count of databases present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDatabasesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Databases = append(r.Databases, results.Databases...)
r.TotalCount += uint32(len(results.Databases))
return uint32(len(results.Databases)), nil
}
// ListInstanceACLRulesRequest: list instance acl rules request.
type ListInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListInstanceACLRulesResponse: list instance acl rules response.
type ListInstanceACLRulesResponse struct {
// Rules: list of ACL rules present on a Database Instance.
Rules []*ACLRule `json:"rules"`
// TotalCount: total count of ACL rules present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInstanceACLRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInstanceACLRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListInstanceACLRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Rules = append(r.Rules, results.Rules...)
r.TotalCount += uint32(len(results.Rules))
return uint32(len(results.Rules)), nil
}
// ListInstanceLogsDetailsRequest: list instance logs details request.
type ListInstanceLogsDetailsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
}
// ListInstanceLogsDetailsResponse: list instance logs details response.
type ListInstanceLogsDetailsResponse struct {
// Details: remote Database Instance logs details.
Details []*ListInstanceLogsDetailsResponseInstanceLogDetail `json:"details"`
}
// ListInstanceLogsRequest: list instance logs request.
type ListInstanceLogsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
// OrderBy: criteria to use when ordering Database Instance logs listing.
// Default value: created_at_asc
OrderBy ListInstanceLogsRequestOrderBy `json:"order_by"`
}
// ListInstanceLogsResponse: list instance logs response.
type ListInstanceLogsResponse struct {
// InstanceLogs: available logs in a Database Instance.
InstanceLogs []*InstanceLog `json:"instance_logs"`
}
// ListInstancesRequest: list instances request.
type ListInstancesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Tags: list Database Instances that have a given tag.
Tags []string `json:"-"`
// Name: lists Database Instances that match a name pattern.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering Database Instance listings.
// Default value: created_at_asc
OrderBy ListInstancesRequestOrderBy `json:"-"`
// OrganizationID: please use project_id instead.
OrganizationID *string `json:"-"`
// ProjectID: project ID to list the Database Instance of.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListInstancesResponse: list instances response.
type ListInstancesResponse struct {
// Instances: list of all Database Instances available in an Organization or Project.
Instances []*Instance `json:"instances"`
// TotalCount: total count of Database Instances available in a Organization or Project.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListInstancesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListInstancesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Instances = append(r.Instances, results.Instances...)
r.TotalCount += uint32(len(results.Instances))
return uint32(len(results.Instances)), nil
}
// ListNodeTypesRequest: list node types request.
type ListNodeTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// IncludeDisabledTypes: defines whether or not to include disabled types.
IncludeDisabledTypes bool `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListNodeTypesResponse: list node types response.
type ListNodeTypesResponse struct {
// NodeTypes: types of the node.
NodeTypes []*NodeType `json:"node_types"`
// TotalCount: total count of node-types available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNodeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NodeTypes = append(r.NodeTypes, results.NodeTypes...)
r.TotalCount += uint32(len(results.NodeTypes))
return uint32(len(results.NodeTypes)), nil
}
// ListPrivilegesRequest: list privileges request.
type ListPrivilegesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// OrderBy: criteria to use when ordering privileges listing.
// Default value: user_name_asc
OrderBy ListPrivilegesRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// DatabaseName: name of the database.
DatabaseName *string `json:"-"`
// UserName: name of the user.
UserName *string `json:"-"`
}
// ListPrivilegesResponse: list privileges response.
type ListPrivilegesResponse struct {
// Privileges: privileges of a user in a database in a Database Instance.
Privileges []*Privilege `json:"privileges"`
// TotalCount: total count of privileges present on a database.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPrivilegesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPrivilegesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPrivilegesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Privileges = append(r.Privileges, results.Privileges...)
r.TotalCount += uint32(len(results.Privileges))
return uint32(len(results.Privileges)), nil
}
// ListSnapshotsRequest: list snapshots request.
type ListSnapshotsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the snapshot.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering snapshot listing.
// Default value: created_at_asc
OrderBy ListSnapshotsRequestOrderBy `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID *string `json:"-"`
// OrganizationID: organization ID the snapshots belongs to.
OrganizationID *string `json:"-"`
// ProjectID: project ID the snapshots belongs to.
ProjectID *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListSnapshotsResponse: list snapshots response.
type ListSnapshotsResponse struct {
// Snapshots: list of snapshots.
Snapshots []*Snapshot `json:"snapshots"`
// TotalCount: total count of snapshots available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSnapshotsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Snapshots = append(r.Snapshots, results.Snapshots...)
r.TotalCount += uint32(len(results.Snapshots))
return uint32(len(results.Snapshots)), nil
}
// ListUsersRequest: list users request.
type ListUsersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// Name: name of the user.
Name *string `json:"-"`
// OrderBy: criteria to use when requesting user listing.
// Default value: name_asc
OrderBy ListUsersRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListUsersResponse: list users response.
type ListUsersResponse struct {
// Users: list of users in a Database Instance.
Users []*User `json:"users"`
// TotalCount: total count of users present on a Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListUsersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Users = append(r.Users, results.Users...)
r.TotalCount += uint32(len(results.Users))
return uint32(len(results.Users)), nil
}
// MigrateEndpointRequest: migrate endpoint request.
type MigrateEndpointRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EndpointID: UUID of the endpoint you want to migrate.
EndpointID string `json:"-"`
// InstanceID: UUID of the instance you want to attach the endpoint to.
InstanceID string `json:"instance_id"`
}
// PrepareInstanceLogsRequest: prepare instance logs request.
type PrepareInstanceLogsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
// StartDate: start datetime of your log. (RFC 3339 format).
StartDate *time.Time `json:"start_date,omitempty"`
// EndDate: end datetime of your log. (RFC 3339 format).
EndDate *time.Time `json:"end_date,omitempty"`
}
// PrepareInstanceLogsResponse: prepare instance logs response.
type PrepareInstanceLogsResponse struct {
// InstanceLogs: instance logs for a Database Instance between a start and an end date.
InstanceLogs []*InstanceLog `json:"instance_logs"`
}
// PromoteReadReplicaRequest: promote read replica request.
type PromoteReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// PurgeInstanceLogsRequest: purge instance logs request.
type PurgeInstanceLogsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
// LogName: given log name to purge.
LogName *string `json:"log_name,omitempty"`
}
// RenewInstanceCertificateRequest: renew instance certificate request.
type RenewInstanceCertificateRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want logs of.
InstanceID string `json:"-"`
}
// ResetReadReplicaRequest: reset read replica request.
type ResetReadReplicaRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ReadReplicaID: UUID of the Read Replica.
ReadReplicaID string `json:"-"`
}
// RestartInstanceRequest: restart instance request.
type RestartInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to restart.
InstanceID string `json:"-"`
}
// RestoreDatabaseBackupRequest: restore database backup request.
type RestoreDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseBackupID: backup of a logical database.
DatabaseBackupID string `json:"-"`
// DatabaseName: defines the destination database to restore into a specified database (the default destination is set to the origin database of the backup).
DatabaseName *string `json:"database_name,omitempty"`
// InstanceID: defines the Database Instance where the backup has to be restored.
InstanceID string `json:"instance_id"`
}
// SetInstanceACLRulesRequest: set instance acl rules request.
type SetInstanceACLRulesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where the ACL rules must be set.
InstanceID string `json:"-"`
// Rules: ACL rules to define for the Database Instance.
Rules []*ACLRuleRequest `json:"rules"`
}
// SetInstanceACLRulesResponse: set instance acl rules response.
type SetInstanceACLRulesResponse struct {
// Rules: aCLs rules configured for a Database Instance.
Rules []*ACLRule `json:"rules"`
}
// SetInstanceSettingsRequest: set instance settings request.
type SetInstanceSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance where the settings must be set.
InstanceID string `json:"-"`
// Settings: settings to define for the Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// SetInstanceSettingsResponse: set instance settings response.
type SetInstanceSettingsResponse struct {
// Settings: settings configured for a Database Instance.
Settings []*InstanceSetting `json:"settings"`
}
// SetPrivilegeRequest: set privilege request.
type SetPrivilegeRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance.
InstanceID string `json:"-"`
// DatabaseName: name of the database.
DatabaseName string `json:"database_name"`
// UserName: name of the user.
UserName string `json:"user_name"`
// Permission: permission to set (Read, Read/Write, All, Custom).
// Default value: readonly
Permission Permission `json:"permission"`
}
// UpdateDatabaseBackupRequest: update database backup request.
type UpdateDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseBackupID: UUID of the database backup to update.
DatabaseBackupID string `json:"-"`
// Name: name of the Database Backup.
Name *string `json:"name,omitempty"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// UpdateInstanceRequest: update instance request.
type UpdateInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance to update.
InstanceID string `json:"-"`
// BackupScheduleFrequency: in hours.
BackupScheduleFrequency *uint32 `json:"backup_schedule_frequency,omitempty"`
// BackupScheduleRetention: in days.
BackupScheduleRetention *uint32 `json:"backup_schedule_retention,omitempty"`
// IsBackupScheduleDisabled: defines whether or not the backup schedule is disabled.
IsBackupScheduleDisabled *bool `json:"is_backup_schedule_disabled,omitempty"`
// Name: name of the Database Instance.
Name *string `json:"name,omitempty"`
// Tags: tags of a Database Instance.
Tags *[]string `json:"tags,omitempty"`
// LogsPolicy: logs policy of the Database Instance.
LogsPolicy *LogsPolicy `json:"logs_policy,omitempty"`
// BackupSameRegion: store logical backups in the same region as the Database Instance.
BackupSameRegion *bool `json:"backup_same_region,omitempty"`
// BackupScheduleStartHour: defines the start time of the autobackup.
BackupScheduleStartHour *uint32 `json:"backup_schedule_start_hour,omitempty"`
}
// UpdateSnapshotRequest: update snapshot request.
type UpdateSnapshotRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SnapshotID: UUID of the snapshot to update.
SnapshotID string `json:"-"`
// Name: name of the snapshot.
Name *string `json:"name,omitempty"`
// ExpiresAt: expiration date (must follow the ISO 8601 format).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// UpdateUserRequest: update user request.
type UpdateUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance the user belongs to.
InstanceID string `json:"-"`
// Name: name of the database user.
Name string `json:"-"`
// Password: password of the database user. Password must be between 8 and 128 characters, contain at least one digit, one uppercase, one lowercase and one special character.
Password *string `json:"password,omitempty"`
// IsAdmin: defines whether or not this user got administrative privileges.
IsAdmin *bool `json:"is_admin,omitempty"`
}
// UpgradeInstanceRequest: upgrade instance request.
type UpgradeInstanceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// InstanceID: UUID of the Database Instance you want to upgrade.
InstanceID string `json:"-"`
// NodeType: node type of the Database Instance you want to upgrade to.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
NodeType *string `json:"node_type,omitempty"`
// EnableHa: defines whether or not high availability should be enabled on the Database Instance.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
EnableHa *bool `json:"enable_ha,omitempty"`
// VolumeSize: increase your block storage volume size.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
VolumeSize *uint64 `json:"volume_size,omitempty"`
// VolumeType: change your Database Instance storage type.
// Default value: lssd
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
VolumeType *VolumeType `json:"volume_type,omitempty"`
// UpgradableVersionID: this will create a new Database Instance with same specifications as the current one and perform a Database Engine upgrade.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
UpgradableVersionID *string `json:"upgradable_version_id,omitempty"`
// MajorUpgradeWorkflow: upgrade your database engine to a new major version including instance endpoints.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
MajorUpgradeWorkflow *UpgradeInstanceRequestMajorUpgradeWorkflow `json:"major_upgrade_workflow,omitempty"`
// EnableEncryption: defines whether or not encryption should be enabled on the Database Instance.
// Precisely one of NodeType, EnableHa, VolumeSize, VolumeType, UpgradableVersionID, MajorUpgradeWorkflow, EnableEncryption must be set.
EnableEncryption *bool `json:"enable_encryption,omitempty"`
}
// This API allows you to manage your Managed Databases for PostgreSQL and MySQL.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListDatabaseEngines: List the PostgreSQL and MySQL database engines available at Scaleway.
func (s *API) ListDatabaseEngines(req *ListDatabaseEnginesRequest, opts ...scw.RequestOption) (*ListDatabaseEnginesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "version", req.Version)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/database-engines",
Query: query,
}
var resp ListDatabaseEnginesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNodeTypes: List all available node types. By default, the node types returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListNodeTypes(req *ListNodeTypesRequest, opts ...scw.RequestOption) (*ListNodeTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "include_disabled_types", req.IncludeDisabledTypes)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/node-types",
Query: query,
}
var resp ListNodeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDatabaseBackups: List all backups in a specified region, for a given Scaleway Organization or Scaleway Project. By default, the backups listed are ordered by creation date in ascending order. This can be modified via the `order_by` field.
func (s *API) ListDatabaseBackups(req *ListDatabaseBackupsRequest, opts ...scw.RequestOption) (*ListDatabaseBackupsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "instance_id", req.InstanceID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups",
Query: query,
}
var resp ListDatabaseBackupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDatabaseBackup: Create a new backup. You must set the `instance_id`, `database_name`, `name` and `expires_at` parameters.
func (s *API) CreateDatabaseBackup(req *CreateDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("bkp")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDatabaseBackup: Retrieve information about a given backup, specified by its database backup ID and region. Full details about the backup, like size, URL and expiration date, are returned in the response.
func (s *API) GetDatabaseBackup(req *GetDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseBackupID) == "" {
return nil, errors.New("field DatabaseBackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.DatabaseBackupID) + "",
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDatabaseBackup: Update the parameters of a backup, including name and expiration date.
func (s *API) UpdateDatabaseBackup(req *UpdateDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseBackupID) == "" {
return nil, errors.New("field DatabaseBackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.DatabaseBackupID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabaseBackup: Delete a backup, specified by its database backup ID and region. Deleting a backup is permanent, and cannot be undone.
func (s *API) DeleteDatabaseBackup(req *DeleteDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseBackupID) == "" {
return nil, errors.New("field DatabaseBackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.DatabaseBackupID) + "",
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestoreDatabaseBackup: Launch the process of restoring database backup. You must specify the `instance_id` of the Database Instance of destination, where the backup will be restored. Note that large database backups can take up to several hours to restore.
func (s *API) RestoreDatabaseBackup(req *RestoreDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseBackupID) == "" {
return nil, errors.New("field DatabaseBackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.DatabaseBackupID) + "/restore",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ExportDatabaseBackup: Export a backup, specified by the `database_backup_id` and the `region` parameters. The download URL is returned in the response.
func (s *API) ExportDatabaseBackup(req *ExportDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseBackupID) == "" {
return nil, errors.New("field DatabaseBackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.DatabaseBackupID) + "/export",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradeInstance: Upgrade your current Database Instance specifications like node type, high availability, volume, or the database engine version. Note that upon upgrade the `enable_ha` parameter can only be set to `true`.
func (s *API) UpgradeInstance(req *UpgradeInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstances: List all Database Instances in the specified region, for a given Scaleway Organization or Scaleway Project. By default, the Database Instances returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `tags` and `name`. For the `name` parameter, the value you include will be checked against the whole name string to see if it includes the string you put in the parameter.
func (s *API) ListInstances(req *ListInstancesRequest, opts ...scw.RequestOption) (*ListInstancesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances",
Query: query,
}
var resp ListInstancesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstance: Retrieve information about a given Database Instance, specified by the `region` and `instance_id` parameters. Its full details, including name, status, IP address and port, are returned in the response object.
func (s *API) GetInstance(req *GetInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateInstance: Create a new Database Instance. You must set the `engine`, `user_name`, `password` and `node_type` parameters. Optionally, you can specify the volume type and size.
func (s *API) CreateInstance(req *CreateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("ins")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateInstance: Update the parameters of a Database Instance, including name, tags and backup schedule details.
func (s *API) UpdateInstance(req *UpdateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstance: Delete a given Database Instance, specified by the `region` and `instance_id` parameters. Deleting a Database Instance is permanent, and cannot be undone. Note that upon deletion all your data will be lost.
func (s *API) DeleteInstance(req *DeleteInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "",
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CloneInstance: Clone a given Database Instance, specified by the `region` and `instance_id` parameters. The clone feature allows you to create a new Database Instance from an existing one. The clone includes all existing databases, users and permissions. You can create a clone on a Database Instance bigger than your current one.
func (s *API) CloneInstance(req *CloneInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/clone",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestartInstance: Restart a given Database Instance, specified by the `region` and `instance_id` parameters. The status of the Database Instance returned in the response.
func (s *API) RestartInstance(req *RestartInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/restart",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstanceCertificate: Retrieve information about the TLS certificate of a given Database Instance. Details like name and content are returned in the response.
func (s *API) GetInstanceCertificate(req *GetInstanceCertificateRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/certificate",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RenewInstanceCertificate: Renew a TLS for a Database Instance. Renewing a certificate means that you will not be able to connect to your Database Instance using the previous certificate. You will also need to download and update the new certificate for all database clients.
func (s *API) RenewInstanceCertificate(req *RenewInstanceCertificateRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/renew-certificate",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetInstanceMetrics: Retrieve the time series metrics of a given Database Instance. You can define the period from which to retrieve metrics by specifying the `start_date` and `end_date`.
func (s *API) GetInstanceMetrics(req *GetInstanceMetricsRequest, opts ...scw.RequestOption) (*InstanceMetrics, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "start_date", req.StartDate)
parameter.AddToQuery(query, "end_date", req.EndDate)
parameter.AddToQuery(query, "metric_name", req.MetricName)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/metrics",
Query: query,
}
var resp InstanceMetrics
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateReadReplica: Create a new Read Replica of a Database Instance. You must specify the `region` and the `instance_id`. You can only create a maximum of 3 Read Replicas per Database Instance.
func (s *API) CreateReadReplica(req *CreateReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetReadReplica: Retrieve information about a Database Instance Read Replica. Full details about the Read Replica, like `endpoints`, `status` and `region` are returned in the response.
func (s *API) GetReadReplica(req *GetReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "",
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteReadReplica: Delete a Read Replica of a Database Instance. You must specify the `region` and `read_replica_id` parameters of the Read Replica you want to delete.
func (s *API) DeleteReadReplica(req *DeleteReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "",
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ResetReadReplica: When you resync a Read Replica, first it is reset, then its data is resynchronized from the primary node. Your Read Replica remains unavailable during the resync process. The duration of this process is proportional to the size of your Database Instance.
// The configured endpoints do not change.
func (s *API) ResetReadReplica(req *ResetReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/reset",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PromoteReadReplica: Promote a Read Replica to Database Instance automatically.
func (s *API) PromoteReadReplica(req *PromoteReadReplicaRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/promote",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateReadReplicaEndpoint: Create a new endpoint for a Read Replica. Read Replicas can have at most one direct access and one Private Network endpoint.
func (s *API) CreateReadReplicaEndpoint(req *CreateReadReplicaEndpointRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ReadReplicaID) == "" {
return nil, errors.New("field ReadReplicaID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/read-replicas/" + fmt.Sprint(req.ReadReplicaID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ReadReplica
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PrepareInstanceLogs: Prepare your Database Instance logs. You can define the `start_date` and `end_date` parameters for your query. The download URL is returned in the response. Logs are recorded from 00h00 to 23h59 and then aggregated in a `.log` file once a day. Therefore, even if you specify a timeframe from which you want to get the logs, you will receive logs from the full 24 hours.
func (s *API) PrepareInstanceLogs(req *PrepareInstanceLogsRequest, opts ...scw.RequestOption) (*PrepareInstanceLogsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/prepare-logs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrepareInstanceLogsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstanceLogs: List the available logs of a Database Instance. By default, the logs returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListInstanceLogs(req *ListInstanceLogsRequest, opts ...scw.RequestOption) (*ListInstanceLogsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/logs",
Query: query,
}
var resp ListInstanceLogsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetInstanceLog: Retrieve information about the logs of a Database Instance. Specify the `instance_log_id` and `region` in your request to get information such as `download_url`, `status`, `expires_at` and `created_at` about your logs in the response.
func (s *API) GetInstanceLog(req *GetInstanceLogRequest, opts ...scw.RequestOption) (*InstanceLog, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceLogID) == "" {
return nil, errors.New("field InstanceLogID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/logs/" + fmt.Sprint(req.InstanceLogID) + "",
}
var resp InstanceLog
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// PurgeInstanceLogs: Purge a given remote log from a Database Instance. You can specify the `log_name` of the log you wish to clean from your Database Instance.
func (s *API) PurgeInstanceLogs(req *PurgeInstanceLogsRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/purge-logs",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListInstanceLogsDetails: List remote log details. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListInstanceLogsDetails(req *ListInstanceLogsDetailsRequest, opts ...scw.RequestOption) (*ListInstanceLogsDetailsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/logs-details",
}
var resp ListInstanceLogsDetailsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddInstanceSettings: Add an advanced setting to a Database Instance. You must set the `name` and the `value` of each setting.
func (s *API) AddInstanceSettings(req *AddInstanceSettingsRequest, opts ...scw.RequestOption) (*AddInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstanceSettings: Delete an advanced setting in a Database Instance. You must specify the names of the settings you want to delete in the request.
func (s *API) DeleteInstanceSettings(req *DeleteInstanceSettingsRequest, opts ...scw.RequestOption) (*DeleteInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DeleteInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetInstanceSettings: Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.
func (s *API) SetInstanceSettings(req *SetInstanceSettingsRequest, opts ...scw.RequestOption) (*SetInstanceSettingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetInstanceSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListInstanceACLRules: List the ACL rules for a given Database Instance. The response is an array of ACL objects, each one representing an ACL that denies, allows or redirects traffic based on certain conditions.
func (s *API) ListInstanceACLRules(req *ListInstanceACLRulesRequest, opts ...scw.RequestOption) (*ListInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
Query: query,
}
var resp ListInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddInstanceACLRules: Add an additional ACL rule to a Database Instance.
func (s *API) AddInstanceACLRules(req *AddInstanceACLRulesRequest, opts ...scw.RequestOption) (*AddInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetInstanceACLRules: Replace all the ACL rules of a Database Instance.
func (s *API) SetInstanceACLRules(req *SetInstanceACLRulesRequest, opts ...scw.RequestOption) (*SetInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteInstanceACLRules: Delete one or more ACL rules of a Database Instance.
func (s *API) DeleteInstanceACLRules(req *DeleteInstanceACLRulesRequest, opts ...scw.RequestOption) (*DeleteInstanceACLRulesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DeleteInstanceACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListUsers: List all users of a given Database Instance. By default, the users returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListUsers(req *ListUsersRequest, opts ...scw.RequestOption) (*ListUsersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
Query: query,
}
var resp ListUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateUser: Create a new user for a Database Instance. You must define the `name`, `password` and `is_admin` parameters.
func (s *API) CreateUser(req *CreateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateUser: Update the parameters of a user on a Database Instance. You can update the `password` and `is_admin` parameters, but you cannot change the name of the user.
func (s *API) UpdateUser(req *UpdateUserRequest, opts ...scw.RequestOption) (*User, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return nil, errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp User
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteUser: Delete a given user on a Database Instance. You must specify, in the endpoint, the `region`, `instance_id` and `name` parameters of the user you want to delete.
func (s *API) DeleteUser(req *DeleteUserRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/users/" + fmt.Sprint(req.Name) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDatabases: List all databases of a given Database Instance. By default, the databases returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `name`, `managed` and `owner`.
func (s *API) ListDatabases(req *ListDatabasesRequest, opts ...scw.RequestOption) (*ListDatabasesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "managed", req.Managed)
parameter.AddToQuery(query, "owner", req.Owner)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases",
Query: query,
}
var resp ListDatabasesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDatabase: Create a new database. You must define the `name` parameter in the request.
func (s *API) CreateDatabase(req *CreateDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabase: Delete a given database on a Database Instance. You must specify, in the endpoint, the `region`, `instance_id` and `name` parameters of the database you want to delete.
func (s *API) DeleteDatabase(req *DeleteDatabaseRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return errors.New("field InstanceID cannot be empty in request")
}
if fmt.Sprint(req.Name) == "" {
return errors.New("field Name cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/databases/" + fmt.Sprint(req.Name) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPrivileges: List privileges of a user on a database. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `database_name` and `user_name`.
func (s *API) ListPrivileges(req *ListPrivilegesRequest, opts ...scw.RequestOption) (*ListPrivilegesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "database_name", req.DatabaseName)
parameter.AddToQuery(query, "user_name", req.UserName)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/privileges",
Query: query,
}
var resp ListPrivilegesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPrivilege: Set the privileges of a user on a database. You must define `database_name`, `user_name` and `permission` in the request body.
func (s *API) SetPrivilege(req *SetPrivilegeRequest, opts ...scw.RequestOption) (*Privilege, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/privileges",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Privilege
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSnapshots: List snapshots. You can include the `instance_id` or `project_id` in your query to get the list of snapshots for specific Database Instances and/or Projects. By default, the details returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "instance_id", req.InstanceID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/snapshots",
Query: query,
}
var resp ListSnapshotsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSnapshot: Retrieve information about a given snapshot, specified by its `snapshot_id` and `region`. Full details about the snapshot, like size and expiration date, are returned in the response.
func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSnapshot: Create a new snapshot of a Database Instance. You must define the `name` parameter in the request.
func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("snp")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/snapshots",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSnapshot: Update the parameters of a snapshot of a Database Instance. You can update the `name` and `expires_at` parameters.
func (s *API) UpdateSnapshot(req *UpdateSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSnapshot: Delete a given snapshot of a Database Instance. You must specify, in the endpoint, the `region` and `snapshot_id` parameters of the snapshot you want to delete.
func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "",
}
var resp Snapshot
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateInstanceFromSnapshot: Restore a snapshot. When you restore a snapshot, a new Instance is created and billed to your account. Note that is possible to select a larger node type for your new Database Instance. However, the Block volume size will be the same as the size of the restored snapshot. All Instance settings will be restored if you chose a node type with the same or more memory size than the initial Instance. Settings will be reset to the default if your node type has less memory.
func (s *API) CreateInstanceFromSnapshot(req *CreateInstanceFromSnapshotRequest, opts ...scw.RequestOption) (*Instance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SnapshotID) == "" {
return nil, errors.New("field SnapshotID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "/create-instance",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Instance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateEndpoint: Create a new endpoint for a Database Instance. You can add `load_balancer` and `private_network` specifications to the body of the request.
func (s *API) CreateEndpoint(req *CreateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteEndpoint: Delete the endpoint of a Database Instance. You must specify the `region` and `endpoint_id` parameters of the endpoint you want to delete. Note that might need to update any environment configurations that point to the deleted endpoint.
func (s *API) DeleteEndpoint(req *DeleteEndpointRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetEndpoint: Retrieve information about a Database Instance endpoint. Full details about the endpoint, like `ip`, `port`, `private_network` and `load_balancer` specifications are returned in the response.
func (s *API) GetEndpoint(req *GetEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// MigrateEndpoint: Migrate an existing instance endpoint to another instance.
func (s *API) MigrateEndpoint(req *MigrateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "/migrate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ApplyInstanceMaintenance: Apply maintenance tasks to your Database Instance. This will trigger pending maintenance tasks to start in your Database Instance and can generate service interruption. Maintenance tasks can be applied between `starts_at` and `stops_at` times, and are run directly by Scaleway at `forced_at` timestamp.
func (s *API) ApplyInstanceMaintenance(req *ApplyInstanceMaintenanceRequest, opts ...scw.RequestOption) (*Maintenance, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.InstanceID) == "" {
return nil, errors.New("field InstanceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/rdb/v1/regions/" + fmt.Sprint(req.Region) + "/instances/" + fmt.Sprint(req.InstanceID) + "/apply-maintenance",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Maintenance
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/v1/rdb_utils.go 0000664 0000000 0000000 00000016647 14747113137 0026446 0 ustar 00root root 0000000 0000000 package rdb
import (
"fmt"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 15 * time.Minute
)
// WaitForInstanceRequest is used by WaitForInstance method.
type WaitForInstanceRequest struct {
InstanceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForInstance waits for the instance to be in a "terminal state" before returning.
// This function can be used to wait for an instance to be ready for example.
func (s *API) WaitForInstance(req *WaitForInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[InstanceStatus]struct{}{
InstanceStatusReady: {},
InstanceStatusDiskFull: {},
InstanceStatusError: {},
}
instance, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetInstance(&GetInstanceRequest{
InstanceID: req.InstanceID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for instance failed")
}
return instance.(*Instance), nil
}
type WaitForDatabaseBackupRequest struct {
DatabaseBackupID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDatabaseBackup waits for the backup to be in a "terminal state" before returning.
// This function can be used to wait for a backup to be ready for example.
func (s *API) WaitForDatabaseBackup(req *WaitForDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DatabaseBackupStatus]struct{}{
DatabaseBackupStatusReady: {},
DatabaseBackupStatusError: {},
}
backup, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetDatabaseBackup(&GetDatabaseBackupRequest{
DatabaseBackupID: req.DatabaseBackupID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for database backup failed")
}
return backup.(*DatabaseBackup), nil
}
type WaitForInstanceLogRequest struct {
InstanceLogID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForInstanceLog waits for the instance logs to be in a "terminal state" before returning.
// This function can be used to wait for an instance logs to be ready for example.
func (s *API) WaitForInstanceLog(req *WaitForInstanceLogRequest, opts ...scw.RequestOption) (*InstanceLog, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[InstanceLogStatus]struct{}{
InstanceLogStatusReady: {},
InstanceLogStatusError: {},
}
logs, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetInstanceLog(&GetInstanceLogRequest{
Region: req.Region,
InstanceLogID: req.InstanceLogID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for instance logs failed")
}
return logs.(*InstanceLog), nil
}
// WaitForReadReplicaRequest is used by WaitForReadReplica method.
type WaitForReadReplicaRequest struct {
ReadReplicaID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForReadReplica waits for the read replica to be in a "terminal state" before returning.
// This function can be used to wait for a read replica to be ready for example.
func (s *API) WaitForReadReplica(req *WaitForReadReplicaRequest, opts ...scw.RequestOption) (*ReadReplica, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ReadReplicaStatus]struct{}{
ReadReplicaStatusReady: {},
ReadReplicaStatusError: {},
}
readReplica, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetReadReplica(&GetReadReplicaRequest{
ReadReplicaID: req.ReadReplicaID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for read replica failed")
}
return readReplica.(*ReadReplica), nil
}
func (s *API) FetchLatestEngineVersion(engineName string) (*EngineVersion, error) {
engines, err := s.ListDatabaseEngines(&ListDatabaseEnginesRequest{})
if err != nil {
return nil, err
}
var latestEngineVersion *EngineVersion
for _, engine := range engines.Engines {
if engine.Name == engineName {
if len(engine.Versions) > 0 {
latestEngineVersion = engine.Versions[0]
break
}
}
}
if latestEngineVersion == nil {
return nil, fmt.Errorf("no versions found for engine: %s", engineName)
}
return latestEngineVersion, nil
}
// WaitForSnapshotRequest is used by WaitForSnapshot method.
type WaitForSnapshotRequest struct {
SnapshotID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForSnapshot(req *WaitForSnapshotRequest, opts ...scw.RequestOption) (*Snapshot, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[SnapshotStatus]struct{}{
SnapshotStatusReady: {},
SnapshotStatusError: {},
SnapshotStatusLocked: {},
}
snapshot, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetSnapshot(&GetSnapshotRequest{
SnapshotID: req.SnapshotID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for snapshot failed")
}
return snapshot.(*Snapshot), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0025747 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/rdb/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000002040 14747113137 0030127 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/rdb/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepInstance(scwClient *scw.Client, region scw.Region) error {
rdbAPI := rdb.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the rdb instance in (%s)", region)
listInstances, err := rdbAPI.ListInstances(&rdb.ListInstancesRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing rdb instances in (%s) in sweeper: %s", region, err)
}
for _, instance := range listInstances.Instances {
_, err := rdbAPI.DeleteInstance(&rdb.DeleteInstanceRequest{
Region: region,
InstanceID: instance.ID,
})
if err != nil {
return fmt.Errorf("error deleting rdb instance in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&rdb.API{}).Regions() {
err := SweepInstance(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/ 0000775 0000000 0000000 00000000000 14747113137 0024123 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024451 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/v1/redis_sdk.go 0000664 0000000 0000000 00000150465 14747113137 0026762 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package redis provides methods and message types of the redis v1 API.
package redis
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type AvailableClusterSettingPropertyType string
const (
AvailableClusterSettingPropertyTypeUNKNOWN = AvailableClusterSettingPropertyType("UNKNOWN")
AvailableClusterSettingPropertyTypeBOOLEAN = AvailableClusterSettingPropertyType("BOOLEAN")
AvailableClusterSettingPropertyTypeINT = AvailableClusterSettingPropertyType("INT")
AvailableClusterSettingPropertyTypeSTRING = AvailableClusterSettingPropertyType("STRING")
)
func (enum AvailableClusterSettingPropertyType) String() string {
if enum == "" {
// return default value if empty
return "UNKNOWN"
}
return string(enum)
}
func (enum AvailableClusterSettingPropertyType) Values() []AvailableClusterSettingPropertyType {
return []AvailableClusterSettingPropertyType{
"UNKNOWN",
"BOOLEAN",
"INT",
"STRING",
}
}
func (enum AvailableClusterSettingPropertyType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *AvailableClusterSettingPropertyType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = AvailableClusterSettingPropertyType(AvailableClusterSettingPropertyType(tmp).String())
return nil
}
type ClusterStatus string
const (
ClusterStatusUnknown = ClusterStatus("unknown")
ClusterStatusReady = ClusterStatus("ready")
ClusterStatusProvisioning = ClusterStatus("provisioning")
ClusterStatusConfiguring = ClusterStatus("configuring")
ClusterStatusDeleting = ClusterStatus("deleting")
ClusterStatusError = ClusterStatus("error")
ClusterStatusAutohealing = ClusterStatus("autohealing")
ClusterStatusLocked = ClusterStatus("locked")
ClusterStatusSuspended = ClusterStatus("suspended")
ClusterStatusInitializing = ClusterStatus("initializing")
)
func (enum ClusterStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ClusterStatus) Values() []ClusterStatus {
return []ClusterStatus{
"unknown",
"ready",
"provisioning",
"configuring",
"deleting",
"error",
"autohealing",
"locked",
"suspended",
"initializing",
}
}
func (enum ClusterStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ClusterStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ClusterStatus(ClusterStatus(tmp).String())
return nil
}
type ListClustersRequestOrderBy string
const (
ListClustersRequestOrderByCreatedAtAsc = ListClustersRequestOrderBy("created_at_asc")
ListClustersRequestOrderByCreatedAtDesc = ListClustersRequestOrderBy("created_at_desc")
ListClustersRequestOrderByNameAsc = ListClustersRequestOrderBy("name_asc")
ListClustersRequestOrderByNameDesc = ListClustersRequestOrderBy("name_desc")
)
func (enum ListClustersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListClustersRequestOrderBy) Values() []ListClustersRequestOrderBy {
return []ListClustersRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListClustersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListClustersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListClustersRequestOrderBy(ListClustersRequestOrderBy(tmp).String())
return nil
}
type NodeTypeStock string
const (
NodeTypeStockUnknown = NodeTypeStock("unknown")
NodeTypeStockLowStock = NodeTypeStock("low_stock")
NodeTypeStockOutOfStock = NodeTypeStock("out_of_stock")
NodeTypeStockAvailable = NodeTypeStock("available")
)
func (enum NodeTypeStock) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NodeTypeStock) Values() []NodeTypeStock {
return []NodeTypeStock{
"unknown",
"low_stock",
"out_of_stock",
"available",
}
}
func (enum NodeTypeStock) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NodeTypeStock) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NodeTypeStock(NodeTypeStock(tmp).String())
return nil
}
type PrivateNetworkProvisioningMode string
const (
PrivateNetworkProvisioningModeStatic = PrivateNetworkProvisioningMode("static")
PrivateNetworkProvisioningModeIpam = PrivateNetworkProvisioningMode("ipam")
)
func (enum PrivateNetworkProvisioningMode) String() string {
if enum == "" {
// return default value if empty
return "static"
}
return string(enum)
}
func (enum PrivateNetworkProvisioningMode) Values() []PrivateNetworkProvisioningMode {
return []PrivateNetworkProvisioningMode{
"static",
"ipam",
}
}
func (enum PrivateNetworkProvisioningMode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PrivateNetworkProvisioningMode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PrivateNetworkProvisioningMode(PrivateNetworkProvisioningMode(tmp).String())
return nil
}
// EndpointSpecPrivateNetworkSpecIpamConfig: endpoint spec private network spec ipam config.
type EndpointSpecPrivateNetworkSpecIpamConfig struct {
}
// PrivateNetwork: private network.
type PrivateNetwork struct {
// ID: UUID of the Private Network.
ID string `json:"id"`
// ServiceIPs: list of IPv4 CIDR notation addresses of the endpoint.
ServiceIPs []scw.IPNet `json:"service_ips"`
// Zone: zone of the Private Network.
Zone scw.Zone `json:"zone"`
// ProvisioningMode: how your endpoint ips are provisioned.
// Default value: static
ProvisioningMode PrivateNetworkProvisioningMode `json:"provisioning_mode"`
}
// PublicNetwork: public network.
type PublicNetwork struct {
}
// EndpointSpecPrivateNetworkSpec: endpoint spec private network spec.
type EndpointSpecPrivateNetworkSpec struct {
// ID: UUID of the Private Network to connect to the Database Instance.
ID string `json:"id"`
// ServiceIPs: endpoint IPv4 address with a CIDR notation. You must provide at least one IPv4 per node.
ServiceIPs []scw.IPNet `json:"service_ips"`
// IpamConfig: automated configuration of your Private Network endpoint with Scaleway IPAM service.
IpamConfig *EndpointSpecPrivateNetworkSpecIpamConfig `json:"ipam_config"`
}
// EndpointSpecPublicNetworkSpec: endpoint spec public network spec.
type EndpointSpecPublicNetworkSpec struct {
}
// AvailableClusterSetting: available cluster setting.
type AvailableClusterSetting struct {
// Name: name of the setting.
Name string `json:"name"`
// DefaultValue: default value of the setting.
DefaultValue *string `json:"default_value"`
// Type: type of setting.
// Default value: UNKNOWN
Type AvailableClusterSettingPropertyType `json:"type"`
// Description: description of the setting.
Description string `json:"description"`
// MaxValue: optional maximum value of the setting.
MaxValue *int64 `json:"max_value"`
// MinValue: optional minimum value of the setting.
MinValue *int64 `json:"min_value"`
// Regex: optional validation rule of the setting.
Regex *string `json:"regex"`
// Deprecated: defines whether or not the setting is deprecated.
Deprecated bool `json:"deprecated"`
}
// ACLRule: acl rule.
type ACLRule struct {
// ID: ID of the rule.
ID string `json:"id"`
// IPCidr: iPv4 network address of the rule.
IPCidr *scw.IPNet `json:"ip_cidr"`
// Description: description of the rule.
Description *string `json:"description"`
}
// ClusterSetting: cluster setting.
type ClusterSetting struct {
// Value: value of the setting.
Value string `json:"value"`
// Name: name of the setting.
Name string `json:"name"`
}
// Endpoint: endpoint.
type Endpoint struct {
// Port: TCP port of the endpoint.
Port uint32 `json:"port"`
// PrivateNetwork: private Network details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PrivateNetwork *PrivateNetwork `json:"private_network,omitempty"`
// PublicNetwork: public network details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PublicNetwork *PublicNetwork `json:"public_network,omitempty"`
// IPs: list of IPv4 addresses of the endpoint.
IPs []net.IP `json:"ips"`
// ID: UUID of the endpoint.
ID string `json:"id"`
}
// ACLRuleSpec: acl rule spec.
type ACLRuleSpec struct {
// IPCidr: iPv4 network address of the rule.
IPCidr scw.IPNet `json:"ip_cidr"`
// Description: description of the rule.
Description string `json:"description"`
}
// EndpointSpec: endpoint spec.
type EndpointSpec struct {
// PrivateNetwork: private Network specification details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetworkSpec `json:"private_network,omitempty"`
// PublicNetwork: public network specification details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PublicNetwork *EndpointSpecPublicNetworkSpec `json:"public_network,omitempty"`
}
// ClusterVersion: cluster version.
type ClusterVersion struct {
// Version: redisâĸ engine version.
Version string `json:"version"`
// EndOfLifeAt: date of End of Life.
EndOfLifeAt *time.Time `json:"end_of_life_at"`
// AvailableSettings: cluster settings available to be updated.
AvailableSettings []*AvailableClusterSetting `json:"available_settings"`
// LogoURL: redisâĸ logo url.
LogoURL string `json:"logo_url"`
// Zone: zone of the Redisâĸ Database Instance.
Zone scw.Zone `json:"zone"`
}
// Cluster: cluster.
type Cluster struct {
// ID: UUID of the Database Instance.
ID string `json:"id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// ProjectID: project ID the Database Instance belongs to.
ProjectID string `json:"project_id"`
// Status: status of the Database Instance.
// Default value: unknown
Status ClusterStatus `json:"status"`
// Version: redisâĸ engine version of the Database Instance.
Version string `json:"version"`
// Endpoints: list of Database Instance endpoints.
Endpoints []*Endpoint `json:"endpoints"`
// Tags: list of tags applied to the Database Instance.
Tags []string `json:"tags"`
// NodeType: node type of the Database Instance.
NodeType string `json:"node_type"`
// CreatedAt: creation date (Format ISO 8601).
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: update date (Format ISO 8601).
UpdatedAt *time.Time `json:"updated_at"`
// TLSEnabled: defines whether or not TLS is enabled.
TLSEnabled bool `json:"tls_enabled"`
// ClusterSettings: list of Database Instance settings.
ClusterSettings []*ClusterSetting `json:"cluster_settings"`
// ACLRules: list of ACL rules.
ACLRules []*ACLRule `json:"acl_rules"`
// ClusterSize: number of nodes of the Database Instance cluster.
ClusterSize uint32 `json:"cluster_size"`
// Zone: zone of the Database Instance.
Zone scw.Zone `json:"zone"`
// UserName: name of the user associated to the cluster.
UserName string `json:"user_name"`
// UpgradableVersions: list of engine versions the Database Instance can upgrade to.
UpgradableVersions []string `json:"upgradable_versions"`
}
// NodeType: node type.
type NodeType struct {
// Name: node type name.
Name string `json:"name"`
// StockStatus: current stock status of the node type.
// Default value: unknown
StockStatus NodeTypeStock `json:"stock_status"`
// Description: current specifications of the offer.
Description string `json:"description"`
// Vcpus: number of virtual CPUs.
Vcpus uint32 `json:"vcpus"`
// Memory: quantity of RAM.
Memory scw.Size `json:"memory"`
// Disabled: defines whether node type is currently disabled or not.
Disabled bool `json:"disabled"`
// Beta: defines whether node type is currently in beta.
Beta bool `json:"beta"`
// Zone: zone of the node type.
Zone scw.Zone `json:"zone"`
}
// AddACLRulesRequest: add acl rules request.
type AddACLRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance you want to add ACL rules to.
ClusterID string `json:"-"`
// ACLRules: aCLs rules to add to the cluster.
ACLRules []*ACLRuleSpec `json:"acl_rules"`
}
// AddACLRulesResponse: add acl rules response.
type AddACLRulesResponse struct {
// ACLRules: ACL Rules enabled for the Database Instance.
ACLRules []*ACLRule `json:"acl_rules"`
// TotalCount: total count of ACL rules of the Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *AddACLRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *AddACLRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*AddACLRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ACLRules = append(r.ACLRules, results.ACLRules...)
r.TotalCount += uint32(len(results.ACLRules))
return uint32(len(results.ACLRules)), nil
}
// AddClusterSettingsRequest: add cluster settings request.
type AddClusterSettingsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance you want to add settings to.
ClusterID string `json:"-"`
// Settings: settings to add to the cluster.
Settings []*ClusterSetting `json:"settings"`
}
// AddEndpointsRequest: add endpoints request.
type AddEndpointsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance you want to add endpoints to.
ClusterID string `json:"-"`
// Endpoints: endpoints to add to the Database Instance.
Endpoints []*EndpointSpec `json:"endpoints"`
}
// AddEndpointsResponse: add endpoints response.
type AddEndpointsResponse struct {
// Endpoints: endpoints defined on the Database Instance.
Endpoints []*Endpoint `json:"endpoints"`
// TotalCount: total count of endpoints of the Database Instance.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *AddEndpointsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *AddEndpointsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*AddEndpointsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Endpoints = append(r.Endpoints, results.Endpoints...)
r.TotalCount += uint32(len(results.Endpoints))
return uint32(len(results.Endpoints)), nil
}
// ClusterMetricsResponse: cluster metrics response.
type ClusterMetricsResponse struct {
// Timeseries: time series of metrics of a given cluster.
Timeseries []*scw.TimeSeries `json:"timeseries"`
}
// ClusterSettingsResponse: cluster settings response.
type ClusterSettingsResponse struct {
// Settings: settings configured for a given Database Instance.
Settings []*ClusterSetting `json:"settings"`
}
// CreateClusterRequest: create cluster request.
type CreateClusterRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: project ID in which to create the Database Instance.
ProjectID string `json:"project_id"`
// Name: name of the Database Instance.
Name string `json:"name"`
// Version: redisâĸ engine version of the Database Instance.
Version string `json:"version"`
// Tags: tags to apply to the Database Instance.
Tags []string `json:"tags"`
// NodeType: type of node to use for the Database Instance.
NodeType string `json:"node_type"`
// UserName: name of the user created upon Database Instance creation.
UserName string `json:"user_name"`
// Password: password of the user.
Password string `json:"password"`
// ClusterSize: number of nodes in the Redisâĸ cluster.
ClusterSize *int32 `json:"cluster_size,omitempty"`
// ACLRules: list of ACLRuleSpec used to secure your publicly exposed cluster.
ACLRules []*ACLRuleSpec `json:"acl_rules"`
// Endpoints: zero or multiple EndpointSpec used to expose your cluster publicly and inside private networks. If no EndpoindSpec is given the cluster will be publicly exposed by default.
Endpoints []*EndpointSpec `json:"endpoints"`
// TLSEnabled: defines whether or not TLS is enabled.
TLSEnabled bool `json:"tls_enabled"`
// ClusterSettings: list of advanced settings to be set upon Database Instance initialization.
ClusterSettings []*ClusterSetting `json:"cluster_settings"`
}
// DeleteACLRuleRequest: delete acl rule request.
type DeleteACLRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ACLID: UUID of the ACL rule you want to delete.
ACLID string `json:"-"`
}
// DeleteClusterRequest: delete cluster request.
type DeleteClusterRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance to delete.
ClusterID string `json:"-"`
}
// DeleteClusterSettingRequest: delete cluster setting request.
type DeleteClusterSettingRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance where the settings must be set.
ClusterID string `json:"-"`
// SettingName: setting name to delete.
SettingName string `json:"-"`
}
// DeleteEndpointRequest: delete endpoint request.
type DeleteEndpointRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// EndpointID: UUID of the endpoint you want to delete.
EndpointID string `json:"-"`
}
// GetACLRuleRequest: get acl rule request.
type GetACLRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ACLID: UUID of the ACL rule you want to get.
ACLID string `json:"-"`
}
// GetClusterCertificateRequest: get cluster certificate request.
type GetClusterCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the cluster.
ClusterID string `json:"-"`
}
// GetClusterMetricsRequest: get cluster metrics request.
type GetClusterMetricsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the cluster.
ClusterID string `json:"-"`
// StartAt: start date.
StartAt *time.Time `json:"-"`
// EndAt: end date.
EndAt *time.Time `json:"-"`
// MetricName: name of the metric to gather.
MetricName *string `json:"-"`
}
// GetClusterRequest: get cluster request.
type GetClusterRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the cluster.
ClusterID string `json:"-"`
}
// GetEndpointRequest: get endpoint request.
type GetEndpointRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// EndpointID: UUID of the endpoint you want to get.
EndpointID string `json:"-"`
}
// ListClusterVersionsRequest: list cluster versions request.
type ListClusterVersionsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IncludeDisabled: defines whether or not to include disabled Redisâĸ engine versions.
IncludeDisabled bool `json:"-"`
// IncludeBeta: defines whether or not to include beta Redisâĸ engine versions.
IncludeBeta bool `json:"-"`
// IncludeDeprecated: defines whether or not to include deprecated Redisâĸ engine versions.
IncludeDeprecated bool `json:"-"`
// Version: list Redisâĸ engine versions that match a given name pattern.
Version *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListClusterVersionsResponse: list cluster versions response.
type ListClusterVersionsResponse struct {
// Versions: list of available Redisâĸ engine versions.
Versions []*ClusterVersion `json:"versions"`
// TotalCount: total count of available Redisâĸ engine versions.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClusterVersionsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClusterVersionsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListClusterVersionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Versions = append(r.Versions, results.Versions...)
r.TotalCount += uint32(len(results.Versions))
return uint32(len(results.Versions)), nil
}
// ListClustersRequest: list clusters request.
type ListClustersRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// Tags: filter by Database Instance tags.
Tags []string `json:"-"`
// Name: filter by Database Instance names.
Name *string `json:"-"`
// OrderBy: criteria to use when ordering the list.
// Default value: created_at_asc
OrderBy ListClustersRequestOrderBy `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// Version: filter by Redisâĸ engine version.
Version *string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListClustersResponse: list clusters response.
type ListClustersResponse struct {
// Clusters: list all Database Instances.
Clusters []*Cluster `json:"clusters"`
// TotalCount: total count of Database Instances.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListClustersResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListClustersResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListClustersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Clusters = append(r.Clusters, results.Clusters...)
r.TotalCount += uint32(len(results.Clusters))
return uint32(len(results.Clusters)), nil
}
// ListNodeTypesRequest: list node types request.
type ListNodeTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IncludeDisabledTypes: defines whether or not to include disabled types.
IncludeDisabledTypes bool `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListNodeTypesResponse: list node types response.
type ListNodeTypesResponse struct {
// NodeTypes: types of node.
NodeTypes []*NodeType `json:"node_types"`
// TotalCount: total count of node types available.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNodeTypesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNodeTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.NodeTypes = append(r.NodeTypes, results.NodeTypes...)
r.TotalCount += uint32(len(results.NodeTypes))
return uint32(len(results.NodeTypes)), nil
}
// MigrateClusterRequest: migrate cluster request.
type MigrateClusterRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance to update.
ClusterID string `json:"-"`
// Version: redisâĸ engine version of the Database Instance.
// Precisely one of Version, NodeType, ClusterSize must be set.
Version *string `json:"version,omitempty"`
// NodeType: type of node to use for the Database Instance.
// Precisely one of Version, NodeType, ClusterSize must be set.
NodeType *string `json:"node_type,omitempty"`
// ClusterSize: number of nodes for the Database Instance.
// Precisely one of Version, NodeType, ClusterSize must be set.
ClusterSize *uint32 `json:"cluster_size,omitempty"`
}
// RenewClusterCertificateRequest: renew cluster certificate request.
type RenewClusterCertificateRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the cluster.
ClusterID string `json:"-"`
}
// SetACLRulesRequest: set acl rules request.
type SetACLRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance where the ACL rules have to be set.
ClusterID string `json:"-"`
// ACLRules: aCLs rules to define for the cluster.
ACLRules []*ACLRuleSpec `json:"acl_rules"`
}
// SetACLRulesResponse: set acl rules response.
type SetACLRulesResponse struct {
// ACLRules: ACL Rules enabled for the Database Instance.
ACLRules []*ACLRule `json:"acl_rules"`
}
// SetClusterSettingsRequest: set cluster settings request.
type SetClusterSettingsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance where the settings must be set.
ClusterID string `json:"-"`
// Settings: settings to define for the Database Instance.
Settings []*ClusterSetting `json:"settings"`
}
// SetEndpointsRequest: set endpoints request.
type SetEndpointsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance where the endpoints have to be set.
ClusterID string `json:"-"`
// Endpoints: endpoints to define for the Database Instance.
Endpoints []*EndpointSpec `json:"endpoints"`
}
// SetEndpointsResponse: set endpoints response.
type SetEndpointsResponse struct {
// Endpoints: endpoints defined on the Database Instance.
Endpoints []*Endpoint `json:"endpoints"`
}
// UpdateClusterRequest: update cluster request.
type UpdateClusterRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ClusterID: UUID of the Database Instance to update.
ClusterID string `json:"-"`
// Name: name of the Database Instance.
Name *string `json:"name,omitempty"`
// Tags: database Instance tags.
Tags *[]string `json:"tags,omitempty"`
// UserName: name of the Database Instance user.
UserName *string `json:"user_name,omitempty"`
// Password: password of the Database Instance user.
Password *string `json:"password,omitempty"`
}
// UpdateEndpointRequest: update endpoint request.
type UpdateEndpointRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// EndpointID: UUID of the endpoint you want to get.
EndpointID string `json:"-"`
// PrivateNetwork: private Network details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PrivateNetwork *EndpointSpecPrivateNetworkSpec `json:"private_network,omitempty"`
// PublicNetwork: public network details.
// Precisely one of PrivateNetwork, PublicNetwork must be set.
PublicNetwork *EndpointSpecPublicNetworkSpec `json:"public_network,omitempty"`
}
// This API allows you to manage your Managed Databases for Redisâĸ.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2}
}
// CreateCluster: Create a new Redisâĸ Database Instance (Redisâĸ cluster). You must set the `zone`, `project_id`, `version`, `node_type`, `user_name` and `password` parameters. Optionally you can define `acl_rules`, `endpoints`, `tls_enabled` and `cluster_settings`.
func (s *API) CreateCluster(req *CreateClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("ins")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateCluster: Update the parameters of a Redisâĸ Database Instance (Redisâĸ cluster), including `name`, `tags`, `user_name` and `password`.
func (s *API) UpdateCluster(req *UpdateClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetCluster: Retrieve information about a Redisâĸ Database Instance (Redisâĸ cluster). Specify the `cluster_id` and `region` in your request to get information such as `id`, `status`, `version`, `tls_enabled`, `cluster_settings`, `upgradable_versions` and `endpoints` about your cluster in the response.
func (s *API) GetCluster(req *GetClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusters: List all Redisâĸ Database Instances (Redisâĸ cluster) in the specified zone. By default, the Database Instances returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. You can define additional parameters for your query, such as `tags`, `name`, `organization_id` and `version`.
func (s *API) ListClusters(req *ListClustersRequest, opts ...scw.RequestOption) (*ListClustersResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "version", req.Version)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters",
Query: query,
}
var resp ListClustersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// MigrateCluster: Upgrade your Redisâĸ Database Instance, either by upgrading to a bigger node type (vertical scaling) or by adding more nodes to your Database Instance to increase your number of endpoints and distribute cache (horizontal scaling, available for clusters only). Note that scaling horizontally your Redisâĸ Database Instance will not renew its TLS certificate. In order to refresh the TLS certificate, you must use the Renew TLS certificate endpoint.
func (s *API) MigrateCluster(req *MigrateClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/migrate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteCluster: Delete a Redisâĸ Database Instance (Redisâĸ cluster), specified by the `region` and `cluster_id` parameters. Deleting a Database Instance is permanent, and cannot be undone. Note that upon deletion all your data will be lost.
func (s *API) DeleteCluster(req *DeleteClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetClusterMetrics: Retrieve the metrics of a Redisâĸ Database Instance (Redisâĸ cluster). You can define the period from which to retrieve metrics by specifying the `start_date` and `end_date`.
func (s *API) GetClusterMetrics(req *GetClusterMetricsRequest, opts ...scw.RequestOption) (*ClusterMetricsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "start_at", req.StartAt)
parameter.AddToQuery(query, "end_at", req.EndAt)
parameter.AddToQuery(query, "metric_name", req.MetricName)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/metrics",
Query: query,
}
var resp ClusterMetricsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListNodeTypes: List all available node types. By default, the node types returned in the list are ordered by creation date in ascending order, though this can be modified via the `order_by` field.
func (s *API) ListNodeTypes(req *ListNodeTypesRequest, opts ...scw.RequestOption) (*ListNodeTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "include_disabled_types", req.IncludeDisabledTypes)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/node-types",
Query: query,
}
var resp ListNodeTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListClusterVersions: List the Redisâĸ database engine versions available. You can define additional parameters for your query, such as `include_disabled`, `include_beta`, `include_deprecated` and `version`.
func (s *API) ListClusterVersions(req *ListClusterVersionsRequest, opts ...scw.RequestOption) (*ListClusterVersionsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "include_disabled", req.IncludeDisabled)
parameter.AddToQuery(query, "include_beta", req.IncludeBeta)
parameter.AddToQuery(query, "include_deprecated", req.IncludeDeprecated)
parameter.AddToQuery(query, "version", req.Version)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/cluster-versions",
Query: query,
}
var resp ListClusterVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetClusterCertificate: Retrieve information about the TLS certificate of a Redisâĸ Database Instance (Redisâĸ cluster). Details like name and content are returned in the response.
func (s *API) GetClusterCertificate(req *GetClusterCertificateRequest, opts ...scw.RequestOption) (*scw.File, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/certificate",
}
var resp scw.File
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RenewClusterCertificate: Renew a TLS certificate for a Redisâĸ Database Instance (Redisâĸ cluster). Renewing a certificate means that you will not be able to connect to your Database Instance using the previous certificate. You will also need to download and update the new certificate for all database clients.
func (s *API) RenewClusterCertificate(req *RenewClusterCertificateRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/renew-certificate",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddClusterSettings: Add an advanced setting to a Redisâĸ Database Instance (Redisâĸ cluster). You must set the `name` and the `value` of each setting.
func (s *API) AddClusterSettings(req *AddClusterSettingsRequest, opts ...scw.RequestOption) (*ClusterSettingsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ClusterSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteClusterSetting: Delete an advanced setting in a Redisâĸ Database Instance (Redisâĸ cluster). You must specify the names of the settings you want to delete in the request body.
func (s *API) DeleteClusterSetting(req *DeleteClusterSettingRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
if fmt.Sprint(req.SettingName) == "" {
return nil, errors.New("field SettingName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/settings/" + fmt.Sprint(req.SettingName) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetClusterSettings: Update an advanced setting for a Redisâĸ Database Instance (Redisâĸ cluster). Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.
func (s *API) SetClusterSettings(req *SetClusterSettingsRequest, opts ...scw.RequestOption) (*ClusterSettingsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ClusterSettingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetACLRules: Replace all the ACL rules of a Redisâĸ Database Instance (Redisâĸ cluster).
func (s *API) SetACLRules(req *SetACLRulesRequest, opts ...scw.RequestOption) (*SetACLRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddACLRules: Add an additional ACL rule to a Redisâĸ Database Instance (Redisâĸ cluster).
func (s *API) AddACLRules(req *AddACLRulesRequest, opts ...scw.RequestOption) (*AddACLRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/acls",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddACLRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteACLRule: Delete an ACL rule of a Redisâĸ Database Instance (Redisâĸ cluster). You must specify the `acl_id` of the rule you want to delete in your request.
func (s *API) DeleteACLRule(req *DeleteACLRuleRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetACLRule: Retrieve information about an ACL rule of a Redisâĸ Database Instance (Redisâĸ cluster). You must specify the `acl_id` of the rule in your request.
func (s *API) GetACLRule(req *GetACLRuleRequest, opts ...scw.RequestOption) (*ACLRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ACLID) == "" {
return nil, errors.New("field ACLID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/acls/" + fmt.Sprint(req.ACLID) + "",
}
var resp ACLRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetEndpoints: Update an endpoint for a Redisâĸ Database Instance (Redisâĸ cluster). You must specify the `cluster_id` and the `endpoints` parameters in your request.
func (s *API) SetEndpoints(req *SetEndpointsRequest, opts ...scw.RequestOption) (*SetEndpointsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetEndpointsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddEndpoints: Add a new endpoint for a Redisâĸ Database Instance (Redisâĸ cluster). You can add `private_network` or `public_network` specifications to the body of the request.
func (s *API) AddEndpoints(req *AddEndpointsRequest, opts ...scw.RequestOption) (*AddEndpointsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ClusterID) == "" {
return nil, errors.New("field ClusterID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/clusters/" + fmt.Sprint(req.ClusterID) + "/endpoints",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddEndpointsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteEndpoint: Delete the endpoint of a Redisâĸ Database Instance (Redisâĸ cluster). You must specify the `region` and `endpoint_id` parameters of the endpoint you want to delete. Note that might need to update any environment configurations that point to the deleted endpoint.
func (s *API) DeleteEndpoint(req *DeleteEndpointRequest, opts ...scw.RequestOption) (*Cluster, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
var resp Cluster
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetEndpoint: Retrieve information about a Redisâĸ Database Instance (Redisâĸ cluster) endpoint. Full details about the endpoint, like `ips`, `port`, `private_network` and `public_network` specifications are returned in the response.
func (s *API) GetEndpoint(req *GetEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateEndpoint: Update information about a Redisâĸ Database Instance (Redisâĸ cluster) endpoint. Full details about the endpoint, like `ips`, `port`, `private_network` and `public_network` specifications are returned in the response.
func (s *API) UpdateEndpoint(req *UpdateEndpointRequest, opts ...scw.RequestOption) (*Endpoint, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.EndpointID) == "" {
return nil, errors.New("field EndpointID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/redis/v1/zones/" + fmt.Sprint(req.Zone) + "/endpoints/" + fmt.Sprint(req.EndpointID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Endpoint
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/v1/redis_utils.go 0000664 0000000 0000000 00000003205 14747113137 0027326 0 ustar 00root root 0000000 0000000 package redis
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 15 * time.Minute
)
// WaitForClusterRequest is used by WaitForCluster method.
type WaitForClusterRequest struct {
ClusterID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForCluster waits for the cluster to be in a "terminal state" before returning.
// This function can be used to wait for a cluster to be ready for example.
func (s *API) WaitForCluster(req *WaitForClusterRequest, opts ...scw.RequestOption) (*Cluster, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ClusterStatus]struct{}{
ClusterStatusReady: {},
ClusterStatusLocked: {},
ClusterStatusError: {},
ClusterStatusSuspended: {},
}
cluster, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetCluster(&GetClusterRequest{
Zone: req.Zone,
ClusterID: req.ClusterID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for cluster failed")
}
return cluster.(*Cluster), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026306 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/redis/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000002022 14747113137 0030466 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/redis/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepCluster(scwClient *scw.Client, zone scw.Zone) error {
redisAPI := redis.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the redis cluster in (%s)", zone)
listClusters, err := redisAPI.ListClusters(&redis.ListClustersRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing redis clusters in (%s) in sweeper: %w", zone, err)
}
for _, cluster := range listClusters.Clusters {
_, err := redisAPI.DeleteCluster(&redis.DeleteClusterRequest{
Zone: zone,
ClusterID: cluster.ID,
})
if err != nil {
return fmt.Errorf("error deleting redis cluster in sweeper: %w", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&redis.API{}).Zones() {
err := SweepCluster(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/ 0000775 0000000 0000000 00000000000 14747113137 0024665 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/ 0000775 0000000 0000000 00000000000 14747113137 0025213 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/image_utils.go 0000664 0000000 0000000 00000003000 14747113137 0030035 0 ustar 00root root 0000000 0000000 package registry
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForNamespaceRequest is used by WaitForNamespace method
type WaitForImageRequest struct {
ImageID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForImage wait for the image to be in a "terminal state" before returning.
// This function can be used to wait for an image to be ready for example.
func (s *API) WaitForImage(req *WaitForImageRequest, opts ...scw.RequestOption) (*Image, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ImageStatus]struct{}{
ImageStatusReady: {},
ImageStatusLocked: {},
ImageStatusError: {},
ImageStatusUnknown: {},
}
image, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
img, err := s.GetImage(&GetImageRequest{
Region: req.Region,
ImageID: req.ImageID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[img.Status]
return img, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for image failed")
}
return image.(*Image), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/registry_sdk.go 0000664 0000000 0000000 00000101252 14747113137 0030254 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package registry provides methods and message types of the registry v1 API.
package registry
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ImageStatus string
const (
ImageStatusUnknown = ImageStatus("unknown")
ImageStatusReady = ImageStatus("ready")
ImageStatusDeleting = ImageStatus("deleting")
ImageStatusError = ImageStatus("error")
ImageStatusLocked = ImageStatus("locked")
)
func (enum ImageStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum ImageStatus) Values() []ImageStatus {
return []ImageStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
}
}
func (enum ImageStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ImageStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ImageStatus(ImageStatus(tmp).String())
return nil
}
type ImageVisibility string
const (
ImageVisibilityVisibilityUnknown = ImageVisibility("visibility_unknown")
ImageVisibilityInherit = ImageVisibility("inherit")
ImageVisibilityPublic = ImageVisibility("public")
ImageVisibilityPrivate = ImageVisibility("private")
)
func (enum ImageVisibility) String() string {
if enum == "" {
// return default value if empty
return "visibility_unknown"
}
return string(enum)
}
func (enum ImageVisibility) Values() []ImageVisibility {
return []ImageVisibility{
"visibility_unknown",
"inherit",
"public",
"private",
}
}
func (enum ImageVisibility) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ImageVisibility) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ImageVisibility(ImageVisibility(tmp).String())
return nil
}
type ListImagesRequestOrderBy string
const (
ListImagesRequestOrderByCreatedAtAsc = ListImagesRequestOrderBy("created_at_asc")
ListImagesRequestOrderByCreatedAtDesc = ListImagesRequestOrderBy("created_at_desc")
ListImagesRequestOrderByNameAsc = ListImagesRequestOrderBy("name_asc")
ListImagesRequestOrderByNameDesc = ListImagesRequestOrderBy("name_desc")
)
func (enum ListImagesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListImagesRequestOrderBy) Values() []ListImagesRequestOrderBy {
return []ListImagesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListImagesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListImagesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListImagesRequestOrderBy(ListImagesRequestOrderBy(tmp).String())
return nil
}
type ListNamespacesRequestOrderBy string
const (
ListNamespacesRequestOrderByCreatedAtAsc = ListNamespacesRequestOrderBy("created_at_asc")
ListNamespacesRequestOrderByCreatedAtDesc = ListNamespacesRequestOrderBy("created_at_desc")
ListNamespacesRequestOrderByDescriptionAsc = ListNamespacesRequestOrderBy("description_asc")
ListNamespacesRequestOrderByDescriptionDesc = ListNamespacesRequestOrderBy("description_desc")
ListNamespacesRequestOrderByNameAsc = ListNamespacesRequestOrderBy("name_asc")
ListNamespacesRequestOrderByNameDesc = ListNamespacesRequestOrderBy("name_desc")
)
func (enum ListNamespacesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListNamespacesRequestOrderBy) Values() []ListNamespacesRequestOrderBy {
return []ListNamespacesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"description_asc",
"description_desc",
"name_asc",
"name_desc",
}
}
func (enum ListNamespacesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListNamespacesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListNamespacesRequestOrderBy(ListNamespacesRequestOrderBy(tmp).String())
return nil
}
type ListTagsRequestOrderBy string
const (
ListTagsRequestOrderByCreatedAtAsc = ListTagsRequestOrderBy("created_at_asc")
ListTagsRequestOrderByCreatedAtDesc = ListTagsRequestOrderBy("created_at_desc")
ListTagsRequestOrderByNameAsc = ListTagsRequestOrderBy("name_asc")
ListTagsRequestOrderByNameDesc = ListTagsRequestOrderBy("name_desc")
)
func (enum ListTagsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListTagsRequestOrderBy) Values() []ListTagsRequestOrderBy {
return []ListTagsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListTagsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListTagsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListTagsRequestOrderBy(ListTagsRequestOrderBy(tmp).String())
return nil
}
type NamespaceStatus string
const (
NamespaceStatusUnknown = NamespaceStatus("unknown")
NamespaceStatusReady = NamespaceStatus("ready")
NamespaceStatusDeleting = NamespaceStatus("deleting")
NamespaceStatusError = NamespaceStatus("error")
NamespaceStatusLocked = NamespaceStatus("locked")
)
func (enum NamespaceStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum NamespaceStatus) Values() []NamespaceStatus {
return []NamespaceStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
}
}
func (enum NamespaceStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NamespaceStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NamespaceStatus(NamespaceStatus(tmp).String())
return nil
}
type TagStatus string
const (
TagStatusUnknown = TagStatus("unknown")
TagStatusReady = TagStatus("ready")
TagStatusDeleting = TagStatus("deleting")
TagStatusError = TagStatus("error")
TagStatusLocked = TagStatus("locked")
)
func (enum TagStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum TagStatus) Values() []TagStatus {
return []TagStatus{
"unknown",
"ready",
"deleting",
"error",
"locked",
}
}
func (enum TagStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *TagStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = TagStatus(TagStatus(tmp).String())
return nil
}
// Image: image.
type Image struct {
// ID: UUID of the image.
ID string `json:"id"`
// Name: name of the image, it must be unique within the namespace.
Name string `json:"name"`
// NamespaceID: UUID of the namespace the image belongs to.
NamespaceID string `json:"namespace_id"`
// Status: status of the image.
// Default value: unknown
Status ImageStatus `json:"status"`
// StatusMessage: details of the image status.
StatusMessage *string `json:"status_message"`
// Visibility: set to `public` to allow the image to be pulled without authentication. Else, set to `private`. Set to `inherit` to keep the same visibility configuration as the namespace.
// Default value: visibility_unknown
Visibility ImageVisibility `json:"visibility"`
// Size: image size in bytes, calculated from the size of image layers. One layer used in two tags of the same image is counted once but one layer used in two images is counted twice.
Size scw.Size `json:"size"`
// CreatedAt: date and time of image creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last update.
UpdatedAt *time.Time `json:"updated_at"`
// Tags: list of docker tags of the image.
Tags []string `json:"tags"`
}
// Namespace: namespace.
type Namespace struct {
// ID: UUID of the namespace.
ID string `json:"id"`
// Name: name of the namespace, unique in a region accross all organizations.
Name string `json:"name"`
// Description: description of the namespace.
Description string `json:"description"`
// OrganizationID: owner of the namespace.
OrganizationID string `json:"organization_id"`
// ProjectID: project of the namespace.
ProjectID string `json:"project_id"`
// Status: namespace status.
// Default value: unknown
Status NamespaceStatus `json:"status"`
// StatusMessage: namespace status details.
StatusMessage string `json:"status_message"`
// Endpoint: endpoint reachable by docker.
Endpoint string `json:"endpoint"`
// IsPublic: defines whether or not namespace is public.
IsPublic bool `json:"is_public"`
// Size: total size of the namespace, calculated as the sum of the size of all images in the namespace.
Size scw.Size `json:"size"`
// CreatedAt: date and time of creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last update.
UpdatedAt *time.Time `json:"updated_at"`
// ImageCount: number of images in the namespace.
ImageCount uint32 `json:"image_count"`
// Region: region the namespace belongs to.
Region scw.Region `json:"region"`
}
// Tag: tag.
type Tag struct {
// ID: UUID of the tag.
ID string `json:"id"`
// Name: tag name, unique to an image.
Name string `json:"name"`
// ImageID: image ID the of the image the tag belongs to.
ImageID string `json:"image_id"`
// Status: tag status.
// Default value: unknown
Status TagStatus `json:"status"`
// Digest: hash of the tag content. Several tags of a same image may have the same digest.
Digest string `json:"digest"`
// CreatedAt: date and time of creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last update.
UpdatedAt *time.Time `json:"updated_at"`
}
// CreateNamespaceRequest: create namespace request.
type CreateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name of the namespace.
Name string `json:"name"`
// Description: description of the namespace.
Description string `json:"description"`
// Deprecated: OrganizationID: namespace owner (deprecated).
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
// ProjectID: project ID on which the namespace will be created.
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
// IsPublic: defines whether or not namespace is public.
IsPublic bool `json:"is_public"`
}
// DeleteImageRequest: delete image request.
type DeleteImageRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ImageID: UUID of the image.
ImageID string `json:"-"`
}
// DeleteNamespaceRequest: delete namespace request.
type DeleteNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace.
NamespaceID string `json:"-"`
}
// DeleteTagRequest: delete tag request.
type DeleteTagRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TagID: UUID of the tag.
TagID string `json:"-"`
// Deprecated: Force: if two tags share the same digest the deletion will fail unless this parameter is set to true (deprecated).
Force *bool `json:"force,omitempty"`
}
// GetImageRequest: get image request.
type GetImageRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ImageID: UUID of the image.
ImageID string `json:"-"`
}
// GetNamespaceRequest: get namespace request.
type GetNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: UUID of the namespace.
NamespaceID string `json:"-"`
}
// GetTagRequest: get tag request.
type GetTagRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// TagID: UUID of the tag.
TagID string `json:"-"`
}
// ListImagesRequest: list images request.
type ListImagesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: a positive integer to choose the page to display.
Page *int32 `json:"-"`
// PageSize: a positive integer lower or equal to 100 to select the number of items to display.
PageSize *uint32 `json:"-"`
// OrderBy: criteria to use when ordering image listings. Possible values are `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc`, `region`, `status_asc` and `status_desc`. The default value is `created_at_asc`.
// Default value: created_at_asc
OrderBy ListImagesRequestOrderBy `json:"-"`
// NamespaceID: filter by the namespace ID.
NamespaceID *string `json:"-"`
// Name: filter by the image name (exact match).
Name *string `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
}
// ListImagesResponse: list images response.
type ListImagesResponse struct {
// Images: paginated list of images that match the selected filters.
Images []*Image `json:"images"`
// TotalCount: total number of images that match the selected filters.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListImagesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListImagesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Images = append(r.Images, results.Images...)
r.TotalCount += uint32(len(results.Images))
return uint32(len(results.Images)), nil
}
// ListNamespacesRequest: list namespaces request.
type ListNamespacesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: a positive integer to choose the page to display.
Page *int32 `json:"-"`
// PageSize: a positive integer lower or equal to 100 to select the number of items to display.
PageSize *uint32 `json:"-"`
// OrderBy: criteria to use when ordering namespace listings. Possible values are `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc`, `region`, `status_asc` and `status_desc`. The default value is `created_at_asc`.
// Default value: created_at_asc
OrderBy ListNamespacesRequestOrderBy `json:"-"`
// OrganizationID: filter by Organization ID.
OrganizationID *string `json:"-"`
// ProjectID: filter by Project ID.
ProjectID *string `json:"-"`
// Name: filter by the namespace name (exact match).
Name *string `json:"-"`
}
// ListNamespacesResponse: list namespaces response.
type ListNamespacesResponse struct {
// Namespaces: paginated list of namespaces that match the selected filters.
Namespaces []*Namespace `json:"namespaces"`
// TotalCount: total number of namespaces that match the selected filters.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListNamespacesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListNamespacesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Namespaces = append(r.Namespaces, results.Namespaces...)
r.TotalCount += uint32(len(results.Namespaces))
return uint32(len(results.Namespaces)), nil
}
// ListTagsRequest: list tags request.
type ListTagsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ImageID: UUID of the image.
ImageID string `json:"-"`
// Page: a positive integer to choose the page to display.
Page *int32 `json:"-"`
// PageSize: a positive integer lower or equal to 100 to select the number of items to display.
PageSize *uint32 `json:"-"`
// OrderBy: criteria to use when ordering tag listings. Possible values are `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc`, `region`, `status_asc` and `status_desc`. The default value is `created_at_asc`.
// Default value: created_at_asc
OrderBy ListTagsRequestOrderBy `json:"-"`
// Name: filter by the tag name (exact match).
Name *string `json:"-"`
}
// ListTagsResponse: list tags response.
type ListTagsResponse struct {
// Tags: paginated list of tags that match the selected filters.
Tags []*Tag `json:"tags"`
// TotalCount: total number of tags that match the selected filters.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTagsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTagsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListTagsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tags = append(r.Tags, results.Tags...)
r.TotalCount += uint32(len(results.Tags))
return uint32(len(results.Tags)), nil
}
// UpdateImageRequest: update image request.
type UpdateImageRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ImageID: ID of the image to update.
ImageID string `json:"-"`
// Visibility: set to `public` to allow the image to be pulled without authentication. Else, set to `private`. Set to `inherit` to keep the same visibility configuration as the namespace.
// Default value: visibility_unknown
Visibility ImageVisibility `json:"visibility"`
}
// UpdateNamespaceRequest: update namespace request.
type UpdateNamespaceRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// NamespaceID: ID of the namespace to update.
NamespaceID string `json:"-"`
// Description: namespace description.
Description *string `json:"description,omitempty"`
// IsPublic: defines whether or not the namespace is public.
IsPublic *bool `json:"is_public,omitempty"`
}
// This API allows you to manage your Container Registry resources.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListNamespaces: List all namespaces in a specified region. By default, the namespaces listed are ordered by creation date in ascending order. This can be modified via the order_by field. You can also define additional parameters for your query, such as the `instance_id` and `project_id` parameters.
func (s *API) ListNamespaces(req *ListNamespacesRequest, opts ...scw.RequestOption) (*ListNamespacesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
Query: query,
}
var resp ListNamespacesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetNamespace: Retrieve information about a given namespace, specified by its `namespace_id` and region. Full details about the namespace, such as `description`, `project_id`, `status`, `endpoint`, `is_public`, `size`, and `image_count` are returned in the response.
func (s *API) GetNamespace(req *GetNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateNamespace: Create a new Container Registry namespace. You must specify the namespace name and region in which you want it to be created. Optionally, you can specify the `project_id` and `is_public` in the request payload.
func (s *API) CreateNamespace(req *CreateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("ns")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/namespaces",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateNamespace: Update the parameters of a given namespace, specified by its `namespace_id` and `region`. You can update the `description` and `is_public` parameters.
func (s *API) UpdateNamespace(req *UpdateNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteNamespace: Delete a given namespace. You must specify, in the endpoint, the `region` and `namespace_id` parameters of the namespace you want to delete.
func (s *API) DeleteNamespace(req *DeleteNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.NamespaceID) == "" {
return nil, errors.New("field NamespaceID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/namespaces/" + fmt.Sprint(req.NamespaceID) + "",
}
var resp Namespace
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListImages: List all images in a specified region. By default, the images listed are ordered by creation date in ascending order. This can be modified via the order_by field. You can also define additional parameters for your query, such as the `namespace_id` and `project_id` parameters.
func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "namespace_id", req.NamespaceID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/images",
Query: query,
}
var resp ListImagesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetImage: Retrieve information about a given container image, specified by its `image_id` and region. Full details about the image, such as `name`, `namespace_id`, `status`, `visibility`, and `size` are returned in the response.
func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*Image, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
var resp Image
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateImage: Update the parameters of a given image, specified by its `image_id` and `region`. You can update the `visibility` parameter.
func (s *API) UpdateImage(req *UpdateImageRequest, opts ...scw.RequestOption) (*Image, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Image
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteImage: Delete a given image. You must specify, in the endpoint, the `region` and `image_id` parameters of the image you want to delete.
func (s *API) DeleteImage(req *DeleteImageRequest, opts ...scw.RequestOption) (*Image, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/images/" + fmt.Sprint(req.ImageID) + "",
}
var resp Image
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTags: List all tags for a given image, specified by region. By default, the tags listed are ordered by creation date in ascending order. This can be modified via the order_by field. You can also define additional parameters for your query, such as the `name`.
func (s *API) ListTags(req *ListTagsRequest, opts ...scw.RequestOption) (*ListTagsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ImageID) == "" {
return nil, errors.New("field ImageID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/images/" + fmt.Sprint(req.ImageID) + "/tags",
Query: query,
}
var resp ListTagsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetTag: Retrieve information about a given image tag, specified by its `tag_id` and region. Full details about the tag, such as `name`, `image_id`, `status`, and `digest` are returned in the response.
func (s *API) GetTag(req *GetTagRequest, opts ...scw.RequestOption) (*Tag, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TagID) == "" {
return nil, errors.New("field TagID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/tags/" + fmt.Sprint(req.TagID) + "",
}
var resp Tag
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteTag: Delete a given image tag. You must specify, in the endpoint, the `region` and `tag_id` parameters of the tag you want to delete.
func (s *API) DeleteTag(req *DeleteTagRequest, opts ...scw.RequestOption) (*Tag, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "force", req.Force)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.TagID) == "" {
return nil, errors.New("field TagID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/registry/v1/regions/" + fmt.Sprint(req.Region) + "/tags/" + fmt.Sprint(req.TagID) + "",
Query: query,
}
var resp Tag
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/registry_utils.go 0000664 0000000 0000000 00000003254 14747113137 0030636 0 ustar 00root root 0000000 0000000 package registry
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 15 * time.Second
)
// WaitForNamespaceRequest is used by WaitForNamespace method
type WaitForNamespaceRequest struct {
NamespaceID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForNamespace wait for the namespace to be in a "terminal state" before returning.
// This function can be used to wait for a namespace to be ready for example.
func (s *API) WaitForNamespace(req *WaitForNamespaceRequest, opts ...scw.RequestOption) (*Namespace, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[NamespaceStatus]struct{}{
NamespaceStatusReady: {},
NamespaceStatusLocked: {},
NamespaceStatusError: {},
NamespaceStatusUnknown: {},
}
namespace, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
ns, err := s.GetNamespace(&GetNamespaceRequest{
Region: req.Region,
NamespaceID: req.NamespaceID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[ns.Status]
return ns, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for namespace failed")
}
return namespace.(*Namespace), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027050 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000002105 14747113137 0031232 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
"github.com/scaleway/scaleway-sdk-go/api/registry/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepNamespace(scwClient *scw.Client, region scw.Region) error {
registryAPI := registry.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the registry namespaces in (%s)", region)
listNamespaces, err := registryAPI.ListNamespaces(
®istry.ListNamespacesRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing namespaces in (%s) in sweeper: %s", region, err)
}
for _, ns := range listNamespaces.Namespaces {
_, err := registryAPI.DeleteNamespace(®istry.DeleteNamespaceRequest{
NamespaceID: ns.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting namespace in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (®istry.API{}).Regions() {
err := SweepNamespace(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/registry/v1/tag_utils.go 0000664 0000000 0000000 00000002705 14747113137 0027541 0 ustar 00root root 0000000 0000000 package registry
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// WaitForTagRequest is used by WaitForTag method
type WaitForTagRequest struct {
TagID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForTag wait for the tag to be in a "terminal state" before returning.
// This function can be used to wait for a tag to be ready for example.
func (s *API) WaitForTag(req *WaitForTagRequest, opts ...scw.RequestOption) (*Tag, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[TagStatus]struct{}{
TagStatusReady: {},
TagStatusLocked: {},
TagStatusError: {},
TagStatusUnknown: {},
}
tag, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
t, err := s.GetTag(&GetTagRequest{
Region: req.Region,
TagID: req.TagID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[t.Status]
return t, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for tag failed")
}
return tag.(*Tag), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/secret/ 0000775 0000000 0000000 00000000000 14747113137 0024302 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/secret/v1beta1/ 0000775 0000000 0000000 00000000000 14747113137 0025545 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/secret/v1beta1/secret_sdk.go 0000664 0000000 0000000 00000150236 14747113137 0030231 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package secret provides methods and message types of the secret v1beta1 API.
package secret
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type BrowseSecretsRequestOrderBy string
const (
BrowseSecretsRequestOrderByNameAsc = BrowseSecretsRequestOrderBy("name_asc")
BrowseSecretsRequestOrderByNameDesc = BrowseSecretsRequestOrderBy("name_desc")
BrowseSecretsRequestOrderByCreatedAtAsc = BrowseSecretsRequestOrderBy("created_at_asc")
BrowseSecretsRequestOrderByCreatedAtDesc = BrowseSecretsRequestOrderBy("created_at_desc")
BrowseSecretsRequestOrderByUpdatedAtAsc = BrowseSecretsRequestOrderBy("updated_at_asc")
BrowseSecretsRequestOrderByUpdatedAtDesc = BrowseSecretsRequestOrderBy("updated_at_desc")
)
func (enum BrowseSecretsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum BrowseSecretsRequestOrderBy) Values() []BrowseSecretsRequestOrderBy {
return []BrowseSecretsRequestOrderBy{
"name_asc",
"name_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum BrowseSecretsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BrowseSecretsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BrowseSecretsRequestOrderBy(BrowseSecretsRequestOrderBy(tmp).String())
return nil
}
type EphemeralPolicyAction string
const (
EphemeralPolicyActionUnknownAction = EphemeralPolicyAction("unknown_action")
// The version is deleted once it expires.
EphemeralPolicyActionDelete = EphemeralPolicyAction("delete")
// The version is disabled once it expires.
EphemeralPolicyActionDisable = EphemeralPolicyAction("disable")
)
func (enum EphemeralPolicyAction) String() string {
if enum == "" {
// return default value if empty
return "unknown_action"
}
return string(enum)
}
func (enum EphemeralPolicyAction) Values() []EphemeralPolicyAction {
return []EphemeralPolicyAction{
"unknown_action",
"delete",
"disable",
}
}
func (enum EphemeralPolicyAction) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EphemeralPolicyAction) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EphemeralPolicyAction(EphemeralPolicyAction(tmp).String())
return nil
}
type ListSecretsRequestOrderBy string
const (
ListSecretsRequestOrderByNameAsc = ListSecretsRequestOrderBy("name_asc")
ListSecretsRequestOrderByNameDesc = ListSecretsRequestOrderBy("name_desc")
ListSecretsRequestOrderByCreatedAtAsc = ListSecretsRequestOrderBy("created_at_asc")
ListSecretsRequestOrderByCreatedAtDesc = ListSecretsRequestOrderBy("created_at_desc")
ListSecretsRequestOrderByUpdatedAtAsc = ListSecretsRequestOrderBy("updated_at_asc")
ListSecretsRequestOrderByUpdatedAtDesc = ListSecretsRequestOrderBy("updated_at_desc")
)
func (enum ListSecretsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "name_asc"
}
return string(enum)
}
func (enum ListSecretsRequestOrderBy) Values() []ListSecretsRequestOrderBy {
return []ListSecretsRequestOrderBy{
"name_asc",
"name_desc",
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
}
}
func (enum ListSecretsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSecretsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSecretsRequestOrderBy(ListSecretsRequestOrderBy(tmp).String())
return nil
}
type Product string
const (
ProductUnknownProduct = Product("unknown_product")
ProductEdgeServices = Product("edge_services")
)
func (enum Product) String() string {
if enum == "" {
// return default value if empty
return "unknown_product"
}
return string(enum)
}
func (enum Product) Values() []Product {
return []Product{
"unknown_product",
"edge_services",
}
}
func (enum Product) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *Product) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = Product(Product(tmp).String())
return nil
}
type SecretStatus string
const (
SecretStatusUnknownStatus = SecretStatus("unknown_status")
SecretStatusReady = SecretStatus("ready")
SecretStatusLocked = SecretStatus("locked")
)
func (enum SecretStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SecretStatus) Values() []SecretStatus {
return []SecretStatus{
"unknown_status",
"ready",
"locked",
}
}
func (enum SecretStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecretStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecretStatus(SecretStatus(tmp).String())
return nil
}
type SecretType string
const (
SecretTypeUnknownType = SecretType("unknown_type")
// Default type.
SecretTypeOpaque = SecretType("opaque")
// List of concatenated PEM blocks. They can contain certificates, private keys or any other PEM block types.
SecretTypeCertificate = SecretType("certificate")
// Flat JSON that allows you to set as many first level keys and scalar types as values (string, numeric, boolean) as you need.
SecretTypeKeyValue = SecretType("key_value")
// Flat JSON that allows you to set a username and a password.
SecretTypeBasicCredentials = SecretType("basic_credentials")
// Flat JSON that allows you to set an engine, username, password, host, database name, and port.
SecretTypeDatabaseCredentials = SecretType("database_credentials")
// Flat JSON that allows you to set an SSH key.
SecretTypeSSHKey = SecretType("ssh_key")
)
func (enum SecretType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum SecretType) Values() []SecretType {
return []SecretType{
"unknown_type",
"opaque",
"certificate",
"key_value",
"basic_credentials",
"database_credentials",
"ssh_key",
}
}
func (enum SecretType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecretType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecretType(SecretType(tmp).String())
return nil
}
type SecretVersionStatus string
const (
SecretVersionStatusUnknownStatus = SecretVersionStatus("unknown_status")
SecretVersionStatusEnabled = SecretVersionStatus("enabled")
SecretVersionStatusDisabled = SecretVersionStatus("disabled")
SecretVersionStatusDeleted = SecretVersionStatus("deleted")
)
func (enum SecretVersionStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum SecretVersionStatus) Values() []SecretVersionStatus {
return []SecretVersionStatus{
"unknown_status",
"enabled",
"disabled",
"deleted",
}
}
func (enum SecretVersionStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *SecretVersionStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = SecretVersionStatus(SecretVersionStatus(tmp).String())
return nil
}
// EphemeralPolicy: ephemeral policy.
type EphemeralPolicy struct {
// TimeToLive: time frame, from one second and up to one year, during which the secret's versions are valid.
TimeToLive *scw.Duration `json:"time_to_live"`
// ExpiresOnceAccessed: returns `true` if the version expires after a single user access.
ExpiresOnceAccessed *bool `json:"expires_once_accessed"`
// Action: see the `EphemeralPolicy.Action` enum for a description of values.
// Default value: unknown_action
Action EphemeralPolicyAction `json:"action"`
}
// BrowseSecretsResponseItemFolderDetails: browse secrets response item folder details.
type BrowseSecretsResponseItemFolderDetails struct {
}
// BrowseSecretsResponseItemSecretDetails: browse secrets response item secret details.
type BrowseSecretsResponseItemSecretDetails struct {
ID string `json:"id"`
Tags []string `json:"tags"`
VersionCount uint32 `json:"version_count"`
Protected bool `json:"protected"`
EphemeralPolicy *EphemeralPolicy `json:"ephemeral_policy"`
// Type: default value: unknown_type
Type SecretType `json:"type"`
}
// EphemeralProperties: ephemeral properties.
type EphemeralProperties struct {
// ExpiresAt: (Optional.) If not specified, the version does not have an expiration date.
ExpiresAt *time.Time `json:"expires_at"`
// ExpiresOnceAccessed: (Optional.) If not specified, the version can be accessed an unlimited amount of times.
ExpiresOnceAccessed *bool `json:"expires_once_accessed"`
// Action: see `EphemeralPolicy.Action` enum for a description of values.
// Default value: unknown_action
Action EphemeralPolicyAction `json:"action"`
}
// BrowseSecretsResponseItem: browse secrets response item.
type BrowseSecretsResponseItem struct {
Name string `json:"name"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
// Precisely one of Secret, Folder must be set.
Secret *BrowseSecretsResponseItemSecretDetails `json:"secret,omitempty"`
// Precisely one of Secret, Folder must be set.
Folder *BrowseSecretsResponseItemFolderDetails `json:"folder,omitempty"`
}
// SecretVersion: secret version.
type SecretVersion struct {
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1.
Revision uint32 `json:"revision"`
// SecretID: ID of the secret.
SecretID string `json:"secret_id"`
// Status: * `unknown_status`: the version is in an invalid state.
// * `enabled`: the version is accessible.
// * `disabled`: the version is not accessible but can be enabled.
// * `deleted`: the version is permanently deleted. It is not possible to recover it.
// Default value: unknown_status
Status SecretVersionStatus `json:"status"`
// CreatedAt: date and time of the version's creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update of the version.
UpdatedAt *time.Time `json:"updated_at"`
// DeletedAt: date and time of the version's deletion.
DeletedAt *time.Time `json:"deleted_at"`
// Description: description of the version.
Description *string `json:"description"`
// Latest: returns `true` if the version is the latest.
Latest bool `json:"latest"`
// EphemeralProperties: returns the version's expiration date, whether it expires after being accessed once, and the action to perform (disable or delete) once the version expires.
EphemeralProperties *EphemeralProperties `json:"ephemeral_properties"`
}
// Secret: secret.
type Secret struct {
// ID: ID of the secret.
ID string `json:"id"`
// ProjectID: ID of the Project containing the secret.
ProjectID string `json:"project_id"`
// Name: name of the secret.
Name string `json:"name"`
// Status: * `ready`: the secret can be read, modified and deleted.
// * `locked`: no action can be performed on the secret. This status can only be applied and removed by Scaleway.
// Default value: unknown_status
Status SecretStatus `json:"status"`
// CreatedAt: date and time of the secret's creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update of the secret.
UpdatedAt *time.Time `json:"updated_at"`
// Tags: list of the secret's tags.
Tags []string `json:"tags"`
// VersionCount: number of versions for this secret.
VersionCount uint32 `json:"version_count"`
// Description: updated description of the secret.
Description *string `json:"description"`
// Managed: returns `true` for secrets that are managed by another product.
Managed bool `json:"managed"`
// Protected: returns `true` for protected secrets that cannot be deleted.
Protected bool `json:"protected"`
// Type: see the `Secret.Type` enum for a description of values.
// Default value: unknown_type
Type SecretType `json:"type"`
// Path: location of the secret in the directory structure.
Path string `json:"path"`
// EphemeralPolicy: (Optional.) Policy that defines whether/when a secret's versions expire. By default, the policy is applied to all the secret's versions.
EphemeralPolicy *EphemeralPolicy `json:"ephemeral_policy"`
// UsedBy: list of Scaleway resources that can access and manage the secret.
UsedBy []Product `json:"used_by"`
// Region: region of the secret.
Region scw.Region `json:"region"`
}
// AccessSecretVersionByPathRequest: access secret version by path request.
type AccessSecretVersionByPathRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - an integer (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
// SecretPath: secret's path.
SecretPath string `json:"-"`
// SecretName: secret's name.
SecretName string `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
}
// AccessSecretVersionRequest: access secret version request.
type AccessSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
}
// AccessSecretVersionResponse: access secret version response.
type AccessSecretVersionResponse struct {
// SecretID: ID of the secret.
SecretID string `json:"secret_id"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1.
Revision uint32 `json:"revision"`
// Data: the base64-encoded secret payload of the version.
Data []byte `json:"data"`
// DataCrc32: this field is only available if a CRC32 was supplied during the creation of the version.
DataCrc32 *uint32 `json:"data_crc32"`
// Type: see the `Secret.Type` enum for a description of values.
// Default value: unknown_type
Type SecretType `json:"type"`
}
// AddSecretOwnerRequest: add secret owner request.
type AddSecretOwnerRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Product: see `Product` enum for description of values.
// Default value: unknown_product
Product Product `json:"product"`
}
// BasicCredentials: basic credentials.
type BasicCredentials struct {
// Username: the username or identifier associated with the credentials.
Username string `json:"username"`
// Password: the password associated with the credentials.
Password string `json:"password"`
}
// BrowseSecretsRequest: browse secrets request.
type BrowseSecretsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: filter by Project ID (optional).
ProjectID *string `json:"-"`
// OrderBy: default value: name_asc
OrderBy BrowseSecretsRequestOrderBy `json:"-"`
// Prefix: filter secrets and folders for a given prefix (default /).
Prefix string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// Tags: filter secrets by tags.
Tags []string `json:"-"`
// Type: filter by secret type (optional).
// Default value: unknown_type
Type SecretType `json:"-"`
}
// BrowseSecretsResponse: browse secrets response.
type BrowseSecretsResponse struct {
// Items: repeated item of type secret or folder, sorted by the request parameter.
Items []*BrowseSecretsResponseItem `json:"items"`
// CurrentPath: current path for the given prefix.
CurrentPath string `json:"current_path"`
// TotalCount: count of all secrets and folders matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *BrowseSecretsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *BrowseSecretsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*BrowseSecretsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Items = append(r.Items, results.Items...)
r.TotalCount += uint64(len(results.Items))
return uint64(len(results.Items)), nil
}
// CreateSecretRequest: create secret request.
type CreateSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project containing the secret.
ProjectID string `json:"project_id"`
// Name: name of the secret.
Name string `json:"name"`
// Tags: list of the secret's tags.
Tags []string `json:"tags"`
// Description: description of the secret.
Description *string `json:"description,omitempty"`
// Type: (Optional.) See the `Secret.Type` enum for a description of values. If not specified, the type is `Opaque`.
// Default value: unknown_type
Type SecretType `json:"type"`
// Path: (Optional.) Location of the secret in the directory structure. If not specified, the path is `/`.
Path *string `json:"path,omitempty"`
// EphemeralPolicy: (Optional.) Policy that defines whether/when a secret's versions expire. By default, the policy is applied to all the secret's versions.
EphemeralPolicy *EphemeralPolicy `json:"ephemeral_policy,omitempty"`
// Protected: a protected secret cannot be deleted.
Protected bool `json:"protected"`
}
// CreateSecretVersionRequest: create secret version request.
type CreateSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Data: the base64-encoded secret payload of the version.
Data []byte `json:"data"`
// Description: description of the version.
Description *string `json:"description,omitempty"`
// DisablePrevious: (Optional.) If there is no previous version or if the previous version was already disabled, does nothing.
DisablePrevious *bool `json:"disable_previous,omitempty"`
// DataCrc32: if specified, Secret Manager will verify the integrity of the data received against the given CRC32 checksum. An error is returned if the CRC32 does not match. If, however, the CRC32 matches, it will be stored and returned along with the SecretVersion on future access requests.
DataCrc32 *uint32 `json:"data_crc32,omitempty"`
}
// DatabaseCredentials: database credentials.
type DatabaseCredentials struct {
// Engine: supported database engines are: 'postgres', 'mysql', 'other'.
Engine string `json:"engine"`
// Username: the username used to authenticate to the database server.
Username string `json:"username"`
// Password: the password used to authenticate to the database server.
Password string `json:"password"`
// Host: the hostname or resolvable DNS name of the database server.
Host string `json:"host"`
// Dbname: the name of the database to connect to.
Dbname string `json:"dbname"`
// Port: the port must be an integer ranging from 0 to 65535.
Port string `json:"port"`
}
// DeleteSecretRequest: delete secret request.
type DeleteSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
}
// DeleteSecretVersionRequest: delete secret version request.
type DeleteSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
}
// DisableSecretVersionRequest: disable secret version request.
type DisableSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
}
// EnableSecretVersionRequest: enable secret version request.
type EnableSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
}
// GetSecretRequest: get secret request.
type GetSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
}
// GetSecretVersionRequest: get secret version request.
type GetSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
}
// ListSecretTypesRequest: list secret types request.
type ListSecretTypesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListSecretTypesResponse: list secret types response.
type ListSecretTypesResponse struct {
// Types: list of secret types.
Types []SecretType `json:"types"`
// TotalCount: count of all secret types matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSecretTypesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSecretTypesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSecretTypesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Types = append(r.Types, results.Types...)
r.TotalCount += uint64(len(results.Types))
return uint64(len(results.Types)), nil
}
// ListSecretVersionsRequest: list secret versions request.
type ListSecretVersionsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// Status: filter results by status.
Status []SecretVersionStatus `json:"-"`
}
// ListSecretVersionsResponse: list secret versions response.
type ListSecretVersionsResponse struct {
// Versions: single page of versions.
Versions []*SecretVersion `json:"versions"`
// TotalCount: number of versions.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSecretVersionsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSecretVersionsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSecretVersionsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Versions = append(r.Versions, results.Versions...)
r.TotalCount += uint64(len(results.Versions))
return uint64(len(results.Versions)), nil
}
// ListSecretsRequest: list secrets request.
type ListSecretsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrganizationID: filter by Organization ID (optional).
OrganizationID *string `json:"-"`
// ProjectID: filter by Project ID (optional).
ProjectID *string `json:"-"`
// OrderBy: default value: name_asc
OrderBy ListSecretsRequestOrderBy `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// Tags: list of tags to filter on (optional).
Tags []string `json:"-"`
// Name: filter by secret name (optional).
Name *string `json:"-"`
// Path: filter by exact path (optional).
Path *string `json:"-"`
// Ephemeral: filter by ephemeral / not ephemeral (optional).
Ephemeral *bool `json:"-"`
// Type: filter by secret type (optional).
// Default value: unknown_type
Type SecretType `json:"-"`
}
// ListSecretsResponse: list secrets response.
type ListSecretsResponse struct {
// Secrets: single page of secrets matching the requested criteria.
Secrets []*Secret `json:"secrets"`
// TotalCount: count of all secrets matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSecretsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSecretsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListSecretsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Secrets = append(r.Secrets, results.Secrets...)
r.TotalCount += uint64(len(results.Secrets))
return uint64(len(results.Secrets)), nil
}
// ListTagsRequest: list tags request.
type ListTagsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the Project to target.
ProjectID string `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
}
// ListTagsResponse: list tags response.
type ListTagsResponse struct {
// Tags: list of tags.
Tags []string `json:"tags"`
// TotalCount: count of all tags matching the requested criteria.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListTagsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListTagsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListTagsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Tags = append(r.Tags, results.Tags...)
r.TotalCount += uint64(len(results.Tags))
return uint64(len(results.Tags)), nil
}
// ProtectSecretRequest: protect secret request.
type ProtectSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret to enable secret protection for.
SecretID string `json:"-"`
}
// SSHKey: ssh key.
type SSHKey struct {
// SSHPrivateKey: the private SSH key.
SSHPrivateKey string `json:"ssh_private_key"`
}
// UnprotectSecretRequest: unprotect secret request.
type UnprotectSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret to disable secret protection for.
SecretID string `json:"-"`
}
// UpdateSecretRequest: update secret request.
type UpdateSecretRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Name: secret's updated name (optional).
Name *string `json:"name,omitempty"`
// Tags: secret's updated list of tags (optional).
Tags *[]string `json:"tags,omitempty"`
// Description: description of the secret.
Description *string `json:"description,omitempty"`
// Path: (Optional.) Location of the folder in the directory structure. If not specified, the path is `/`.
Path *string `json:"path,omitempty"`
// EphemeralPolicy: (Optional.) Policy that defines whether/when a secret's versions expire.
EphemeralPolicy *EphemeralPolicy `json:"ephemeral_policy,omitempty"`
}
// UpdateSecretVersionRequest: update secret version request.
type UpdateSecretVersionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// SecretID: ID of the secret.
SecretID string `json:"-"`
// Revision: the first version of the secret is numbered 1, and all subsequent revisions augment by 1. Value can be either:
// - a number (the revision number)
// - "latest" (the latest revision)
// - "latest_enabled" (the latest enabled revision).
Revision string `json:"-"`
// Description: description of the version.
Description *string `json:"description,omitempty"`
// EphemeralProperties: (Optional.) Properties that defines the version's expiration date, whether it expires after being accessed once, and the action to perform (disable or delete) once the version expires.
EphemeralProperties *EphemeralProperties `json:"ephemeral_properties,omitempty"`
}
// This API allows you to manage your Secret Manager services, for storing, accessing and sharing sensitive data such as passwords, API keys and certificates.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateSecret: Create a secret in a given region specified by the `region` parameter.
func (s *API) CreateSecret(req *CreateSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSecret: Retrieve the metadata of a secret specified by the `region` and `secret_id` parameters.
func (s *API) GetSecret(req *GetSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSecret: Edit a secret's metadata such as name, tag(s), description and ephemeral policy. The secret to update is specified by the `secret_id` and `region` parameters.
func (s *API) UpdateSecret(req *UpdateSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSecret: Delete a given secret specified by the `region` and `secret_id` parameters.
func (s *API) DeleteSecret(req *DeleteSecretRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListSecrets: Retrieve the list of secrets created within an Organization and/or Project. You must specify either the `organization_id` or the `project_id` and the `region`.
func (s *API) ListSecrets(req *ListSecretsRequest, opts ...scw.RequestOption) (*ListSecretsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "path", req.Path)
parameter.AddToQuery(query, "ephemeral", req.Ephemeral)
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets",
Query: query,
}
var resp ListSecretsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// BrowseSecrets: Retrieve the list of secrets and folders for the given prefix. You must specify either the `organization_id` or the `project_id` and the `region`.
func (s *API) BrowseSecrets(req *BrowseSecretsRequest, opts ...scw.RequestOption) (*BrowseSecretsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "prefix", req.Prefix)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/browse",
Query: query,
}
var resp BrowseSecretsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ProtectSecret: Enable secret protection for a given secret specified by the `secret_id` parameter. Enabling secret protection means that your secret can be read and modified, but it cannot be deleted.
func (s *API) ProtectSecret(req *ProtectSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/protect",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnprotectSecret: Disable secret protection for a given secret specified by the `secret_id` parameter. Disabling secret protection means that your secret can be read, modified and deleted.
func (s *API) UnprotectSecret(req *UnprotectSecretRequest, opts ...scw.RequestOption) (*Secret, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/unprotect",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Secret
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddSecretOwner: Allow a product to use the secret.
func (s *API) AddSecretOwner(req *AddSecretOwnerRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/add-owner",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// CreateSecretVersion: Create a version of a given secret specified by the `region` and `secret_id` parameters.
func (s *API) CreateSecretVersion(req *CreateSecretVersionRequest, opts ...scw.RequestOption) (*SecretVersion, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SecretVersion
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetSecretVersion: Retrieve the metadata of a secret's given version specified by the `region`, `secret_id` and `revision` parameters.
func (s *API) GetSecretVersion(req *GetSecretVersionRequest, opts ...scw.RequestOption) (*SecretVersion, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "",
}
var resp SecretVersion
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateSecretVersion: Edit the metadata of a secret's given version, specified by the `region`, `secret_id` and `revision` parameters.
func (s *API) UpdateSecretVersion(req *UpdateSecretVersionRequest, opts ...scw.RequestOption) (*SecretVersion, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SecretVersion
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSecretVersion: Delete a secret's version and the sensitive data contained in it. Deleting a version is permanent and cannot be undone.
func (s *API) DeleteSecretVersion(req *DeleteSecretVersionRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListSecretVersions: Retrieve the list of a given secret's versions specified by the `secret_id` and `region` parameters.
func (s *API) ListSecretVersions(req *ListSecretVersionsRequest, opts ...scw.RequestOption) (*ListSecretVersionsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "status", req.Status)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions",
Query: query,
}
var resp ListSecretVersionsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AccessSecretVersion: Access sensitive data in a secret's version specified by the `region`, `secret_id` and `revision` parameters.
func (s *API) AccessSecretVersion(req *AccessSecretVersionRequest, opts ...scw.RequestOption) (*AccessSecretVersionResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "/access",
}
var resp AccessSecretVersionResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AccessSecretVersionByPath: Access sensitive data in a secret's version specified by the `region`, `secret_name`, `secret_path` and `revision` parameters.
func (s *API) AccessSecretVersionByPath(req *AccessSecretVersionByPathRequest, opts ...scw.RequestOption) (*AccessSecretVersionResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
query := url.Values{}
parameter.AddToQuery(query, "secret_path", req.SecretPath)
parameter.AddToQuery(query, "secret_name", req.SecretName)
parameter.AddToQuery(query, "project_id", req.ProjectID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets-by-path/versions/" + fmt.Sprint(req.Revision) + "/access",
Query: query,
}
var resp AccessSecretVersionResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableSecretVersion: Make a specific version accessible. You must specify the `region`, `secret_id` and `revision` parameters.
func (s *API) EnableSecretVersion(req *EnableSecretVersionRequest, opts ...scw.RequestOption) (*SecretVersion, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "/enable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SecretVersion
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DisableSecretVersion: Make a specific version inaccessible. You must specify the `region`, `secret_id` and `revision` parameters.
func (s *API) DisableSecretVersion(req *DisableSecretVersionRequest, opts ...scw.RequestOption) (*SecretVersion, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.SecretID) == "" {
return nil, errors.New("field SecretID cannot be empty in request")
}
if fmt.Sprint(req.Revision) == "" {
return nil, errors.New("field Revision cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secrets/" + fmt.Sprint(req.SecretID) + "/versions/" + fmt.Sprint(req.Revision) + "/disable",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SecretVersion
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListTags: List all tags associated with secrets within a given Project.
func (s *API) ListTags(req *ListTagsRequest, opts ...scw.RequestOption) (*ListTagsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/tags",
Query: query,
}
var resp ListTagsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSecretTypes: List all secret types created within a given Project.
func (s *API) ListSecretTypes(req *ListSecretTypesRequest, opts ...scw.RequestOption) (*ListSecretTypesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/secret-manager/v1beta1/regions/" + fmt.Sprint(req.Region) + "/secret-types",
Query: query,
}
var resp ListSecretTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/secret/v1beta1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027402 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/secret/v1beta1/sweepers/sweepers.go 0000664 0000000 0000000 00000002026 14747113137 0031566 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
secretSDK "github.com/scaleway/scaleway-sdk-go/api/secret/v1beta1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepSecret(scwClient *scw.Client, region scw.Region) error {
secretAPI := secretSDK.NewAPI(scwClient)
logger.Warningf("sweeper: deleting the secrets in (%s)", region)
listSecrets, err := secretAPI.ListSecrets(&secretSDK.ListSecretsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing secrets in (%s) in sweeper: %s", region, err)
}
for _, se := range listSecrets.Secrets {
err := secretAPI.DeleteSecret(&secretSDK.DeleteSecretRequest{
SecretID: se.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting secret in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&secretSDK.API{}).Regions() {
err := SweepSecret(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/ 0000775 0000000 0000000 00000000000 14747113137 0026377 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0030014 5 ustar 00root root 0000000 0000000 serverless_sqldb_sdk.go 0000664 0000000 0000000 00000056625 14747113137 0034525 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/v1alpha1 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package serverless_sqldb provides methods and message types of the serverless_sqldb v1alpha1 API.
package serverless_sqldb
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DatabaseBackupStatus string
const (
DatabaseBackupStatusUnknownStatus = DatabaseBackupStatus("unknown_status")
DatabaseBackupStatusError = DatabaseBackupStatus("error")
DatabaseBackupStatusReady = DatabaseBackupStatus("ready")
DatabaseBackupStatusLocked = DatabaseBackupStatus("locked")
)
func (enum DatabaseBackupStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DatabaseBackupStatus) Values() []DatabaseBackupStatus {
return []DatabaseBackupStatus{
"unknown_status",
"error",
"ready",
"locked",
}
}
func (enum DatabaseBackupStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DatabaseBackupStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DatabaseBackupStatus(DatabaseBackupStatus(tmp).String())
return nil
}
type DatabaseStatus string
const (
DatabaseStatusUnknownStatus = DatabaseStatus("unknown_status")
DatabaseStatusError = DatabaseStatus("error")
DatabaseStatusCreating = DatabaseStatus("creating")
DatabaseStatusReady = DatabaseStatus("ready")
DatabaseStatusDeleting = DatabaseStatus("deleting")
DatabaseStatusRestoring = DatabaseStatus("restoring")
DatabaseStatusLocked = DatabaseStatus("locked")
)
func (enum DatabaseStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DatabaseStatus) Values() []DatabaseStatus {
return []DatabaseStatus{
"unknown_status",
"error",
"creating",
"ready",
"deleting",
"restoring",
"locked",
}
}
func (enum DatabaseStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DatabaseStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DatabaseStatus(DatabaseStatus(tmp).String())
return nil
}
type ListDatabaseBackupsRequestOrderBy string
const (
ListDatabaseBackupsRequestOrderByCreatedAtDesc = ListDatabaseBackupsRequestOrderBy("created_at_desc")
ListDatabaseBackupsRequestOrderByCreatedAtAsc = ListDatabaseBackupsRequestOrderBy("created_at_asc")
)
func (enum ListDatabaseBackupsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListDatabaseBackupsRequestOrderBy) Values() []ListDatabaseBackupsRequestOrderBy {
return []ListDatabaseBackupsRequestOrderBy{
"created_at_desc",
"created_at_asc",
}
}
func (enum ListDatabaseBackupsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabaseBackupsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabaseBackupsRequestOrderBy(ListDatabaseBackupsRequestOrderBy(tmp).String())
return nil
}
type ListDatabasesRequestOrderBy string
const (
ListDatabasesRequestOrderByCreatedAtAsc = ListDatabasesRequestOrderBy("created_at_asc")
ListDatabasesRequestOrderByCreatedAtDesc = ListDatabasesRequestOrderBy("created_at_desc")
ListDatabasesRequestOrderByNameAsc = ListDatabasesRequestOrderBy("name_asc")
ListDatabasesRequestOrderByNameDesc = ListDatabasesRequestOrderBy("name_desc")
)
func (enum ListDatabasesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDatabasesRequestOrderBy) Values() []ListDatabasesRequestOrderBy {
return []ListDatabasesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListDatabasesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabasesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabasesRequestOrderBy(ListDatabasesRequestOrderBy(tmp).String())
return nil
}
// DatabaseBackup: database backup.
type DatabaseBackup struct {
// ID: UUID that uniquely identifies a Serverless SQL Database backup.
ID string `json:"id"`
// Status: status of the Serverless SQL Database backup. One of `unknown_status` | `error` | `ready` | `locked`.
// Default value: unknown_status
Status DatabaseBackupStatus `json:"status"`
// OrganizationID: the ID of your Scaleway organization.
OrganizationID string `json:"organization_id"`
// ProjectID: UUID of the Scaleway project.
ProjectID string `json:"project_id"`
// DatabaseID: UUID of the source Serverless SQL Database the backup is created from.
DatabaseID string `json:"database_id"`
// CreatedAt: creation date.
CreatedAt *time.Time `json:"created_at"`
// ExpiresAt: expiration date.
ExpiresAt *time.Time `json:"expires_at"`
// Size: size (in bytes) of the database backup file.
Size *scw.Size `json:"size"`
// DbSize: size (in bytes) of the database when backup has been done.
DbSize *scw.Size `json:"db_size"`
// DownloadURL: download URL of the exported database backup.
DownloadURL *string `json:"download_url"`
// DownloadURLExpiresAt: expiration date of the download URL.
DownloadURLExpiresAt *time.Time `json:"download_url_expires_at"`
// Region: region of the database backup.
Region scw.Region `json:"region"`
}
// Database: database.
type Database struct {
// ID: UUID that uniquely identifies your Serverless SQL DB Database.
ID string `json:"id"`
// Name: name of the database.
Name string `json:"name"`
// Status: status of the Serverless SQL Ddatabase. One of `unknown_status` | `ready` | `creating` | `deleting` | `error` | `restoring` | `locked`.
// Default value: unknown_status
Status DatabaseStatus `json:"status"`
// Endpoint: endpoint of the database.
Endpoint string `json:"endpoint"`
// OrganizationID: the ID of your Scaleway organization.
OrganizationID string `json:"organization_id"`
// ProjectID: project ID the database belongs to.
ProjectID string `json:"project_id"`
// Region: region of the database.
Region scw.Region `json:"region"`
// CreatedAt: creation date.
CreatedAt *time.Time `json:"created_at"`
// CPUMin: the minimum number of CPU units for your Serverless SQL Database.
CPUMin uint32 `json:"cpu_min"`
// CPUMax: the maximum number of CPU units for your Serverless SQL Database.
CPUMax uint32 `json:"cpu_max"`
// CPUCurrent: the current number of CPU units allocated to your Serverless SQL Database.
CPUCurrent uint32 `json:"cpu_current"`
// Started: whether your Serverless SQL Database is running or not.
Started bool `json:"started"`
// EngineMajorVersion: the major version of the underlying database engine.
EngineMajorVersion uint32 `json:"engine_major_version"`
}
// CreateDatabaseRequest: create database request.
type CreateDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: the ID of your Scaleway project.
ProjectID string `json:"project_id"`
// Name: the name of the Serverless SQL Database to be created.
Name string `json:"name"`
// CPUMin: the minimum number of CPU units for your Serverless SQL Database.
CPUMin uint32 `json:"cpu_min"`
// CPUMax: the maximum number of CPU units for your Serverless SQL Database.
CPUMax uint32 `json:"cpu_max"`
// FromBackupID: the ID of the backup to create the database from.
FromBackupID *string `json:"from_backup_id,omitempty"`
}
// DeleteDatabaseRequest: delete database request.
type DeleteDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseID: UUID of the Serverless SQL Database.
DatabaseID string `json:"-"`
}
// ExportDatabaseBackupRequest: export database backup request.
type ExportDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackupID: UUID of the Serverless SQL Database backup.
BackupID string `json:"-"`
}
// GetDatabaseBackupRequest: get database backup request.
type GetDatabaseBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BackupID: UUID of the Serverless SQL Database backup.
BackupID string `json:"-"`
}
// GetDatabaseRequest: get database request.
type GetDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseID: UUID of the Serverless SQL DB database.
DatabaseID string `json:"-"`
}
// ListDatabaseBackupsRequest: list database backups request.
type ListDatabaseBackupsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrganizationID: filter by the UUID of the Scaleway organization.
OrganizationID *string `json:"-"`
// ProjectID: filter by the UUID of the Scaleway project.
ProjectID *string `json:"-"`
// DatabaseID: filter by the UUID of the Serverless SQL Database.
DatabaseID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size.
PageSize *uint32 `json:"-"`
// OrderBy: sorting criteria. One of `created_at_asc`, `created_at_desc`.
// Default value: created_at_desc
OrderBy ListDatabaseBackupsRequestOrderBy `json:"-"`
}
// ListDatabaseBackupsResponse: list database backups response.
type ListDatabaseBackupsResponse struct {
// Backups: list of the backups.
Backups []*DatabaseBackup `json:"backups"`
// TotalCount: length of the backups list.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabaseBackupsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabaseBackupsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDatabaseBackupsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Backups = append(r.Backups, results.Backups...)
r.TotalCount += uint64(len(results.Backups))
return uint64(len(results.Backups)), nil
}
// ListDatabasesRequest: list databases request.
type ListDatabasesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrganizationID: filter by the UUID of the Scaleway organization.
OrganizationID *string `json:"-"`
// ProjectID: UUID of the Scaleway project.
ProjectID string `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: page size.
PageSize *uint32 `json:"-"`
// Name: filter by the name of the database.
Name *string `json:"-"`
// OrderBy: sorting criteria. One of `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc`.
// Default value: created_at_asc
OrderBy ListDatabasesRequestOrderBy `json:"-"`
}
// ListDatabasesResponse: list databases response.
type ListDatabasesResponse struct {
// Databases: list of the databases.
Databases []*Database `json:"databases"`
// TotalCount: total count of Serverless SQL Databases.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDatabasesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Databases = append(r.Databases, results.Databases...)
r.TotalCount += uint64(len(results.Databases))
return uint64(len(results.Databases)), nil
}
// RestoreDatabaseFromBackupRequest: restore database from backup request.
type RestoreDatabaseFromBackupRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseID: UUID of the Serverless SQL Database.
DatabaseID string `json:"-"`
// BackupID: UUID of the Serverless SQL Database backup to restore.
BackupID string `json:"backup_id"`
}
// UpdateDatabaseRequest: update database request.
type UpdateDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DatabaseID: UUID of the Serverless SQL Database.
DatabaseID string `json:"-"`
// CPUMin: the minimum number of CPU units for your Serverless SQL Database.
CPUMin *uint32 `json:"cpu_min,omitempty"`
// CPUMax: the maximum number of CPU units for your Serverless SQL Database.
CPUMax *uint32 `json:"cpu_max,omitempty"`
}
// This API allows you to manage your Serverless SQL Databases.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar}
}
// CreateDatabase: You must provide the following parameters: `organization_id`, `project_id`, `name`, `cpu_min`, `cpu_max`. You can also provide `from_backup_id` to create a database from a backup.
func (s *API) CreateDatabase(req *CreateDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDatabase: Retrieve information about your Serverless SQL Database. You must provide the `database_id` parameter.
func (s *API) GetDatabase(req *GetDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseID) == "" {
return nil, errors.New("field DatabaseID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases/" + fmt.Sprint(req.DatabaseID) + "",
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabase: Deletes a database. You must provide the `database_id` parameter. All data stored in the database will be permanently deleted.
func (s *API) DeleteDatabase(req *DeleteDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseID) == "" {
return nil, errors.New("field DatabaseID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases/" + fmt.Sprint(req.DatabaseID) + "",
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDatabases: List all Serverless SQL Databases for a given Scaleway Organization or Scaleway Project. By default, the databases returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field. For the `name` parameter, the value you include will be checked against the whole name string to see if it includes the string you put in the parameter.
func (s *API) ListDatabases(req *ListDatabasesRequest, opts ...scw.RequestOption) (*ListDatabasesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases",
Query: query,
}
var resp ListDatabasesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDatabase: Update CPU limits of your Serverless SQL Database. You must provide the `database_id` parameter.
func (s *API) UpdateDatabase(req *UpdateDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseID) == "" {
return nil, errors.New("field DatabaseID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases/" + fmt.Sprint(req.DatabaseID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestoreDatabaseFromBackup: Restore a database from a backup. You must provide the `backup_id` parameter.
func (s *API) RestoreDatabaseFromBackup(req *RestoreDatabaseFromBackupRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DatabaseID) == "" {
return nil, errors.New("field DatabaseID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/databases/" + fmt.Sprint(req.DatabaseID) + "/restore",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDatabaseBackup: Retrieve information about your Serverless SQL Database backup. You must provide the `backup_id` parameter.
func (s *API) GetDatabaseBackup(req *GetDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackupID) == "" {
return nil, errors.New("field BackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.BackupID) + "",
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDatabaseBackups: List all Serverless SQL Database backups for a given Scaleway Project or Database. By default, the backups returned in the list are ordered by creation date in descending order, though this can be modified via the order_by field.
func (s *API) ListDatabaseBackups(req *ListDatabaseBackupsRequest, opts ...scw.RequestOption) (*ListDatabaseBackupsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "database_id", req.DatabaseID)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/backups",
Query: query,
}
var resp ListDatabaseBackupsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ExportDatabaseBackup: Export a database backup providing a download link once the export process is completed. You must provide the `backup_id` parameter.
func (s *API) ExportDatabaseBackup(req *ExportDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BackupID) == "" {
return nil, errors.New("field BackupID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/serverless-sqldb/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/backups/" + fmt.Sprint(req.BackupID) + "/export",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseBackup
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
serverless_sqldb_utils.go 0000664 0000000 0000000 00000006101 14747113137 0035064 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/v1alpha1 package serverless_sqldb //nolint:revive
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 15 * time.Minute
)
// WaitForDatabaseRequest is used by WaitForDatabase method.
type WaitForDatabaseRequest struct {
DatabaseID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDatabase waits for the database to be in a "terminal state" before returning.
// This function can be used to wait for a database to be ready for example.
func (s *API) WaitForDatabase(req *WaitForDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DatabaseStatus]struct{}{
DatabaseStatusReady: {},
DatabaseStatusError: {},
DatabaseStatusLocked: {},
}
database, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetDatabase(&GetDatabaseRequest{
DatabaseID: req.DatabaseID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for database failed")
}
return database.(*Database), nil
}
// WaitForDatabaseBackupRequest is used by WaitForDatabase method.
type WaitForDatabaseBackupRequest struct {
BackupID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDatabaseBackup waits for the backup to be in a "terminal state" before returning.
// This function can be used to wait for a backup to be ready for example.
func (s *API) WaitForDatabaseBackup(req *WaitForDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DatabaseBackupStatus]struct{}{
DatabaseBackupStatusReady: {},
DatabaseBackupStatusError: {},
DatabaseBackupStatusLocked: {},
}
backup, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetDatabaseBackup(&GetDatabaseBackupRequest{
BackupID: req.BackupID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Status]
return res, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for database backup failed")
}
return backup.(*DatabaseBackup), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0031651 5 ustar 00root root 0000000 0000000 sweepers.go 0000664 0000000 0000000 00000002153 14747113137 0033757 0 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/serverless_sqldb/v1alpha1/sweepers package sweepers
import (
"fmt"
sdbSDK "github.com/scaleway/scaleway-sdk-go/api/serverless_sqldb/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepDatabase(scwClient *scw.Client, region scw.Region) error {
sdbAPI := sdbSDK.NewAPI(scwClient)
logger.Warningf("sweeper: destroying the serverless sql database in (%s)", region)
listServerlessSQLDBDatabases, err := sdbAPI.ListDatabases(
&sdbSDK.ListDatabasesRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing database in (%s) in sweeper: %s", region, err)
}
for _, database := range listServerlessSQLDBDatabases.Databases {
_, err := sdbAPI.DeleteDatabase(&sdbSDK.DeleteDatabaseRequest{
DatabaseID: database.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting database in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&sdbSDK.API{}).Regions() {
err := SweepDatabase(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/std/ 0000775 0000000 0000000 00000000000 14747113137 0023607 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/std/std_sdk.go 0000664 0000000 0000000 00000003200 14747113137 0025564 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package std provides methods and message types of the std API.
package std
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type LanguageCode string
const (
LanguageCodeUnknownLanguageCode = LanguageCode("unknown_language_code")
LanguageCodeEnUS = LanguageCode("en_US")
LanguageCodeFrFR = LanguageCode("fr_FR")
LanguageCodeDeDE = LanguageCode("de_DE")
)
func (enum LanguageCode) String() string {
if enum == "" {
// return default value if empty
return "unknown_language_code"
}
return string(enum)
}
func (enum LanguageCode) Values() []LanguageCode {
return []LanguageCode{
"unknown_language_code",
"en_US",
"fr_FR",
"de_DE",
}
}
func (enum LanguageCode) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *LanguageCode) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = LanguageCode(LanguageCode(tmp).String())
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/ 0000775 0000000 0000000 00000000000 14747113137 0023602 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0025217 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0027054 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000001704 14747113137 0031242 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
temSDK "github.com/scaleway/scaleway-sdk-go/api/tem/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepDomain(scwClient *scw.Client, region scw.Region, skippedDomain string) error {
temAPI := temSDK.NewAPI(scwClient)
logger.Warningf("sweeper: revoking the tem domains in (%s)", region)
listDomains, err := temAPI.ListDomains(&temSDK.ListDomainsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing domains in (%s) in sweeper: %s", region, err)
}
for _, ns := range listDomains.Domains {
if ns.Name == skippedDomain {
logger.Debugf("sweeper: skipping deletion of domain %s", ns.Name)
continue
}
_, err := temAPI.RevokeDomain(&temSDK.RevokeDomainRequest{
DomainID: ns.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error revoking domain in sweeper: %s", err)
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/v1alpha1/tem_sdk.go 0000664 0000000 0000000 00000231412 14747113137 0027177 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package tem provides methods and message types of the tem v1alpha1 API.
package tem
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type BlocklistType string
const (
// If unspecified, the type of blocklist is unknown by default.
BlocklistTypeUnknownType = BlocklistType("unknown_type")
// The recipient's mailbox is full and cannot receive any new email.
BlocklistTypeMailboxFull = BlocklistType("mailbox_full")
// The recipient's mailbox does not exist.
BlocklistTypeMailboxNotFound = BlocklistType("mailbox_not_found")
)
func (enum BlocklistType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum BlocklistType) Values() []BlocklistType {
return []BlocklistType{
"unknown_type",
"mailbox_full",
"mailbox_not_found",
}
}
func (enum BlocklistType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *BlocklistType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = BlocklistType(BlocklistType(tmp).String())
return nil
}
type DomainLastStatusAutoconfigStateReason string
const (
// If not specified, the auto-configuration state is unknown by default.
DomainLastStatusAutoconfigStateReasonUnknownReason = DomainLastStatusAutoconfigStateReason("unknown_reason")
// The token doesn't have the necessary permissions to manage the domain's DNS records.
DomainLastStatusAutoconfigStateReasonPermissionDenied = DomainLastStatusAutoconfigStateReason("permission_denied")
// The domain does not exist or isn't manageable by the token.
DomainLastStatusAutoconfigStateReasonDomainNotFound = DomainLastStatusAutoconfigStateReason("domain_not_found")
)
func (enum DomainLastStatusAutoconfigStateReason) String() string {
if enum == "" {
// return default value if empty
return "unknown_reason"
}
return string(enum)
}
func (enum DomainLastStatusAutoconfigStateReason) Values() []DomainLastStatusAutoconfigStateReason {
return []DomainLastStatusAutoconfigStateReason{
"unknown_reason",
"permission_denied",
"domain_not_found",
}
}
func (enum DomainLastStatusAutoconfigStateReason) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainLastStatusAutoconfigStateReason) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainLastStatusAutoconfigStateReason(DomainLastStatusAutoconfigStateReason(tmp).String())
return nil
}
type DomainLastStatusRecordStatus string
const (
// If unspecified, the status of the domain's record is unknown by default.
DomainLastStatusRecordStatusUnknownRecordStatus = DomainLastStatusRecordStatus("unknown_record_status")
// The record is valid.
DomainLastStatusRecordStatusValid = DomainLastStatusRecordStatus("valid")
// The record is invalid.
DomainLastStatusRecordStatusInvalid = DomainLastStatusRecordStatus("invalid")
// The record was not found.
DomainLastStatusRecordStatusNotFound = DomainLastStatusRecordStatus("not_found")
)
func (enum DomainLastStatusRecordStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_record_status"
}
return string(enum)
}
func (enum DomainLastStatusRecordStatus) Values() []DomainLastStatusRecordStatus {
return []DomainLastStatusRecordStatus{
"unknown_record_status",
"valid",
"invalid",
"not_found",
}
}
func (enum DomainLastStatusRecordStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainLastStatusRecordStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainLastStatusRecordStatus(DomainLastStatusRecordStatus(tmp).String())
return nil
}
type DomainReputationStatus string
const (
// If unspecified, the status of the domain's reputation is unknown by default.
DomainReputationStatusUnknownStatus = DomainReputationStatus("unknown_status")
// The domain has an excellent reputation.
DomainReputationStatusExcellent = DomainReputationStatus("excellent")
// The domain has a good reputation.
DomainReputationStatusGood = DomainReputationStatus("good")
// The domain has an average reputation.
DomainReputationStatusAverage = DomainReputationStatus("average")
// The domain has a bad reputation.
DomainReputationStatusBad = DomainReputationStatus("bad")
)
func (enum DomainReputationStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DomainReputationStatus) Values() []DomainReputationStatus {
return []DomainReputationStatus{
"unknown_status",
"excellent",
"good",
"average",
"bad",
}
}
func (enum DomainReputationStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainReputationStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainReputationStatus(DomainReputationStatus(tmp).String())
return nil
}
type DomainStatus string
const (
// If unspecified, the status of the domain is unknown by default.
DomainStatusUnknown = DomainStatus("unknown")
// The domain is checked.
DomainStatusChecked = DomainStatus("checked")
// The domain is unchecked.
DomainStatusUnchecked = DomainStatus("unchecked")
// The domain is invalid.
DomainStatusInvalid = DomainStatus("invalid")
// The domain is locked.
DomainStatusLocked = DomainStatus("locked")
// The domain is revoked.
DomainStatusRevoked = DomainStatus("revoked")
// The domain is pending, waiting to be checked.
DomainStatusPending = DomainStatus("pending")
// The domain is in process of auto-configuration of the domain's DNS zone.
DomainStatusAutoconfiguring = DomainStatus("autoconfiguring")
)
func (enum DomainStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DomainStatus) Values() []DomainStatus {
return []DomainStatus{
"unknown",
"checked",
"unchecked",
"invalid",
"locked",
"revoked",
"pending",
"autoconfiguring",
}
}
func (enum DomainStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DomainStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DomainStatus(DomainStatus(tmp).String())
return nil
}
type EmailFlag string
const (
// If unspecified, the flag type is unknown by default.
EmailFlagUnknownFlag = EmailFlag("unknown_flag")
// Refers to a non critical error received while sending the email(s). Soft bounced emails are retried.
EmailFlagSoftBounce = EmailFlag("soft_bounce")
// Refers to a critical error that happened while sending the email(s).
EmailFlagHardBounce = EmailFlag("hard_bounce")
// Refers to an email considered as spam.
EmailFlagSpam = EmailFlag("spam")
// Refers to an undelivered email because the recipient mailbox is full.
EmailFlagMailboxFull = EmailFlag("mailbox_full")
// Refers to an undelivered email because the recipient mailbox does not exist.
EmailFlagMailboxNotFound = EmailFlag("mailbox_not_found")
// Refers to an email slightly delayed by the recipient to ensure that Scaleway is not sending spam.
EmailFlagGreylisted = EmailFlag("greylisted")
// Refers to an email with a `send-before` tag to indicate the maximum time limit for the email to be sent.
EmailFlagSendBeforeExpiration = EmailFlag("send_before_expiration")
// Refers to an email blocked by a blocklist.
EmailFlagBlocklisted = EmailFlag("blocklisted")
)
func (enum EmailFlag) String() string {
if enum == "" {
// return default value if empty
return "unknown_flag"
}
return string(enum)
}
func (enum EmailFlag) Values() []EmailFlag {
return []EmailFlag{
"unknown_flag",
"soft_bounce",
"hard_bounce",
"spam",
"mailbox_full",
"mailbox_not_found",
"greylisted",
"send_before_expiration",
"blocklisted",
}
}
func (enum EmailFlag) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EmailFlag) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EmailFlag(EmailFlag(tmp).String())
return nil
}
type EmailRcptType string
const (
// If unspecified, the recipient type is unknown by default.
EmailRcptTypeUnknownRcptType = EmailRcptType("unknown_rcpt_type")
// Primary recipient.
EmailRcptTypeTo = EmailRcptType("to")
// Carbon copy recipient.
EmailRcptTypeCc = EmailRcptType("cc")
// Blind carbon copy recipient.
EmailRcptTypeBcc = EmailRcptType("bcc")
)
func (enum EmailRcptType) String() string {
if enum == "" {
// return default value if empty
return "unknown_rcpt_type"
}
return string(enum)
}
func (enum EmailRcptType) Values() []EmailRcptType {
return []EmailRcptType{
"unknown_rcpt_type",
"to",
"cc",
"bcc",
}
}
func (enum EmailRcptType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EmailRcptType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EmailRcptType(EmailRcptType(tmp).String())
return nil
}
type EmailStatus string
const (
// If unspecified, the status of the email is unknown by default.
EmailStatusUnknown = EmailStatus("unknown")
// The email is new.
EmailStatusNew = EmailStatus("new")
// The email is in the process of being sent.
EmailStatusSending = EmailStatus("sending")
// The email was sent.
EmailStatusSent = EmailStatus("sent")
// The sending of the email failed.
EmailStatusFailed = EmailStatus("failed")
// The sending of the email was canceled.
EmailStatusCanceled = EmailStatus("canceled")
)
func (enum EmailStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum EmailStatus) Values() []EmailStatus {
return []EmailStatus{
"unknown",
"new",
"sending",
"sent",
"failed",
"canceled",
}
}
func (enum EmailStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EmailStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EmailStatus(EmailStatus(tmp).String())
return nil
}
type ListBlocklistsRequestOrderBy string
const (
// Order by creation date (descending chronological order).
ListBlocklistsRequestOrderByCreatedAtDesc = ListBlocklistsRequestOrderBy("created_at_desc")
// Order by creation date (ascending chronological order).
ListBlocklistsRequestOrderByCreatedAtAsc = ListBlocklistsRequestOrderBy("created_at_asc")
// Order by blocklist ends date (descending chronological order).
ListBlocklistsRequestOrderByEndsAtDesc = ListBlocklistsRequestOrderBy("ends_at_desc")
// Order by blocklist ends date (ascending chronological order).
ListBlocklistsRequestOrderByEndsAtAsc = ListBlocklistsRequestOrderBy("ends_at_asc")
)
func (enum ListBlocklistsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListBlocklistsRequestOrderBy) Values() []ListBlocklistsRequestOrderBy {
return []ListBlocklistsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"ends_at_desc",
"ends_at_asc",
}
}
func (enum ListBlocklistsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListBlocklistsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListBlocklistsRequestOrderBy(ListBlocklistsRequestOrderBy(tmp).String())
return nil
}
type ListEmailsRequestOrderBy string
const (
// Order by creation date (descending chronological order).
ListEmailsRequestOrderByCreatedAtDesc = ListEmailsRequestOrderBy("created_at_desc")
// Order by creation date (ascending chronological order).
ListEmailsRequestOrderByCreatedAtAsc = ListEmailsRequestOrderBy("created_at_asc")
// Order by last update date (descending chronological order).
ListEmailsRequestOrderByUpdatedAtDesc = ListEmailsRequestOrderBy("updated_at_desc")
// Order by last update date (ascending chronological order).
ListEmailsRequestOrderByUpdatedAtAsc = ListEmailsRequestOrderBy("updated_at_asc")
// Order by status (descending alphabetical order).
ListEmailsRequestOrderByStatusDesc = ListEmailsRequestOrderBy("status_desc")
// Order by status (ascending alphabetical order).
ListEmailsRequestOrderByStatusAsc = ListEmailsRequestOrderBy("status_asc")
// Order by mail_from (descending alphabetical order).
ListEmailsRequestOrderByMailFromDesc = ListEmailsRequestOrderBy("mail_from_desc")
// Order by mail_from (ascending alphabetical order).
ListEmailsRequestOrderByMailFromAsc = ListEmailsRequestOrderBy("mail_from_asc")
// Order by mail recipient (descending alphabetical order).
ListEmailsRequestOrderByMailRcptDesc = ListEmailsRequestOrderBy("mail_rcpt_desc")
// Order by mail recipient (ascending alphabetical order).
ListEmailsRequestOrderByMailRcptAsc = ListEmailsRequestOrderBy("mail_rcpt_asc")
// Order by subject (descending alphabetical order).
ListEmailsRequestOrderBySubjectDesc = ListEmailsRequestOrderBy("subject_desc")
// Order by subject (ascending alphabetical order).
ListEmailsRequestOrderBySubjectAsc = ListEmailsRequestOrderBy("subject_asc")
)
func (enum ListEmailsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListEmailsRequestOrderBy) Values() []ListEmailsRequestOrderBy {
return []ListEmailsRequestOrderBy{
"created_at_desc",
"created_at_asc",
"updated_at_desc",
"updated_at_asc",
"status_desc",
"status_asc",
"mail_from_desc",
"mail_from_asc",
"mail_rcpt_desc",
"mail_rcpt_asc",
"subject_desc",
"subject_asc",
}
}
func (enum ListEmailsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListEmailsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListEmailsRequestOrderBy(ListEmailsRequestOrderBy(tmp).String())
return nil
}
type ListWebhookEventsRequestOrderBy string
const (
ListWebhookEventsRequestOrderByCreatedAtDesc = ListWebhookEventsRequestOrderBy("created_at_desc")
ListWebhookEventsRequestOrderByCreatedAtAsc = ListWebhookEventsRequestOrderBy("created_at_asc")
)
func (enum ListWebhookEventsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListWebhookEventsRequestOrderBy) Values() []ListWebhookEventsRequestOrderBy {
return []ListWebhookEventsRequestOrderBy{
"created_at_desc",
"created_at_asc",
}
}
func (enum ListWebhookEventsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListWebhookEventsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListWebhookEventsRequestOrderBy(ListWebhookEventsRequestOrderBy(tmp).String())
return nil
}
type ListWebhooksRequestOrderBy string
const (
ListWebhooksRequestOrderByCreatedAtDesc = ListWebhooksRequestOrderBy("created_at_desc")
ListWebhooksRequestOrderByCreatedAtAsc = ListWebhooksRequestOrderBy("created_at_asc")
)
func (enum ListWebhooksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_desc"
}
return string(enum)
}
func (enum ListWebhooksRequestOrderBy) Values() []ListWebhooksRequestOrderBy {
return []ListWebhooksRequestOrderBy{
"created_at_desc",
"created_at_asc",
}
}
func (enum ListWebhooksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListWebhooksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListWebhooksRequestOrderBy(ListWebhooksRequestOrderBy(tmp).String())
return nil
}
type ProjectSettingsPeriodicReportFrequency string
const (
// If unspecified, the frequency is unknown by default.
ProjectSettingsPeriodicReportFrequencyUnknownFrequency = ProjectSettingsPeriodicReportFrequency("unknown_frequency")
// The periodic report is sent once a month.
ProjectSettingsPeriodicReportFrequencyMonthly = ProjectSettingsPeriodicReportFrequency("monthly")
// The periodic report is sent once a week.
ProjectSettingsPeriodicReportFrequencyWeekly = ProjectSettingsPeriodicReportFrequency("weekly")
// The periodic report is sent once a day.
ProjectSettingsPeriodicReportFrequencyDaily = ProjectSettingsPeriodicReportFrequency("daily")
)
func (enum ProjectSettingsPeriodicReportFrequency) String() string {
if enum == "" {
// return default value if empty
return "unknown_frequency"
}
return string(enum)
}
func (enum ProjectSettingsPeriodicReportFrequency) Values() []ProjectSettingsPeriodicReportFrequency {
return []ProjectSettingsPeriodicReportFrequency{
"unknown_frequency",
"monthly",
"weekly",
"daily",
}
}
func (enum ProjectSettingsPeriodicReportFrequency) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ProjectSettingsPeriodicReportFrequency) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ProjectSettingsPeriodicReportFrequency(ProjectSettingsPeriodicReportFrequency(tmp).String())
return nil
}
type WebhookEventStatus string
const (
// If unspecified, the status of the Webhook event is unknown by default.
WebhookEventStatusUnknownStatus = WebhookEventStatus("unknown_status")
// The Webhook event is being sent.
WebhookEventStatusSending = WebhookEventStatus("sending")
// The Webhook event was sent.
WebhookEventStatusSent = WebhookEventStatus("sent")
// The Webhook event cannot be sent after multiple retries.
WebhookEventStatusFailed = WebhookEventStatus("failed")
)
func (enum WebhookEventStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum WebhookEventStatus) Values() []WebhookEventStatus {
return []WebhookEventStatus{
"unknown_status",
"sending",
"sent",
"failed",
}
}
func (enum WebhookEventStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *WebhookEventStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = WebhookEventStatus(WebhookEventStatus(tmp).String())
return nil
}
type WebhookEventType string
const (
// If unspecified, the type of the Webhook Event is unknown by default.
WebhookEventTypeUnknownType = WebhookEventType("unknown_type")
// The email was received and is in preparation to be sent to the recipient servers.
WebhookEventTypeEmailQueued = WebhookEventType("email_queued")
// The email was sent but hard-bounced by the recipient server.
WebhookEventTypeEmailDropped = WebhookEventType("email_dropped")
// The email was sent but soft-bounced by the recipient server. In this case, the sending of the email will be automatically retried.
WebhookEventTypeEmailDeferred = WebhookEventType("email_deferred")
// The email was successfully sent.
WebhookEventTypeEmailDelivered = WebhookEventType("email_delivered")
// The email resource was identified as spam by Scaleway or by the recipient server.
WebhookEventTypeEmailSpam = WebhookEventType("email_spam")
// The email hard-bounced with a "mailbox not found" error.
WebhookEventTypeEmailMailboxNotFound = WebhookEventType("email_mailbox_not_found")
// The email was blocked before it was sent, as the recipient matches a blocklist.
WebhookEventTypeEmailBlocklisted = WebhookEventType("email_blocklisted")
// A new blocklist is created.
WebhookEventTypeBlocklistCreated = WebhookEventType("blocklist_created")
)
func (enum WebhookEventType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum WebhookEventType) Values() []WebhookEventType {
return []WebhookEventType{
"unknown_type",
"email_queued",
"email_dropped",
"email_deferred",
"email_delivered",
"email_spam",
"email_mailbox_not_found",
"email_blocklisted",
"blocklist_created",
}
}
func (enum WebhookEventType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *WebhookEventType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = WebhookEventType(WebhookEventType(tmp).String())
return nil
}
// DomainRecordsDMARC: domain records dmarc.
type DomainRecordsDMARC struct {
// Name: name of the DMARC TXT record.
Name string `json:"name"`
// Value: value of the DMARC TXT record.
Value string `json:"value"`
}
// EmailTry: email try.
type EmailTry struct {
// Rank: rank number of this attempt to send the email.
Rank uint32 `json:"rank"`
// TriedAt: date of the attempt to send the email.
TriedAt *time.Time `json:"tried_at"`
// Code: the SMTP status code received after the attempt. 0 if the attempt did not reach an SMTP server.
Code int32 `json:"code"`
// Message: the SMTP message received. If the attempt did not reach an SMTP server, the message returned explains what happened.
Message string `json:"message"`
}
// DomainRecords: domain records.
type DomainRecords struct {
// Dmarc: dMARC TXT record specification.
Dmarc *DomainRecordsDMARC `json:"dmarc"`
}
// DomainReputation: domain reputation.
type DomainReputation struct {
// Status: status of your domain's reputation.
// Default value: unknown_status
Status DomainReputationStatus `json:"status"`
// Score: a range from 0 to 100 that determines your domain's reputation score. A score of `0` means a bad domain reputation and a score of `100` means an excellent domain reputation.
Score uint32 `json:"score"`
// ScoredAt: time and date the score was calculated.
ScoredAt *time.Time `json:"scored_at"`
// PreviousScore: the previously-calculated domain's reputation score.
PreviousScore *uint32 `json:"previous_score"`
// PreviousScoredAt: time and date the previous reputation score was calculated.
PreviousScoredAt *time.Time `json:"previous_scored_at"`
}
// DomainStatistics: domain statistics.
type DomainStatistics struct {
TotalCount uint32 `json:"total_count"`
SentCount uint32 `json:"sent_count"`
FailedCount uint32 `json:"failed_count"`
CanceledCount uint32 `json:"canceled_count"`
}
// Blocklist: blocklist.
type Blocklist struct {
// ID: ID of the blocklist.
ID string `json:"id"`
// DomainID: domain ID linked to the blocklist.
DomainID string `json:"domain_id"`
// CreatedAt: date and time of the blocklist creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of the blocklist's last update.
UpdatedAt *time.Time `json:"updated_at"`
// EndsAt: date and time when the blocklist ends. Empty if the blocklist has no end.
EndsAt *time.Time `json:"ends_at"`
// Email: email blocked by the blocklist.
Email string `json:"email"`
// Type: type of block for this email.
// Default value: unknown_type
Type BlocklistType `json:"type"`
// Reason: reason to block this email.
Reason string `json:"reason"`
// Custom: true if this blocklist was created manually. False for an automatic Transactional Email blocklist.
Custom bool `json:"custom"`
}
// CreateEmailRequestAddress: create email request address.
type CreateEmailRequestAddress struct {
// Email: email address.
Email string `json:"email"`
// Name: (Optional) Name displayed.
Name *string `json:"name"`
}
// CreateEmailRequestAttachment: create email request attachment.
type CreateEmailRequestAttachment struct {
// Name: filename of the attachment.
Name string `json:"name"`
// Type: mIME type of the attachment.
Type string `json:"type"`
// Content: content of the attachment encoded in base64.
Content []byte `json:"content"`
}
// CreateEmailRequestHeader: create email request header.
type CreateEmailRequestHeader struct {
// Key: email header key.
Key string `json:"key"`
// Value: email header value.
Value string `json:"value"`
}
// Email: email.
type Email struct {
// ID: technical ID of the email.
ID string `json:"id"`
// MessageID: message ID of the email.
MessageID string `json:"message_id"`
// ProjectID: ID of the Project to which the email belongs.
ProjectID string `json:"project_id"`
// MailFrom: email address of the sender.
MailFrom string `json:"mail_from"`
// Deprecated: RcptTo: email address of the recipient.
RcptTo *string `json:"rcpt_to,omitempty"`
// MailRcpt: email address of the recipient.
MailRcpt string `json:"mail_rcpt"`
// RcptType: type of recipient.
// Default value: unknown_rcpt_type
RcptType EmailRcptType `json:"rcpt_type"`
// Subject: subject of the email.
Subject string `json:"subject"`
// CreatedAt: creation date of the email object.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: last update of the email object.
UpdatedAt *time.Time `json:"updated_at"`
// Status: status of the email.
// Default value: unknown
Status EmailStatus `json:"status"`
// StatusDetails: additional status information.
StatusDetails *string `json:"status_details"`
// TryCount: number of attempts to send the email.
TryCount uint32 `json:"try_count"`
// LastTries: information about the last three attempts to send the email.
LastTries []*EmailTry `json:"last_tries"`
// Flags: flags categorize emails. They allow you to obtain more information about recurring errors, for example.
Flags []EmailFlag `json:"flags"`
}
// DomainLastStatusAutoconfigState: domain last status autoconfig state.
type DomainLastStatusAutoconfigState struct {
// Enabled: enable or disable the auto-configuration of domain DNS records.
Enabled bool `json:"enabled"`
// Autoconfigurable: whether the domain can be auto-configured or not.
Autoconfigurable bool `json:"autoconfigurable"`
// Reason: the reason that the domain cannot be auto-configurable.
// Default value: unknown_reason
Reason *DomainLastStatusAutoconfigStateReason `json:"reason"`
}
// DomainLastStatusDkimRecord: domain last status dkim record.
type DomainLastStatusDkimRecord struct {
// Status: status of the DKIM record's configuration.
// Default value: unknown_record_status
Status DomainLastStatusRecordStatus `json:"status"`
// LastValidAt: time and date the DKIM record was last valid.
LastValidAt *time.Time `json:"last_valid_at"`
// Error: an error text displays in case the record is not valid.
Error *string `json:"error"`
}
// DomainLastStatusDmarcRecord: domain last status dmarc record.
type DomainLastStatusDmarcRecord struct {
// Status: status of the DMARC record's configuration.
// Default value: unknown_record_status
Status DomainLastStatusRecordStatus `json:"status"`
// LastValidAt: time and date the DMARC record was last valid.
LastValidAt *time.Time `json:"last_valid_at"`
// Error: an error text displays in case the record is not valid.
Error *string `json:"error"`
}
// DomainLastStatusSpfRecord: domain last status spf record.
type DomainLastStatusSpfRecord struct {
// Status: status of the SPF record's configuration.
// Default value: unknown_record_status
Status DomainLastStatusRecordStatus `json:"status"`
// LastValidAt: time and date the SPF record was last valid.
LastValidAt *time.Time `json:"last_valid_at"`
// Error: an error text displays in case the record is not valid.
Error *string `json:"error"`
}
// Domain: domain.
type Domain struct {
// ID: ID of the domain.
ID string `json:"id"`
// OrganizationID: ID of the domain's Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the domain's Project.
ProjectID string `json:"project_id"`
// Name: domain name (example.com).
Name string `json:"name"`
// Status: status of the domain.
// Default value: unknown
Status DomainStatus `json:"status"`
// CreatedAt: date and time of domain creation.
CreatedAt *time.Time `json:"created_at"`
// NextCheckAt: date and time of the next scheduled check.
NextCheckAt *time.Time `json:"next_check_at"`
// LastValidAt: date and time the domain was last valid.
LastValidAt *time.Time `json:"last_valid_at"`
// RevokedAt: date and time of the domain's deletion.
RevokedAt *time.Time `json:"revoked_at"`
// Deprecated: LastError: error message returned if the last check failed.
LastError *string `json:"last_error,omitempty"`
// SpfConfig: snippet of the SPF record to register in the DNS zone.
SpfConfig string `json:"spf_config"`
// DkimConfig: dKIM public key to record in the DNS zone.
DkimConfig string `json:"dkim_config"`
// Statistics: domain's statistics.
Statistics *DomainStatistics `json:"statistics"`
// Reputation: the domain's reputation is available when your domain is checked and has sent enough emails.
Reputation *DomainReputation `json:"reputation"`
// Records: list of records to configure to validate a domain.
Records *DomainRecords `json:"records"`
// Autoconfig: status of auto-configuration for the domain's DNS zone.
Autoconfig bool `json:"autoconfig"`
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"region"`
}
// WebhookEvent: webhook event.
type WebhookEvent struct {
// ID: ID of the Webhook Event.
ID string `json:"id"`
// WebhookID: ID of the Webhook that triggers the Event.
WebhookID string `json:"webhook_id"`
// OrganizationID: ID of the Webhook Event Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the Webhook Event Project.
ProjectID string `json:"project_id"`
// DomainID: ID of the webhook event domain.
DomainID string `json:"domain_id"`
// Type: type of the Webhook Event.
// Default value: unknown_type
Type WebhookEventType `json:"type"`
// Status: status of the Webhook Event.
// Default value: unknown_status
Status WebhookEventStatus `json:"status"`
// Data: data sent to the Webhook destination.
Data string `json:"data"`
// CreatedAt: date and time of the Webhook Event creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last Webhook Event updates.
UpdatedAt *time.Time `json:"updated_at"`
// EmailID: optional Email ID if the event is triggered by an Email resource.
EmailID *string `json:"email_id"`
}
// Webhook: webhook.
type Webhook struct {
// ID: ID of the Webhook.
ID string `json:"id"`
// DomainID: ID of the Domain to watch for triggering events.
DomainID string `json:"domain_id"`
// OrganizationID: ID of the Webhook Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the Webhook Project.
ProjectID string `json:"project_id"`
// Name: name of the Webhook.
Name string `json:"name"`
// EventTypes: list of event types that will trigger a Webhook Event.
EventTypes []WebhookEventType `json:"event_types"`
// SnsArn: scaleway SNS ARN topic to push the events to.
SnsArn string `json:"sns_arn"`
// CreatedAt: date and time of the Webhook creation.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date and time of last Webhook updates.
UpdatedAt *time.Time `json:"updated_at"`
}
// ProjectSettingsPeriodicReport: project settings periodic report.
type ProjectSettingsPeriodicReport struct {
// Enabled: enable or disable periodic report notifications.
Enabled bool `json:"enabled"`
// Frequency: at which frequency you receive periodic report notifications.
// Default value: unknown_frequency
Frequency ProjectSettingsPeriodicReportFrequency `json:"frequency"`
// SendingHour: at which hour you receive periodic report notifications.
SendingHour uint32 `json:"sending_hour"`
// SendingDay: on which day you receive periodic report notifications (1-7 weekly, 1-28 monthly).
SendingDay uint32 `json:"sending_day"`
}
// UpdateProjectSettingsRequestUpdatePeriodicReport: update project settings request update periodic report.
type UpdateProjectSettingsRequestUpdatePeriodicReport struct {
// Enabled: (Optional) Enable or disable periodic report notifications.
Enabled *bool `json:"enabled"`
// Frequency: (Optional) Frequency at which you receive periodic report notifications.
// Default value: unknown_frequency
Frequency *ProjectSettingsPeriodicReportFrequency `json:"frequency"`
// SendingHour: (Optional) Hour at which you receive periodic report notifications.
SendingHour *uint32 `json:"sending_hour"`
// SendingDay: (Optional) On which day you receive periodic report notifications (1-7 weekly, 1-28 monthly).
SendingDay *uint32 `json:"sending_day"`
}
// BulkCreateBlocklistsRequest: bulk create blocklists request.
type BulkCreateBlocklistsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: domain ID linked to the blocklist.
DomainID string `json:"domain_id"`
// Emails: email blocked by the blocklist.
Emails []string `json:"emails"`
// Type: type of blocklist.
// Default value: unknown_type
Type BlocklistType `json:"type"`
// Reason: reason to block the email.
Reason *string `json:"reason,omitempty"`
}
// BulkCreateBlocklistsResponse: bulk create blocklists response.
type BulkCreateBlocklistsResponse struct {
// Blocklists: list of blocklist created.
Blocklists []*Blocklist `json:"blocklists"`
}
// CancelEmailRequest: cancel email request.
type CancelEmailRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EmailID: ID of the email to cancel.
EmailID string `json:"-"`
}
// CheckDomainRequest: check domain request.
type CheckDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the domain to check.
DomainID string `json:"-"`
}
// CreateDomainRequest: create domain request.
type CreateDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the project to which the domain belongs.
ProjectID string `json:"project_id"`
// DomainName: fully qualified domain dame.
DomainName string `json:"domain_name"`
// AcceptTos: accept Scaleway's Terms of Service.
AcceptTos bool `json:"accept_tos"`
// Autoconfig: activate auto-configuration of the domain's DNS zone.
Autoconfig bool `json:"autoconfig"`
}
// CreateEmailRequest: create email request.
type CreateEmailRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// From: sender information. Must be from a checked domain declared in the Project.
From *CreateEmailRequestAddress `json:"from"`
// To: an array of the primary recipient's information.
To []*CreateEmailRequestAddress `json:"to"`
// Cc: an array of the carbon copy recipient's information.
Cc []*CreateEmailRequestAddress `json:"cc"`
// Bcc: an array of the blind carbon copy recipient's information.
Bcc []*CreateEmailRequestAddress `json:"bcc"`
// Subject: subject of the email.
Subject string `json:"subject"`
// Text: text content.
Text string `json:"text"`
// HTML: HTML content.
HTML string `json:"html"`
// ProjectID: ID of the Project in which to create the email.
ProjectID string `json:"project_id"`
// Attachments: array of attachments.
Attachments []*CreateEmailRequestAttachment `json:"attachments"`
// SendBefore: maximum date to deliver the email.
SendBefore *time.Time `json:"send_before,omitempty"`
// AdditionalHeaders: array of additional headers as key-value.
AdditionalHeaders []*CreateEmailRequestHeader `json:"additional_headers"`
}
// CreateEmailResponse: create email response.
type CreateEmailResponse struct {
// Emails: single page of emails matching the requested criteria.
Emails []*Email `json:"emails"`
}
// CreateWebhookRequest: create webhook request.
type CreateWebhookRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the Domain to watch for triggering events.
DomainID string `json:"domain_id"`
// ProjectID: ID of the project to which the Webhook belongs.
ProjectID string `json:"project_id"`
// Name: name of the Webhook.
Name string `json:"name"`
// EventTypes: list of event types that will trigger an event.
EventTypes []WebhookEventType `json:"event_types"`
// SnsArn: scaleway SNS ARN topic to push the events to.
SnsArn string `json:"sns_arn"`
}
// DeleteBlocklistRequest: delete blocklist request.
type DeleteBlocklistRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// BlocklistID: ID of the blocklist to delete.
BlocklistID string `json:"-"`
}
// DeleteWebhookRequest: delete webhook request.
type DeleteWebhookRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// WebhookID: ID of the Webhook to delete.
WebhookID string `json:"-"`
}
// DomainLastStatus: domain last status.
type DomainLastStatus struct {
// DomainID: the ID of the domain.
DomainID string `json:"domain_id"`
// DomainName: the domain name (example.com).
DomainName string `json:"domain_name"`
// SpfRecord: the SPF record verification data.
SpfRecord *DomainLastStatusSpfRecord `json:"spf_record"`
// DkimRecord: the DKIM record verification data.
DkimRecord *DomainLastStatusDkimRecord `json:"dkim_record"`
// DmarcRecord: the DMARC record verification data.
DmarcRecord *DomainLastStatusDmarcRecord `json:"dmarc_record"`
// AutoconfigState: the verification state of domain auto-configuration.
AutoconfigState *DomainLastStatusAutoconfigState `json:"autoconfig_state"`
}
// GetDomainLastStatusRequest: get domain last status request.
type GetDomainLastStatusRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the domain to delete.
DomainID string `json:"-"`
}
// GetDomainRequest: get domain request.
type GetDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the domain.
DomainID string `json:"-"`
}
// GetEmailRequest: get email request.
type GetEmailRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// EmailID: ID of the email to retrieve.
EmailID string `json:"-"`
}
// GetProjectSettingsRequest: get project settings request.
type GetProjectSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the project.
ProjectID string `json:"-"`
}
// GetStatisticsRequest: get statistics request.
type GetStatisticsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: (Optional) Number of emails for this Project.
ProjectID *string `json:"-"`
// DomainID: (Optional) Number of emails sent from this domain (must be coherent with the `project_id` and the `organization_id`).
DomainID *string `json:"-"`
// Since: (Optional) Number of emails created after this date.
Since *time.Time `json:"-"`
// Until: (Optional) Number of emails created before this date.
Until *time.Time `json:"-"`
// MailFrom: (Optional) Number of emails sent with this sender's email address.
MailFrom *string `json:"-"`
}
// GetWebhookRequest: get webhook request.
type GetWebhookRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// WebhookID: ID of the Webhook to check.
WebhookID string `json:"-"`
}
// ListBlocklistsRequest: list blocklists request.
type ListBlocklistsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: (Optional) List blocklist corresponding to specific criteria.
// Default value: created_at_desc
OrderBy ListBlocklistsRequestOrderBy `json:"-"`
// Page: (Optional) Requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: (Optional) Requested page size. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// DomainID: (Optional) Filter by a domain ID.
DomainID string `json:"-"`
// Email: (Optional) Filter by an email address.
Email *string `json:"-"`
// Type: (Optional) Filter by a blocklist type.
// Default value: unknown_type
Type *BlocklistType `json:"-"`
// Custom: (Optional) Filter by custom blocklist (true) or automatic Transactional Email blocklist (false).
Custom *bool `json:"-"`
}
// ListBlocklistsResponse: list blocklists response.
type ListBlocklistsResponse struct {
// TotalCount: number of blocklists matching the requested criteria.
TotalCount uint64 `json:"total_count"`
// Blocklists: single page of blocklists matching the requested criteria.
Blocklists []*Blocklist `json:"blocklists"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListBlocklistsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListBlocklistsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListBlocklistsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Blocklists = append(r.Blocklists, results.Blocklists...)
r.TotalCount += uint64(len(results.Blocklists))
return uint64(len(results.Blocklists)), nil
}
// ListDomainsRequest: list domains request.
type ListDomainsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: requested page size. Value must be between 1 and 1000.
PageSize *uint32 `json:"-"`
// ProjectID: (Optional) ID of the Project in which to list the domains.
ProjectID *string `json:"-"`
// Status: (Optional) List domains under specific statuses.
Status []DomainStatus `json:"-"`
// OrganizationID: (Optional) ID of the Organization in which to list the domains.
OrganizationID *string `json:"-"`
// Name: (Optional) Names of the domains to list.
Name *string `json:"-"`
}
// ListDomainsResponse: list domains response.
type ListDomainsResponse struct {
// TotalCount: number of domains that match the request (without pagination).
TotalCount uint32 `json:"total_count"`
// Domains: single page of domains matching the requested criteria.
Domains []*Domain `json:"domains"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDomainsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDomainsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Domains = append(r.Domains, results.Domains...)
r.TotalCount += uint32(len(results.Domains))
return uint32(len(results.Domains)), nil
}
// ListEmailsRequest: list emails request.
type ListEmailsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// ProjectID: (Optional) ID of the Project in which to list the emails.
ProjectID *string `json:"-"`
// DomainID: (Optional) ID of the domain for which to list the emails.
DomainID *string `json:"-"`
// MessageID: (Optional) ID of the message for which to list the emails.
MessageID *string `json:"-"`
// Since: (Optional) List emails created after this date.
Since *time.Time `json:"-"`
// Until: (Optional) List emails created before this date.
Until *time.Time `json:"-"`
// MailFrom: (Optional) List emails sent with this sender's email address.
MailFrom *string `json:"-"`
// Deprecated: MailTo: list emails sent to this recipient's email address.
MailTo *string `json:"-"`
// MailRcpt: (Optional) List emails sent to this recipient's email address.
MailRcpt *string `json:"-"`
// Statuses: (Optional) List emails with any of these statuses.
Statuses []EmailStatus `json:"-"`
// Subject: (Optional) List emails with this subject.
Subject *string `json:"-"`
// Search: (Optional) List emails by searching to all fields.
Search *string `json:"-"`
// OrderBy: (Optional) List emails corresponding to specific criteria.
// Default value: created_at_desc
OrderBy ListEmailsRequestOrderBy `json:"-"`
// Flags: (Optional) List emails containing only specific flags.
Flags []EmailFlag `json:"-"`
}
// ListEmailsResponse: list emails response.
type ListEmailsResponse struct {
// TotalCount: number of emails matching the requested criteria.
TotalCount uint32 `json:"total_count"`
// Emails: single page of emails matching the requested criteria.
Emails []*Email `json:"emails"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListEmailsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListEmailsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListEmailsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Emails = append(r.Emails, results.Emails...)
r.TotalCount += uint32(len(results.Emails))
return uint32(len(results.Emails)), nil
}
// ListWebhookEventsRequest: list webhook events request.
type ListWebhookEventsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// WebhookID: ID of the Webhook linked to the events.
WebhookID string `json:"-"`
// OrderBy: (Optional) List Webhook events corresponding to specific criteria.
// Default value: created_at_desc
OrderBy ListWebhookEventsRequestOrderBy `json:"-"`
// Page: requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: requested page size. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// EmailID: ID of the email linked to the events.
EmailID *string `json:"-"`
// EventTypes: list of event types linked to the events.
EventTypes []WebhookEventType `json:"-"`
// Statuses: list of event statuses.
Statuses []WebhookEventStatus `json:"-"`
// ProjectID: ID of the webhook Project.
ProjectID *string `json:"-"`
// OrganizationID: ID of the webhook Organization.
OrganizationID *string `json:"-"`
// DomainID: ID of the domain to watch for triggering events.
DomainID *string `json:"-"`
}
// ListWebhookEventsResponse: list webhook events response.
type ListWebhookEventsResponse struct {
// TotalCount: number of Webhook events matching the requested criteria.
TotalCount uint64 `json:"total_count"`
// WebhookEvents: single page of Webhook events matching the requested criteria.
WebhookEvents []*WebhookEvent `json:"webhook_events"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListWebhookEventsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListWebhookEventsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListWebhookEventsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.WebhookEvents = append(r.WebhookEvents, results.WebhookEvents...)
r.TotalCount += uint64(len(results.WebhookEvents))
return uint64(len(results.WebhookEvents)), nil
}
// ListWebhooksRequest: list webhooks request.
type ListWebhooksRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: (Optional) List Webhooks corresponding to specific criteria.
// Default value: created_at_desc
OrderBy ListWebhooksRequestOrderBy `json:"-"`
// Page: (Optional) Requested page number. Value must be greater or equal to 1.
Page *int32 `json:"-"`
// PageSize: (Optional) Requested page size. Value must be between 1 and 100.
PageSize *uint32 `json:"-"`
// ProjectID: (Optional) ID of the Project for which to list the Webhooks.
ProjectID *string `json:"-"`
// OrganizationID: (Optional) ID of the Organization for which to list the Webhooks.
OrganizationID *string `json:"-"`
// DomainID: (Optional) ID of the Domain for which to list the Webhooks.
DomainID *string `json:"-"`
}
// ListWebhooksResponse: list webhooks response.
type ListWebhooksResponse struct {
// TotalCount: number of Webhooks matching the requested criteria.
TotalCount uint64 `json:"total_count"`
// Webhooks: single page of Webhooks matching the requested criteria.
Webhooks []*Webhook `json:"webhooks"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListWebhooksResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListWebhooksResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListWebhooksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Webhooks = append(r.Webhooks, results.Webhooks...)
r.TotalCount += uint64(len(results.Webhooks))
return uint64(len(results.Webhooks)), nil
}
// ProjectSettings: project settings.
type ProjectSettings struct {
// PeriodicReport: information about your periodic report.
PeriodicReport *ProjectSettingsPeriodicReport `json:"periodic_report"`
}
// RevokeDomainRequest: revoke domain request.
type RevokeDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the domain to delete.
DomainID string `json:"-"`
}
// Statistics: statistics.
type Statistics struct {
// TotalCount: total number of emails matching the requested criteria.
TotalCount uint32 `json:"total_count"`
// NewCount: number of emails still in the `new` transient state. This means emails received from the API but not yet processed.
NewCount uint32 `json:"new_count"`
// SendingCount: number of emails still in the `sending` transient state. This means emails received from the API but not yet in their final status.
SendingCount uint32 `json:"sending_count"`
// SentCount: number of emails in the final `sent` state. This means emails that have been delivered to the target mail system.
SentCount uint32 `json:"sent_count"`
// FailedCount: number of emails in the final `failed` state. This means emails that have been refused by the target mail system with a final error status.
FailedCount uint32 `json:"failed_count"`
// CanceledCount: number of emails in the final `canceled` state. This means emails that have been canceled upon request.
CanceledCount uint32 `json:"canceled_count"`
}
// UpdateDomainRequest: update domain request.
type UpdateDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// DomainID: ID of the domain to update.
DomainID string `json:"-"`
// Autoconfig: (Optional) If set to true, activate auto-configuration of the domain's DNS zone.
Autoconfig *bool `json:"autoconfig,omitempty"`
}
// UpdateProjectSettingsRequest: update project settings request.
type UpdateProjectSettingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// ProjectID: ID of the project.
ProjectID string `json:"-"`
// PeriodicReport: periodic report update details - all fields are optional.
PeriodicReport *UpdateProjectSettingsRequestUpdatePeriodicReport `json:"periodic_report,omitempty"`
}
// UpdateWebhookRequest: update webhook request.
type UpdateWebhookRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// WebhookID: ID of the Webhook to update.
WebhookID string `json:"-"`
// Name: name of the Webhook to update.
Name *string `json:"name,omitempty"`
// EventTypes: list of event types to update.
EventTypes []WebhookEventType `json:"event_types"`
// SnsArn: scaleway SNS ARN topic to update.
SnsArn *string `json:"sns_arn,omitempty"`
}
// This API allows you to manage your Transactional Email services.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar}
}
// CreateEmail: You must specify the `region`, the sender and the recipient's information and the `project_id` to send an email from a checked domain. The subject of the email must contain at least 6 characters.
func (s *API) CreateEmail(req *CreateEmailRequest, opts ...scw.RequestOption) (*CreateEmailResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/emails",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CreateEmailResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetEmail: Retrieve information about a specific email using the `email_id` and `region` parameters.
func (s *API) GetEmail(req *GetEmailRequest, opts ...scw.RequestOption) (*Email, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EmailID) == "" {
return nil, errors.New("field EmailID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/emails/" + fmt.Sprint(req.EmailID) + "",
}
var resp Email
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListEmails: Retrieve the list of emails sent from a specific domain or for a specific Project or Organization. You must specify the `region`.
func (s *API) ListEmails(req *ListEmailsRequest, opts ...scw.RequestOption) (*ListEmailsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "domain_id", req.DomainID)
parameter.AddToQuery(query, "message_id", req.MessageID)
parameter.AddToQuery(query, "since", req.Since)
parameter.AddToQuery(query, "until", req.Until)
parameter.AddToQuery(query, "mail_from", req.MailFrom)
parameter.AddToQuery(query, "mail_to", req.MailTo)
parameter.AddToQuery(query, "mail_rcpt", req.MailRcpt)
parameter.AddToQuery(query, "statuses", req.Statuses)
parameter.AddToQuery(query, "subject", req.Subject)
parameter.AddToQuery(query, "search", req.Search)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "flags", req.Flags)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/emails",
Query: query,
}
var resp ListEmailsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetStatistics: Get information on your emails' statuses.
func (s *API) GetStatistics(req *GetStatisticsRequest, opts ...scw.RequestOption) (*Statistics, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "domain_id", req.DomainID)
parameter.AddToQuery(query, "since", req.Since)
parameter.AddToQuery(query, "until", req.Until)
parameter.AddToQuery(query, "mail_from", req.MailFrom)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/statistics",
Query: query,
}
var resp Statistics
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CancelEmail: You can cancel the sending of an email if it has not been sent yet. You must specify the `region` and the `email_id` of the email you want to cancel.
func (s *API) CancelEmail(req *CancelEmailRequest, opts ...scw.RequestOption) (*Email, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.EmailID) == "" {
return nil, errors.New("field EmailID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/emails/" + fmt.Sprint(req.EmailID) + "/cancel",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Email
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDomain: You must specify the `region`, `project_id` and `domain_name` to register a domain in a specific Project.
func (s *API) CreateDomain(req *CreateDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomain: Retrieve information about a specific domain using the `region` and `domain_id` parameters. Monitor your domain's reputation and improve **average** and **bad** reputation statuses, using your domain's **Email activity** tab on the [Scaleway console](https://console.scaleway.com/transactional-email/domains) to get a more detailed report. Check out our [dedicated documentation](https://www.scaleway.com/en/docs/managed-services/transactional-email/reference-content/understanding-tem-reputation-score/) to improve your domain's reputation.
func (s *API) GetDomain(req *GetDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDomains: Retrieve domains in a specific Project or in a specific Organization using the `region` parameter.
func (s *API) ListDomains(req *ListDomainsRequest, opts ...scw.RequestOption) (*ListDomainsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "name", req.Name)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains",
Query: query,
}
var resp ListDomainsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RevokeDomain: You must specify the domain you want to delete by the `region` and `domain_id`. Deleting a domain is permanent and cannot be undone.
func (s *API) RevokeDomain(req *RevokeDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "/revoke",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckDomain: Perform an immediate DNS check of a domain using the `region` and `domain_id` parameters.
func (s *API) CheckDomain(req *CheckDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "/check",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomainLastStatus: Display SPF and DKIM records status and potential errors, including the found records to make debugging easier.
func (s *API) GetDomainLastStatus(req *GetDomainLastStatusRequest, opts ...scw.RequestOption) (*DomainLastStatus, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "/verification",
}
var resp DomainLastStatus
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDomain: Update a domain auto-configuration.
func (s *API) UpdateDomain(req *UpdateDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.DomainID) == "" {
return nil, errors.New("field DomainID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.DomainID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Domain
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateWebhook: Create a new Webhook triggered by a list of event types and pushed to a Scaleway SNS ARN.
func (s *API) CreateWebhook(req *CreateWebhookRequest, opts ...scw.RequestOption) (*Webhook, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Webhook
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListWebhooks: Retrieve Webhooks in a specific Project or in a specific Organization using the `region` parameter.
func (s *API) ListWebhooks(req *ListWebhooksRequest, opts ...scw.RequestOption) (*ListWebhooksResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "domain_id", req.DomainID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks",
Query: query,
}
var resp ListWebhooksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetWebhook: Retrieve information about a specific Webhook using the `webhook_id` and `region` parameters.
func (s *API) GetWebhook(req *GetWebhookRequest, opts ...scw.RequestOption) (*Webhook, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.WebhookID) == "" {
return nil, errors.New("field WebhookID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks/" + fmt.Sprint(req.WebhookID) + "",
}
var resp Webhook
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateWebhook: Update a Webhook events type, SNS ARN or name.
func (s *API) UpdateWebhook(req *UpdateWebhookRequest, opts ...scw.RequestOption) (*Webhook, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.WebhookID) == "" {
return nil, errors.New("field WebhookID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks/" + fmt.Sprint(req.WebhookID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Webhook
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteWebhook: You must specify the Webhook you want to delete by the `region` and `webhook_id`. Deleting a Webhook is permanent and cannot be undone.
func (s *API) DeleteWebhook(req *DeleteWebhookRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.WebhookID) == "" {
return errors.New("field WebhookID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks/" + fmt.Sprint(req.WebhookID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListWebhookEvents: Retrieve the list of Webhook events triggered from a specific Webhook or for a specific Project or Organization. You must specify the `region`.
func (s *API) ListWebhookEvents(req *ListWebhookEventsRequest, opts ...scw.RequestOption) (*ListWebhookEventsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "email_id", req.EmailID)
parameter.AddToQuery(query, "event_types", req.EventTypes)
parameter.AddToQuery(query, "statuses", req.Statuses)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "domain_id", req.DomainID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.WebhookID) == "" {
return nil, errors.New("field WebhookID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/webhooks/" + fmt.Sprint(req.WebhookID) + "/events",
Query: query,
}
var resp ListWebhookEventsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetProjectSettings: Retrieve the project settings including periodic reports.
func (s *API) GetProjectSettings(req *GetProjectSettingsRequest, opts ...scw.RequestOption) (*ProjectSettings, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/project/" + fmt.Sprint(req.ProjectID) + "/settings",
}
var resp ProjectSettings
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateProjectSettings: Update the project settings including periodic reports.
func (s *API) UpdateProjectSettings(req *UpdateProjectSettingsRequest, opts ...scw.RequestOption) (*ProjectSettings, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.ProjectID) == "" {
return nil, errors.New("field ProjectID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/project/" + fmt.Sprint(req.ProjectID) + "/settings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ProjectSettings
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListBlocklists: Retrieve the list of blocklists.
func (s *API) ListBlocklists(req *ListBlocklistsRequest, opts ...scw.RequestOption) (*ListBlocklistsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "domain_id", req.DomainID)
parameter.AddToQuery(query, "email", req.Email)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "custom", req.Custom)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/blocklists",
Query: query,
}
var resp ListBlocklistsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// BulkCreateBlocklists: Create multiple blocklists in a specific Project or Organization using the `region` parameter.
func (s *API) BulkCreateBlocklists(req *BulkCreateBlocklistsRequest, opts ...scw.RequestOption) (*BulkCreateBlocklistsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/blocklists",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp BulkCreateBlocklistsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteBlocklist: You must specify the blocklist you want to delete by the `region` and `blocklist_id`.
func (s *API) DeleteBlocklist(req *DeleteBlocklistRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.BlocklistID) == "" {
return errors.New("field BlocklistID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/transactional-email/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/blocklists/" + fmt.Sprint(req.BlocklistID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/tem/v1alpha1/tem_utils.go 0000664 0000000 0000000 00000003617 14747113137 0027562 0 ustar 00root root 0000000 0000000 package tem
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 15 * time.Second
SMTPHost = "smtp.tem.scw.cloud"
SMTPPortUnsecure = 25
SMTPPort = 587
SMTPPortAlternative = 2587
SMTPSPort = 465
SMTPSPortAlternative = 2465
MXBlackhole = "blackhole.scw-tem.cloud."
)
// WaitForDomainRequest is used by WaitForDomain method
type WaitForDomainRequest struct {
DomainID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDomain wait for the domain to be in a "terminal state" before returning.
// This function can be used to wait for a domain to be checked for example.
func (s *API) WaitForDomain(req *WaitForDomainRequest, opts ...scw.RequestOption) (*Domain, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DomainStatus]struct{}{
DomainStatusChecked: {},
DomainStatusUnchecked: {},
DomainStatusInvalid: {},
DomainStatusLocked: {},
DomainStatusRevoked: {},
DomainStatusUnknown: {},
}
domain, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
img, err := s.GetDomain(&GetDomainRequest{
Region: req.Region,
DomainID: req.DomainID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[img.Status]
return img, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for domain failed")
}
return domain.(*Domain), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/test/ 0000775 0000000 0000000 00000000000 14747113137 0023774 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/test/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024322 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/test/v1/test_sdk.go 0000664 0000000 0000000 00000033160 14747113137 0026474 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package test provides methods and message types of the test v1 API.
package test
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type EyeColors string
const (
// Unknown color.
EyeColorsUnknown = EyeColors("unknown")
// Rare and striking shade that typically features a golden or yellowish-brown hue.
EyeColorsAmber = EyeColors("amber")
// Relatively rare, with the highest frequency found in eastern Europe.
EyeColorsBlue = EyeColors("blue")
// Most common eye color in the world caused by a high concentration of melanin in the iris.
EyeColorsBrown = EyeColors("brown")
// Relatively rare color which can change depending on the lighting conditions.
EyeColorsGray = EyeColors("gray")
// Rare and unique color characterized by a combination of yellow, brown, and blue pigments.
EyeColorsGreen = EyeColors("green")
// Brownish-yellow or greenish-brown with a hint of gold.
EyeColorsHazel = EyeColors("hazel")
// Rare mutation that results in a reddish-pink hue.
EyeColorsRed = EyeColors("red")
// Rare and striking shade that appears to be a mix of blue and purple.
EyeColorsViolet = EyeColors("violet")
)
func (enum EyeColors) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum EyeColors) Values() []EyeColors {
return []EyeColors{
"unknown",
"amber",
"blue",
"brown",
"gray",
"green",
"hazel",
"red",
"violet",
}
}
func (enum EyeColors) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *EyeColors) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = EyeColors(EyeColors(tmp).String())
return nil
}
type HumanStatus string
const (
// Unknown status.
HumanStatusUnknown = HumanStatus("unknown")
// The human is stopped.
HumanStatusStopped = HumanStatus("stopped")
// The human is running.
HumanStatusRunning = HumanStatus("running")
)
func (enum HumanStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum HumanStatus) Values() []HumanStatus {
return []HumanStatus{
"unknown",
"stopped",
"running",
}
}
func (enum HumanStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HumanStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HumanStatus(HumanStatus(tmp).String())
return nil
}
type ListHumansRequestOrderBy string
const (
// Ascending creation date.
ListHumansRequestOrderByCreatedAtAsc = ListHumansRequestOrderBy("created_at_asc")
// Descending creation date.
ListHumansRequestOrderByCreatedAtDesc = ListHumansRequestOrderBy("created_at_desc")
// Ascending update date.
ListHumansRequestOrderByUpdatedAtAsc = ListHumansRequestOrderBy("updated_at_asc")
// Descending update date.
ListHumansRequestOrderByUpdatedAtDesc = ListHumansRequestOrderBy("updated_at_desc")
// Ascending height.
ListHumansRequestOrderByHeightAsc = ListHumansRequestOrderBy("height_asc")
// Descending height.
ListHumansRequestOrderByHeightDesc = ListHumansRequestOrderBy("height_desc")
)
func (enum ListHumansRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListHumansRequestOrderBy) Values() []ListHumansRequestOrderBy {
return []ListHumansRequestOrderBy{
"created_at_asc",
"created_at_desc",
"updated_at_asc",
"updated_at_desc",
"height_asc",
"height_desc",
}
}
func (enum ListHumansRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListHumansRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListHumansRequestOrderBy(ListHumansRequestOrderBy(tmp).String())
return nil
}
// Human: human.
type Human struct {
ID string `json:"id"`
OrganizationID string `json:"organization_id"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
Height float64 `json:"height"`
ShoeSize float32 `json:"shoe_size"`
AltitudeInMeter int32 `json:"altitude_in_meter"`
AltitudeInMillimeter int64 `json:"altitude_in_millimeter"`
FingersCount uint32 `json:"fingers_count"`
HairCount uint64 `json:"hair_count"`
IsHappy bool `json:"is_happy"`
// EyesColor: default value: unknown
EyesColor EyeColors `json:"eyes_color"`
// Status: default value: unknown
Status HumanStatus `json:"status"`
Name string `json:"name"`
ProjectID string `json:"project_id"`
}
// CreateHumanRequest: create human request.
type CreateHumanRequest struct {
Height float64 `json:"height"`
ShoeSize float32 `json:"shoe_size"`
AltitudeInMeter int32 `json:"altitude_in_meter"`
AltitudeInMillimeter int64 `json:"altitude_in_millimeter"`
FingersCount uint32 `json:"fingers_count"`
HairCount uint64 `json:"hair_count"`
IsHappy bool `json:"is_happy"`
// EyesColor: default value: unknown
EyesColor EyeColors `json:"eyes_color"`
// Deprecated
// Precisely one of ProjectID, OrganizationID must be set.
OrganizationID *string `json:"organization_id,omitempty"`
Name string `json:"name"`
// Precisely one of ProjectID, OrganizationID must be set.
ProjectID *string `json:"project_id,omitempty"`
}
// DeleteHumanRequest: delete human request.
type DeleteHumanRequest struct {
// HumanID: UUID of the human you want to delete.
HumanID string `json:"-"`
}
// GetHumanRequest: get human request.
type GetHumanRequest struct {
// HumanID: UUID of the human you want to get.
HumanID string `json:"-"`
}
// ListHumansRequest: list humans request.
type ListHumansRequest struct {
Page *int32 `json:"-"`
PageSize *uint32 `json:"-"`
// OrderBy: default value: created_at_asc
OrderBy ListHumansRequestOrderBy `json:"-"`
OrganizationID *string `json:"-"`
ProjectID *string `json:"-"`
}
// ListHumansResponse: list humans response.
type ListHumansResponse struct {
TotalCount uint32 `json:"total_count"`
Humans []*Human `json:"humans"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListHumansResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListHumansResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListHumansResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Humans = append(r.Humans, results.Humans...)
r.TotalCount += uint32(len(results.Humans))
return uint32(len(results.Humans)), nil
}
// RegisterRequest: register request.
type RegisterRequest struct {
Username string `json:"username"`
}
// RegisterResponse: register response.
type RegisterResponse struct {
SecretKey string `json:"secret_key"`
AccessKey string `json:"access_key"`
}
// RunHumanRequest: run human request.
type RunHumanRequest struct {
// HumanID: UUID of the human you want to make run.
HumanID string `json:"-"`
}
// SmokeHumanRequest: smoke human request.
type SmokeHumanRequest struct {
// Deprecated: HumanID: UUID of the human you want to make smoking.
HumanID string `json:"-"`
}
// UpdateHumanRequest: update human request.
type UpdateHumanRequest struct {
// HumanID: UUID of the human you want to update.
HumanID string `json:"-"`
// Height: height of the human in meters.
Height *float64 `json:"height,omitempty"`
ShoeSize *float32 `json:"shoe_size,omitempty"`
AltitudeInMeter *int32 `json:"altitude_in_meter,omitempty"`
AltitudeInMillimeter *int64 `json:"altitude_in_millimeter,omitempty"`
FingersCount *uint32 `json:"fingers_count,omitempty"`
HairCount *uint64 `json:"hair_count,omitempty"`
IsHappy *bool `json:"is_happy,omitempty"`
// EyesColor: default value: unknown
EyesColor EyeColors `json:"eyes_color"`
Name *string `json:"name,omitempty"`
}
// No Auth Service for end-to-end testing.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
// Register: Register a human and return a access-key and a secret-key that must be used in all other commands.
//
// Hint: you can use other test commands by setting the SCW_SECRET_KEY env variable.
func (s *API) Register(req *RegisterRequest, opts ...scw.RequestOption) (*RegisterResponse, error) {
var err error
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/test/v1/register",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp RegisterResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListHumans: List all your humans.
func (s *API) ListHumans(req *ListHumansRequest, opts ...scw.RequestOption) (*ListHumansResponse, error) {
var err error
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/test/v1/humans",
Query: query,
}
var resp ListHumansResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetHuman: Get the human details associated with the given id.
func (s *API) GetHuman(req *GetHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
if fmt.Sprint(req.HumanID) == "" {
return nil, errors.New("field HumanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/test/v1/humans/" + fmt.Sprint(req.HumanID) + "",
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateHuman: Create a new human.
func (s *API) CreateHuman(req *CreateHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
defaultProjectID, exist := s.client.GetDefaultProjectID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.ProjectID = &defaultProjectID
}
defaultOrganizationID, exist := s.client.GetDefaultOrganizationID()
if exist && req.ProjectID == nil && req.OrganizationID == nil {
req.OrganizationID = &defaultOrganizationID
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/test/v1/humans",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHuman: Update the human associated with the given id.
func (s *API) UpdateHuman(req *UpdateHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
if fmt.Sprint(req.HumanID) == "" {
return nil, errors.New("field HumanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/test/v1/humans/" + fmt.Sprint(req.HumanID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteHuman: Delete the human associated with the given id.
func (s *API) DeleteHuman(req *DeleteHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
if fmt.Sprint(req.HumanID) == "" {
return nil, errors.New("field HumanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/test/v1/humans/" + fmt.Sprint(req.HumanID) + "",
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RunHuman: Start a one hour running for the given human.
func (s *API) RunHuman(req *RunHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
if fmt.Sprint(req.HumanID) == "" {
return nil, errors.New("field HumanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/test/v1/humans/" + fmt.Sprint(req.HumanID) + "/run",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// Deprecated: SmokeHuman: Make a human smoke.
func (s *API) SmokeHuman(req *SmokeHumanRequest, opts ...scw.RequestOption) (*Human, error) {
var err error
if fmt.Sprint(req.HumanID) == "" {
return nil, errors.New("field HumanID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/test/v1/humans/" + fmt.Sprint(req.HumanID) + "/smoke",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Human
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpc/ 0000775 0000000 0000000 00000000000 14747113137 0023605 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpc/v2/ 0000775 0000000 0000000 00000000000 14747113137 0024134 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpc/v2/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0025771 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpc/v2/sweepers/sweepers.go 0000664 0000000 0000000 00000005241 14747113137 0030157 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
vpcSDK "github.com/scaleway/scaleway-sdk-go/api/vpc/v2"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepVPC(scwClient *scw.Client, region scw.Region) error {
vpcAPI := vpcSDK.NewAPI(scwClient)
listVPCs, err := vpcAPI.ListVPCs(&vpcSDK.ListVPCsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing secrets in (%s) in sweeper: %s", region, err)
}
for _, v := range listVPCs.Vpcs {
if v.IsDefault {
continue
}
err := vpcAPI.DeleteVPC(&vpcSDK.DeleteVPCRequest{
VpcID: v.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting VPC in sweeper: %s", err)
}
}
return nil
}
func SweepPrivateNetwork(scwClient *scw.Client, region scw.Region) error {
vpcAPI := vpcSDK.NewAPI(scwClient)
logger.Debugf("sweeper: destroying the private network in (%s)", region)
listPNResponse, err := vpcAPI.ListPrivateNetworks(&vpcSDK.ListPrivateNetworksRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing private network in sweeper: %s", err)
}
for _, pn := range listPNResponse.PrivateNetworks {
err := vpcAPI.DeletePrivateNetwork(&vpcSDK.DeletePrivateNetworkRequest{
Region: region,
PrivateNetworkID: pn.ID,
})
if err != nil {
return fmt.Errorf("error deleting private network in sweeper: %s", err)
}
}
return nil
}
func SweepRoute(scwClient *scw.Client, region scw.Region) error {
vpcAPI := vpcSDK.NewAPI(scwClient)
vpcRouteAPI := vpcSDK.NewRoutesWithNexthopAPI(scwClient)
logger.Warningf("sweeper: destroying the route in (%s)", region)
listRoutesResponse, err := vpcRouteAPI.ListRoutesWithNexthop(&vpcSDK.RoutesWithNexthopAPIListRoutesWithNexthopRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing route in sweeper: %s", err)
}
for _, routeWithNexthop := range listRoutesResponse.Routes {
if routeWithNexthop.Route != nil {
err := vpcAPI.DeleteRoute(&vpcSDK.DeleteRouteRequest{
Region: region,
RouteID: routeWithNexthop.Route.ID,
})
if err != nil {
return fmt.Errorf("error deleting route in sweeper: %s", err)
}
} else {
return fmt.Errorf("route is nil in RouteWithNexthop: %v", routeWithNexthop)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&vpcSDK.API{}).Regions() {
err := SweepVPC(scwClient, region)
if err != nil {
return err
}
err = SweepPrivateNetwork(scwClient, region)
if err != nil {
return err
}
err = SweepRoute(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpc/v2/vpc_sdk.go 0000664 0000000 0000000 00000135155 14747113137 0026126 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package vpc provides methods and message types of the vpc v2 API.
package vpc
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type ListPrivateNetworksRequestOrderBy string
const (
ListPrivateNetworksRequestOrderByCreatedAtAsc = ListPrivateNetworksRequestOrderBy("created_at_asc")
ListPrivateNetworksRequestOrderByCreatedAtDesc = ListPrivateNetworksRequestOrderBy("created_at_desc")
ListPrivateNetworksRequestOrderByNameAsc = ListPrivateNetworksRequestOrderBy("name_asc")
ListPrivateNetworksRequestOrderByNameDesc = ListPrivateNetworksRequestOrderBy("name_desc")
)
func (enum ListPrivateNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPrivateNetworksRequestOrderBy) Values() []ListPrivateNetworksRequestOrderBy {
return []ListPrivateNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListPrivateNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPrivateNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPrivateNetworksRequestOrderBy(ListPrivateNetworksRequestOrderBy(tmp).String())
return nil
}
type ListRoutesWithNexthopRequestOrderBy string
const (
ListRoutesWithNexthopRequestOrderByCreatedAtAsc = ListRoutesWithNexthopRequestOrderBy("created_at_asc")
ListRoutesWithNexthopRequestOrderByCreatedAtDesc = ListRoutesWithNexthopRequestOrderBy("created_at_desc")
ListRoutesWithNexthopRequestOrderByDestinationAsc = ListRoutesWithNexthopRequestOrderBy("destination_asc")
ListRoutesWithNexthopRequestOrderByDestinationDesc = ListRoutesWithNexthopRequestOrderBy("destination_desc")
ListRoutesWithNexthopRequestOrderByPrefixLenAsc = ListRoutesWithNexthopRequestOrderBy("prefix_len_asc")
ListRoutesWithNexthopRequestOrderByPrefixLenDesc = ListRoutesWithNexthopRequestOrderBy("prefix_len_desc")
)
func (enum ListRoutesWithNexthopRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListRoutesWithNexthopRequestOrderBy) Values() []ListRoutesWithNexthopRequestOrderBy {
return []ListRoutesWithNexthopRequestOrderBy{
"created_at_asc",
"created_at_desc",
"destination_asc",
"destination_desc",
"prefix_len_asc",
"prefix_len_desc",
}
}
func (enum ListRoutesWithNexthopRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListRoutesWithNexthopRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListRoutesWithNexthopRequestOrderBy(ListRoutesWithNexthopRequestOrderBy(tmp).String())
return nil
}
type ListSubnetsRequestOrderBy string
const (
ListSubnetsRequestOrderByCreatedAtAsc = ListSubnetsRequestOrderBy("created_at_asc")
ListSubnetsRequestOrderByCreatedAtDesc = ListSubnetsRequestOrderBy("created_at_desc")
)
func (enum ListSubnetsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListSubnetsRequestOrderBy) Values() []ListSubnetsRequestOrderBy {
return []ListSubnetsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListSubnetsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListSubnetsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListSubnetsRequestOrderBy(ListSubnetsRequestOrderBy(tmp).String())
return nil
}
type ListVPCsRequestOrderBy string
const (
ListVPCsRequestOrderByCreatedAtAsc = ListVPCsRequestOrderBy("created_at_asc")
ListVPCsRequestOrderByCreatedAtDesc = ListVPCsRequestOrderBy("created_at_desc")
ListVPCsRequestOrderByNameAsc = ListVPCsRequestOrderBy("name_asc")
ListVPCsRequestOrderByNameDesc = ListVPCsRequestOrderBy("name_desc")
)
func (enum ListVPCsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListVPCsRequestOrderBy) Values() []ListVPCsRequestOrderBy {
return []ListVPCsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
}
}
func (enum ListVPCsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListVPCsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListVPCsRequestOrderBy(ListVPCsRequestOrderBy(tmp).String())
return nil
}
type RouteWithNexthopResourceType string
const (
RouteWithNexthopResourceTypeUnknownType = RouteWithNexthopResourceType("unknown_type")
RouteWithNexthopResourceTypeVpcGatewayNetwork = RouteWithNexthopResourceType("vpc_gateway_network")
RouteWithNexthopResourceTypeInstancePrivateNic = RouteWithNexthopResourceType("instance_private_nic")
RouteWithNexthopResourceTypeBaremetalPrivateNic = RouteWithNexthopResourceType("baremetal_private_nic")
)
func (enum RouteWithNexthopResourceType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum RouteWithNexthopResourceType) Values() []RouteWithNexthopResourceType {
return []RouteWithNexthopResourceType{
"unknown_type",
"vpc_gateway_network",
"instance_private_nic",
"baremetal_private_nic",
}
}
func (enum RouteWithNexthopResourceType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *RouteWithNexthopResourceType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = RouteWithNexthopResourceType(RouteWithNexthopResourceType(tmp).String())
return nil
}
// Subnet: subnet.
type Subnet struct {
// ID: ID of the subnet.
ID string `json:"id"`
// CreatedAt: subnet creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: subnet last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Subnet: subnet CIDR.
Subnet scw.IPNet `json:"subnet"`
// ProjectID: scaleway Project the subnet belongs to.
ProjectID string `json:"project_id"`
// PrivateNetworkID: private Network the subnet belongs to.
PrivateNetworkID string `json:"private_network_id"`
// VpcID: vPC the subnet belongs to.
VpcID string `json:"vpc_id"`
}
// PrivateNetwork: private network.
type PrivateNetwork struct {
// ID: private Network ID.
ID string `json:"id"`
// Name: private Network name.
Name string `json:"name"`
// OrganizationID: scaleway Organization the Private Network belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: scaleway Project the Private Network belongs to.
ProjectID string `json:"project_id"`
// Region: region in which the Private Network is available.
Region scw.Region `json:"region"`
// Tags: tags of the Private Network.
Tags []string `json:"tags"`
// CreatedAt: date the Private Network was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the Private Network was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// Subnets: private Network subnets.
Subnets []*Subnet `json:"subnets"`
// VpcID: vPC the Private Network belongs to.
VpcID string `json:"vpc_id"`
// DHCPEnabled: defines whether managed DHCP is enabled for this Private Network.
DHCPEnabled bool `json:"dhcp_enabled"`
}
// Route: route.
type Route struct {
// ID: route ID.
ID string `json:"id"`
// Description: route description.
Description string `json:"description"`
// Tags: tags of the Route.
Tags []string `json:"tags"`
// VpcID: vPC the Route belongs to.
VpcID string `json:"vpc_id"`
// Destination: destination of the Route.
Destination scw.IPNet `json:"destination"`
// NexthopResourceID: ID of the nexthop resource.
NexthopResourceID *string `json:"nexthop_resource_id"`
// NexthopPrivateNetworkID: ID of the nexthop private network.
NexthopPrivateNetworkID *string `json:"nexthop_private_network_id"`
// CreatedAt: date the Route was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the Route was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// IsReadOnly: defines whether the route can be modified or deleted by the user.
IsReadOnly bool `json:"is_read_only"`
// Region: region of the Route.
Region scw.Region `json:"region"`
}
// RouteWithNexthop: route with nexthop.
type RouteWithNexthop struct {
// Route: route.
Route *Route `json:"route"`
// NexthopIP: IP of the route's next hop.
NexthopIP *net.IP `json:"nexthop_ip"`
// NexthopName: name of the route's next hop.
NexthopName *string `json:"nexthop_name"`
// NexthopResourceType: resource type of the route's next hop.
// Default value: unknown_type
NexthopResourceType RouteWithNexthopResourceType `json:"nexthop_resource_type"`
}
// VPC: vpc.
type VPC struct {
// ID: vPC ID.
ID string `json:"id"`
// Name: vPC name.
Name string `json:"name"`
// OrganizationID: scaleway Organization the VPC belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: scaleway Project the VPC belongs to.
ProjectID string `json:"project_id"`
// Region: region of the VPC.
Region scw.Region `json:"region"`
// Tags: tags for the VPC.
Tags []string `json:"tags"`
// IsDefault: defines whether the VPC is the default one for its Project.
IsDefault bool `json:"is_default"`
// CreatedAt: date the VPC was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date the VPC was last modified.
UpdatedAt *time.Time `json:"updated_at"`
// PrivateNetworkCount: number of Private Networks within this VPC.
PrivateNetworkCount uint32 `json:"private_network_count"`
// RoutingEnabled: defines whether the VPC routes traffic between its Private Networks.
RoutingEnabled bool `json:"routing_enabled"`
}
// AddSubnetsRequest: add subnets request.
type AddSubnetsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Subnets: private Network subnets CIDR.
Subnets []scw.IPNet `json:"subnets"`
}
// AddSubnetsResponse: add subnets response.
type AddSubnetsResponse struct {
Subnets []scw.IPNet `json:"subnets"`
}
// CreatePrivateNetworkRequest: create private network request.
type CreatePrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name for the Private Network.
Name string `json:"name"`
// ProjectID: scaleway Project in which to create the Private Network.
ProjectID string `json:"project_id"`
// Tags: tags for the Private Network.
Tags []string `json:"tags"`
// Subnets: private Network subnets CIDR.
Subnets []scw.IPNet `json:"subnets"`
// VpcID: vPC in which to create the Private Network.
VpcID *string `json:"vpc_id,omitempty"`
}
// CreateRouteRequest: create route request.
type CreateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Description: route description.
Description string `json:"description"`
// Tags: tags of the Route.
Tags []string `json:"tags"`
// VpcID: vPC the Route belongs to.
VpcID string `json:"vpc_id"`
// Destination: destination of the Route.
Destination scw.IPNet `json:"destination"`
// NexthopResourceID: ID of the nexthop resource.
NexthopResourceID *string `json:"nexthop_resource_id,omitempty"`
// NexthopPrivateNetworkID: ID of the nexthop private network.
NexthopPrivateNetworkID *string `json:"nexthop_private_network_id,omitempty"`
}
// CreateVPCRequest: create vpc request.
type CreateVPCRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Name: name for the VPC.
Name string `json:"name"`
// ProjectID: scaleway Project in which to create the VPC.
ProjectID string `json:"project_id"`
// Tags: tags for the VPC.
Tags []string `json:"tags"`
// EnableRouting: enable routing between Private Networks in the VPC.
EnableRouting bool `json:"enable_routing"`
}
// DeletePrivateNetworkRequest: delete private network request.
type DeletePrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
}
// DeleteRouteRequest: delete route request.
type DeleteRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// DeleteSubnetsRequest: delete subnets request.
type DeleteSubnetsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Subnets: private Network subnets CIDR.
Subnets []scw.IPNet `json:"subnets"`
}
// DeleteSubnetsResponse: delete subnets response.
type DeleteSubnetsResponse struct {
Subnets []scw.IPNet `json:"subnets"`
}
// DeleteVPCRequest: delete vpc request.
type DeleteVPCRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// VpcID: vPC ID.
VpcID string `json:"-"`
}
// EnableDHCPRequest: enable dhcp request.
type EnableDHCPRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
}
// EnableRoutingRequest: enable routing request.
type EnableRoutingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// VpcID: vPC ID.
VpcID string `json:"-"`
}
// GetPrivateNetworkRequest: get private network request.
type GetPrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
}
// GetRouteRequest: get route request.
type GetRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
}
// GetVPCRequest: get vpc request.
type GetVPCRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// VpcID: vPC ID.
VpcID string `json:"-"`
}
// ListPrivateNetworksRequest: list private networks request.
type ListPrivateNetworksRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of the returned Private Networks.
// Default value: created_at_asc
OrderBy ListPrivateNetworksRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of Private Networks to return per page.
PageSize *uint32 `json:"-"`
// Name: name to filter for. Only Private Networks with names containing this string will be returned.
Name *string `json:"-"`
// Tags: tags to filter for. Only Private Networks with one or more matching tags will be returned.
Tags []string `json:"-"`
// OrganizationID: organization ID to filter for. Only Private Networks belonging to this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for. Only Private Networks belonging to this Project will be returned.
ProjectID *string `json:"-"`
// PrivateNetworkIDs: private Network IDs to filter for. Only Private Networks with one of these IDs will be returned.
PrivateNetworkIDs []string `json:"-"`
// VpcID: vPC ID to filter for. Only Private Networks belonging to this VPC will be returned.
VpcID *string `json:"-"`
// DHCPEnabled: DHCP status to filter for. When true, only Private Networks with managed DHCP enabled will be returned.
DHCPEnabled *bool `json:"-"`
}
// ListPrivateNetworksResponse: list private networks response.
type ListPrivateNetworksResponse struct {
PrivateNetworks []*PrivateNetwork `json:"private_networks"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPrivateNetworksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPrivateNetworksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPrivateNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PrivateNetworks = append(r.PrivateNetworks, results.PrivateNetworks...)
r.TotalCount += uint32(len(results.PrivateNetworks))
return uint32(len(results.PrivateNetworks)), nil
}
// ListRoutesWithNexthopResponse: list routes with nexthop response.
type ListRoutesWithNexthopResponse struct {
// Routes: list of routes.
Routes []*RouteWithNexthop `json:"routes"`
// TotalCount: total number of routes.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListRoutesWithNexthopResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListRoutesWithNexthopResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListRoutesWithNexthopResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Routes = append(r.Routes, results.Routes...)
r.TotalCount += uint64(len(results.Routes))
return uint64(len(results.Routes)), nil
}
// ListSubnetsRequest: list subnets request.
type ListSubnetsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of the returned subnets.
// Default value: created_at_asc
OrderBy ListSubnetsRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of Private Networks to return per page.
PageSize *uint32 `json:"-"`
// OrganizationID: organization ID to filter for. Only subnets belonging to this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for. Only subnets belonging to this Project will be returned.
ProjectID *string `json:"-"`
// SubnetIDs: subnet IDs to filter for. Only subnets matching the specified IDs will be returned.
SubnetIDs []string `json:"-"`
// VpcID: vPC ID to filter for. Only subnets belonging to this VPC will be returned.
VpcID *string `json:"-"`
}
// ListSubnetsResponse: list subnets response.
type ListSubnetsResponse struct {
Subnets []*Subnet `json:"subnets"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListSubnetsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListSubnetsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListSubnetsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Subnets = append(r.Subnets, results.Subnets...)
r.TotalCount += uint32(len(results.Subnets))
return uint32(len(results.Subnets)), nil
}
// ListVPCsRequest: list vp cs request.
type ListVPCsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of the returned VPCs.
// Default value: created_at_asc
OrderBy ListVPCsRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of VPCs to return per page.
PageSize *uint32 `json:"-"`
// Name: name to filter for. Only VPCs with names containing this string will be returned.
Name *string `json:"-"`
// Tags: tags to filter for. Only VPCs with one more more matching tags will be returned.
Tags []string `json:"-"`
// OrganizationID: organization ID to filter for. Only VPCs belonging to this Organization will be returned.
OrganizationID *string `json:"-"`
// ProjectID: project ID to filter for. Only VPCs belonging to this Project will be returned.
ProjectID *string `json:"-"`
// IsDefault: defines whether to filter only for VPCs which are the default one for their Project.
IsDefault *bool `json:"-"`
// RoutingEnabled: defines whether to filter only for VPCs which route traffic between their Private Networks.
RoutingEnabled *bool `json:"-"`
}
// ListVPCsResponse: list vp cs response.
type ListVPCsResponse struct {
Vpcs []*VPC `json:"vpcs"`
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListVPCsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListVPCsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListVPCsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Vpcs = append(r.Vpcs, results.Vpcs...)
r.TotalCount += uint32(len(results.Vpcs))
return uint32(len(results.Vpcs)), nil
}
// RoutesWithNexthopAPIListRoutesWithNexthopRequest: routes with nexthop api list routes with nexthop request.
type RoutesWithNexthopAPIListRoutesWithNexthopRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of the returned routes.
// Default value: created_at_asc
OrderBy ListRoutesWithNexthopRequestOrderBy `json:"-"`
// Page: page number to return, from the paginated results.
Page *int32 `json:"-"`
// PageSize: maximum number of routes to return per page.
PageSize *uint32 `json:"-"`
// VpcID: vPC to filter for. Only routes within this VPC will be returned.
VpcID *string `json:"-"`
// NexthopResourceID: next hop resource ID to filter for. Only routes with a matching next hop resource ID will be returned.
NexthopResourceID *string `json:"-"`
// NexthopPrivateNetworkID: next hop private network ID to filter for. Only routes with a matching next hop private network ID will be returned.
NexthopPrivateNetworkID *string `json:"-"`
// NexthopResourceType: next hop resource type to filter for. Only Routes with a matching next hop resource type will be returned.
// Default value: unknown_type
NexthopResourceType RouteWithNexthopResourceType `json:"-"`
// Contains: only routes whose destination is contained in this subnet will be returned.
Contains *scw.IPNet `json:"-"`
// Tags: tags to filter for, only routes with one or more matching tags will be returned.
Tags []string `json:"-"`
// IsIPv6: only routes with an IPv6 destination will be returned.
IsIPv6 *bool `json:"-"`
}
// SetSubnetsRequest: set subnets request.
type SetSubnetsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Subnets: private Network subnets CIDR.
Subnets []scw.IPNet `json:"subnets"`
}
// SetSubnetsResponse: set subnets response.
type SetSubnetsResponse struct {
Subnets []scw.IPNet `json:"subnets"`
}
// UpdatePrivateNetworkRequest: update private network request.
type UpdatePrivateNetworkRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// PrivateNetworkID: private Network ID.
PrivateNetworkID string `json:"-"`
// Name: name for the Private Network.
Name *string `json:"name,omitempty"`
// Tags: tags for the Private Network.
Tags *[]string `json:"tags,omitempty"`
}
// UpdateRouteRequest: update route request.
type UpdateRouteRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// RouteID: route ID.
RouteID string `json:"-"`
// Description: route description.
Description *string `json:"description,omitempty"`
// Tags: tags of the Route.
Tags *[]string `json:"tags,omitempty"`
// Destination: destination of the Route.
Destination *scw.IPNet `json:"destination,omitempty"`
// NexthopResourceID: ID of the nexthop resource.
NexthopResourceID *string `json:"nexthop_resource_id,omitempty"`
// NexthopPrivateNetworkID: ID of the nexthop private network.
NexthopPrivateNetworkID *string `json:"nexthop_private_network_id,omitempty"`
}
// UpdateVPCRequest: update vpc request.
type UpdateVPCRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// VpcID: vPC ID.
VpcID string `json:"-"`
// Name: name for the VPC.
Name *string `json:"name,omitempty"`
// Tags: tags for the VPC.
Tags *[]string `json:"tags,omitempty"`
}
// This API allows you to manage your Virtual Private Clouds (VPCs) and Private Networks.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListVPCs: List existing VPCs in the specified region.
func (s *API) ListVPCs(req *ListVPCsRequest, opts ...scw.RequestOption) (*ListVPCsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "is_default", req.IsDefault)
parameter.AddToQuery(query, "routing_enabled", req.RoutingEnabled)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs",
Query: query,
}
var resp ListVPCsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateVPC: Create a new VPC in the specified region.
func (s *API) CreateVPC(req *CreateVPCRequest, opts ...scw.RequestOption) (*VPC, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("vpc")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp VPC
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetVPC: Retrieve details of an existing VPC, specified by its VPC ID.
func (s *API) GetVPC(req *GetVPCRequest, opts ...scw.RequestOption) (*VPC, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.VpcID) == "" {
return nil, errors.New("field VpcID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs/" + fmt.Sprint(req.VpcID) + "",
}
var resp VPC
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateVPC: Update parameters including name and tags of the specified VPC.
func (s *API) UpdateVPC(req *UpdateVPCRequest, opts ...scw.RequestOption) (*VPC, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.VpcID) == "" {
return nil, errors.New("field VpcID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs/" + fmt.Sprint(req.VpcID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp VPC
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteVPC: Delete a VPC specified by its VPC ID.
func (s *API) DeleteVPC(req *DeleteVPCRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.VpcID) == "" {
return errors.New("field VpcID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs/" + fmt.Sprint(req.VpcID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPrivateNetworks: List existing Private Networks in the specified region. By default, the Private Networks returned in the list are ordered by creation date in ascending order, though this can be modified via the order_by field.
func (s *API) ListPrivateNetworks(req *ListPrivateNetworksRequest, opts ...scw.RequestOption) (*ListPrivateNetworksResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "private_network_ids", req.PrivateNetworkIDs)
parameter.AddToQuery(query, "vpc_id", req.VpcID)
parameter.AddToQuery(query, "dhcp_enabled", req.DHCPEnabled)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks",
Query: query,
}
var resp ListPrivateNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePrivateNetwork: Create a new Private Network. Once created, you can attach Scaleway resources which are in the same region.
func (s *API) CreatePrivateNetwork(req *CreatePrivateNetworkRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("pn")
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPrivateNetwork: Retrieve information about an existing Private Network, specified by its Private Network ID. Its full details are returned in the response object.
func (s *API) GetPrivateNetwork(req *GetPrivateNetworkRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePrivateNetwork: Update parameters (such as name or tags) of an existing Private Network, specified by its Private Network ID.
func (s *API) UpdatePrivateNetwork(req *UpdatePrivateNetworkRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePrivateNetwork: Delete an existing Private Network. Note that you must first detach all resources from the network, in order to delete it.
func (s *API) DeletePrivateNetwork(req *DeletePrivateNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// EnableDHCP: Enable DHCP managed on an existing Private Network. Note that you will not be able to deactivate it afterwards.
func (s *API) EnableDHCP(req *EnableDHCPRequest, opts ...scw.RequestOption) (*PrivateNetwork, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/enable-dhcp",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PrivateNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableRouting: Enable routing on an existing VPC. Note that you will not be able to deactivate it afterwards.
func (s *API) EnableRouting(req *EnableRoutingRequest, opts ...scw.RequestOption) (*VPC, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.VpcID) == "" {
return nil, errors.New("field VpcID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/vpcs/" + fmt.Sprint(req.VpcID) + "/enable-routing",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp VPC
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListSubnets: List any Private Network's subnets. See ListPrivateNetworks to list a specific Private Network's subnets.
func (s *API) ListSubnets(req *ListSubnetsRequest, opts ...scw.RequestOption) (*ListSubnetsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "subnet_ids", req.SubnetIDs)
parameter.AddToQuery(query, "vpc_id", req.VpcID)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/subnets",
Query: query,
}
var resp ListSubnetsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetSubnets: Set subnets for an existing Private Network. Note that the method is PUT and not PATCH. Any existing subnets will be removed in favor of the new specified set of subnets.
func (s *API) SetSubnets(req *SetSubnetsRequest, opts ...scw.RequestOption) (*SetSubnetsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/subnets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetSubnetsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddSubnets: Add new subnets to an existing Private Network.
func (s *API) AddSubnets(req *AddSubnetsRequest, opts ...scw.RequestOption) (*AddSubnetsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/subnets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddSubnetsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteSubnets: Delete the specified subnets from a Private Network.
func (s *API) DeleteSubnets(req *DeleteSubnetsRequest, opts ...scw.RequestOption) (*DeleteSubnetsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.PrivateNetworkID) == "" {
return nil, errors.New("field PrivateNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/private-networks/" + fmt.Sprint(req.PrivateNetworkID) + "/subnets",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DeleteSubnetsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateRoute: Create a new custom Route.
func (s *API) CreateRoute(req *CreateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/routes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetRoute: Retrieve details of an existing Route, specified by its Route ID.
func (s *API) GetRoute(req *GetRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateRoute: Update parameters of the specified Route.
func (s *API) UpdateRoute(req *UpdateRouteRequest, opts ...scw.RequestOption) (*Route, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return nil, errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Route
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteRoute: Delete a Route specified by its Route ID.
func (s *API) DeleteRoute(req *DeleteRouteRequest, opts ...scw.RequestOption) error {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.RouteID) == "" {
return errors.New("field RouteID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/routes/" + fmt.Sprint(req.RouteID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
type RoutesWithNexthopAPI struct {
client *scw.Client
}
// NewRoutesWithNexthopAPI returns a RoutesWithNexthopAPI object from a Scaleway client.
func NewRoutesWithNexthopAPI(client *scw.Client) *RoutesWithNexthopAPI {
return &RoutesWithNexthopAPI{
client: client,
}
}
// ListRoutesWithNexthop: Return routes with associated next hop data.
func (s *RoutesWithNexthopAPI) ListRoutesWithNexthop(req *RoutesWithNexthopAPIListRoutesWithNexthopRequest, opts ...scw.RequestOption) (*ListRoutesWithNexthopResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "vpc_id", req.VpcID)
parameter.AddToQuery(query, "nexthop_resource_id", req.NexthopResourceID)
parameter.AddToQuery(query, "nexthop_private_network_id", req.NexthopPrivateNetworkID)
parameter.AddToQuery(query, "nexthop_resource_type", req.NexthopResourceType)
parameter.AddToQuery(query, "contains", req.Contains)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "is_ipv6", req.IsIPv6)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc/v2/regions/" + fmt.Sprint(req.Region) + "/routes-with-nexthop",
Query: query,
}
var resp ListRoutesWithNexthopResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/ 0000775 0000000 0000000 00000000000 14747113137 0024143 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v1/ 0000775 0000000 0000000 00000000000 14747113137 0024471 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0026326 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v1/sweepers/sweepers.go 0000664 0000000 0000000 00000005761 14747113137 0030523 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
vpcgwSDK "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepVPCPublicGateway(scwClient *scw.Client, zone scw.Zone) error {
api := vpcgwSDK.NewAPI(scwClient)
listGatewayResponse, err := api.ListGateways(&vpcgwSDK.ListGatewaysRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing public gateway in sweeper: %w", err)
}
for _, gateway := range listGatewayResponse.Gateways {
err := api.DeleteGateway(&vpcgwSDK.DeleteGatewayRequest{
Zone: zone,
GatewayID: gateway.ID,
})
if err != nil {
return fmt.Errorf("error deleting public gateway in sweeper: %w", err)
}
}
return nil
}
func SweepGatewayNetworks(scwClient *scw.Client, zone scw.Zone) error {
api := vpcgwSDK.NewAPI(scwClient)
listPNResponse, err := api.ListGatewayNetworks(&vpcgwSDK.ListGatewayNetworksRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing gateway network in sweeper: %s", err)
}
for _, gn := range listPNResponse.GatewayNetworks {
err := api.DeleteGatewayNetwork(&vpcgwSDK.DeleteGatewayNetworkRequest{
GatewayNetworkID: gn.GatewayID,
Zone: zone,
// Cleanup the dhcp resource related. DON'T CALL THE SWEEPER DHCP
CleanupDHCP: true,
})
if err != nil {
return fmt.Errorf("error deleting gateway network in sweeper: %s", err)
}
}
return nil
}
func SweepVPCPublicGatewayIP(scwClient *scw.Client, zone scw.Zone) error {
api := vpcgwSDK.NewAPI(scwClient)
listIPResponse, err := api.ListIPs(&vpcgwSDK.ListIPsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing public gateway ip in sweeper: %s", err)
}
for _, ip := range listIPResponse.IPs {
err := api.DeleteIP(&vpcgwSDK.DeleteIPRequest{
Zone: zone,
IPID: ip.ID,
})
if err != nil {
return fmt.Errorf("error deleting public gateway ip in sweeper: %s", err)
}
}
return nil
}
func SweepVPCPublicGatewayDHCP(scwClient *scw.Client, zone scw.Zone) error {
api := vpcgwSDK.NewAPI(scwClient)
listDHCPsResponse, err := api.ListDHCPs(&vpcgwSDK.ListDHCPsRequest{
Zone: zone,
}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing public gateway dhcps in sweeper: %w", err)
}
for _, dhcp := range listDHCPsResponse.Dhcps {
err := api.DeleteDHCP(&vpcgwSDK.DeleteDHCPRequest{
Zone: zone,
DHCPID: dhcp.ID,
})
if err != nil {
return fmt.Errorf("error deleting public gateway dhcp in sweeper: %w", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, zone := range (&vpcgwSDK.API{}).Zones() {
err := SweepVPCPublicGateway(scwClient, zone)
if err != nil {
return err
}
err = SweepGatewayNetworks(scwClient, zone)
if err != nil {
return err
}
err = SweepVPCPublicGatewayIP(scwClient, zone)
if err != nil {
return err
}
err = SweepVPCPublicGatewayDHCP(scwClient, zone)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v1/vpcgw_sdk.go 0000664 0000000 0000000 00000262467 14747113137 0027030 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package vpcgw provides methods and message types of the vpcgw v1 API.
package vpcgw
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DHCPEntryType string
const (
DHCPEntryTypeUnknown = DHCPEntryType("unknown")
DHCPEntryTypeReservation = DHCPEntryType("reservation")
DHCPEntryTypeLease = DHCPEntryType("lease")
)
func (enum DHCPEntryType) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DHCPEntryType) Values() []DHCPEntryType {
return []DHCPEntryType{
"unknown",
"reservation",
"lease",
}
}
func (enum DHCPEntryType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DHCPEntryType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DHCPEntryType(DHCPEntryType(tmp).String())
return nil
}
type GatewayNetworkStatus string
const (
GatewayNetworkStatusUnknown = GatewayNetworkStatus("unknown")
GatewayNetworkStatusCreated = GatewayNetworkStatus("created")
GatewayNetworkStatusAttaching = GatewayNetworkStatus("attaching")
GatewayNetworkStatusConfiguring = GatewayNetworkStatus("configuring")
GatewayNetworkStatusReady = GatewayNetworkStatus("ready")
GatewayNetworkStatusDetaching = GatewayNetworkStatus("detaching")
GatewayNetworkStatusDeleted = GatewayNetworkStatus("deleted")
)
func (enum GatewayNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum GatewayNetworkStatus) Values() []GatewayNetworkStatus {
return []GatewayNetworkStatus{
"unknown",
"created",
"attaching",
"configuring",
"ready",
"detaching",
"deleted",
}
}
func (enum GatewayNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GatewayNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GatewayNetworkStatus(GatewayNetworkStatus(tmp).String())
return nil
}
type GatewayStatus string
const (
GatewayStatusUnknown = GatewayStatus("unknown")
GatewayStatusStopped = GatewayStatus("stopped")
GatewayStatusAllocating = GatewayStatus("allocating")
GatewayStatusConfiguring = GatewayStatus("configuring")
GatewayStatusRunning = GatewayStatus("running")
GatewayStatusStopping = GatewayStatus("stopping")
GatewayStatusFailed = GatewayStatus("failed")
GatewayStatusDeleting = GatewayStatus("deleting")
GatewayStatusDeleted = GatewayStatus("deleted")
GatewayStatusLocked = GatewayStatus("locked")
)
func (enum GatewayStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum GatewayStatus) Values() []GatewayStatus {
return []GatewayStatus{
"unknown",
"stopped",
"allocating",
"configuring",
"running",
"stopping",
"failed",
"deleting",
"deleted",
"locked",
}
}
func (enum GatewayStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GatewayStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GatewayStatus(GatewayStatus(tmp).String())
return nil
}
type ListDHCPEntriesRequestOrderBy string
const (
ListDHCPEntriesRequestOrderByCreatedAtAsc = ListDHCPEntriesRequestOrderBy("created_at_asc")
ListDHCPEntriesRequestOrderByCreatedAtDesc = ListDHCPEntriesRequestOrderBy("created_at_desc")
ListDHCPEntriesRequestOrderByIPAddressAsc = ListDHCPEntriesRequestOrderBy("ip_address_asc")
ListDHCPEntriesRequestOrderByIPAddressDesc = ListDHCPEntriesRequestOrderBy("ip_address_desc")
ListDHCPEntriesRequestOrderByHostnameAsc = ListDHCPEntriesRequestOrderBy("hostname_asc")
ListDHCPEntriesRequestOrderByHostnameDesc = ListDHCPEntriesRequestOrderBy("hostname_desc")
)
func (enum ListDHCPEntriesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDHCPEntriesRequestOrderBy) Values() []ListDHCPEntriesRequestOrderBy {
return []ListDHCPEntriesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"ip_address_asc",
"ip_address_desc",
"hostname_asc",
"hostname_desc",
}
}
func (enum ListDHCPEntriesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDHCPEntriesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDHCPEntriesRequestOrderBy(ListDHCPEntriesRequestOrderBy(tmp).String())
return nil
}
type ListDHCPsRequestOrderBy string
const (
ListDHCPsRequestOrderByCreatedAtAsc = ListDHCPsRequestOrderBy("created_at_asc")
ListDHCPsRequestOrderByCreatedAtDesc = ListDHCPsRequestOrderBy("created_at_desc")
ListDHCPsRequestOrderBySubnetAsc = ListDHCPsRequestOrderBy("subnet_asc")
ListDHCPsRequestOrderBySubnetDesc = ListDHCPsRequestOrderBy("subnet_desc")
)
func (enum ListDHCPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListDHCPsRequestOrderBy) Values() []ListDHCPsRequestOrderBy {
return []ListDHCPsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"subnet_asc",
"subnet_desc",
}
}
func (enum ListDHCPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDHCPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDHCPsRequestOrderBy(ListDHCPsRequestOrderBy(tmp).String())
return nil
}
type ListGatewayNetworksRequestOrderBy string
const (
ListGatewayNetworksRequestOrderByCreatedAtAsc = ListGatewayNetworksRequestOrderBy("created_at_asc")
ListGatewayNetworksRequestOrderByCreatedAtDesc = ListGatewayNetworksRequestOrderBy("created_at_desc")
ListGatewayNetworksRequestOrderByStatusAsc = ListGatewayNetworksRequestOrderBy("status_asc")
ListGatewayNetworksRequestOrderByStatusDesc = ListGatewayNetworksRequestOrderBy("status_desc")
)
func (enum ListGatewayNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListGatewayNetworksRequestOrderBy) Values() []ListGatewayNetworksRequestOrderBy {
return []ListGatewayNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"status_asc",
"status_desc",
}
}
func (enum ListGatewayNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGatewayNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGatewayNetworksRequestOrderBy(ListGatewayNetworksRequestOrderBy(tmp).String())
return nil
}
type ListGatewaysRequestOrderBy string
const (
ListGatewaysRequestOrderByCreatedAtAsc = ListGatewaysRequestOrderBy("created_at_asc")
ListGatewaysRequestOrderByCreatedAtDesc = ListGatewaysRequestOrderBy("created_at_desc")
ListGatewaysRequestOrderByNameAsc = ListGatewaysRequestOrderBy("name_asc")
ListGatewaysRequestOrderByNameDesc = ListGatewaysRequestOrderBy("name_desc")
ListGatewaysRequestOrderByTypeAsc = ListGatewaysRequestOrderBy("type_asc")
ListGatewaysRequestOrderByTypeDesc = ListGatewaysRequestOrderBy("type_desc")
ListGatewaysRequestOrderByStatusAsc = ListGatewaysRequestOrderBy("status_asc")
ListGatewaysRequestOrderByStatusDesc = ListGatewaysRequestOrderBy("status_desc")
)
func (enum ListGatewaysRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListGatewaysRequestOrderBy) Values() []ListGatewaysRequestOrderBy {
return []ListGatewaysRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"type_asc",
"type_desc",
"status_asc",
"status_desc",
}
}
func (enum ListGatewaysRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGatewaysRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGatewaysRequestOrderBy(ListGatewaysRequestOrderBy(tmp).String())
return nil
}
type ListIPsRequestOrderBy string
const (
ListIPsRequestOrderByCreatedAtAsc = ListIPsRequestOrderBy("created_at_asc")
ListIPsRequestOrderByCreatedAtDesc = ListIPsRequestOrderBy("created_at_desc")
ListIPsRequestOrderByIPAsc = ListIPsRequestOrderBy("ip_asc")
ListIPsRequestOrderByIPDesc = ListIPsRequestOrderBy("ip_desc")
ListIPsRequestOrderByReverseAsc = ListIPsRequestOrderBy("reverse_asc")
ListIPsRequestOrderByReverseDesc = ListIPsRequestOrderBy("reverse_desc")
)
func (enum ListIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListIPsRequestOrderBy) Values() []ListIPsRequestOrderBy {
return []ListIPsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"ip_asc",
"ip_desc",
"reverse_asc",
"reverse_desc",
}
}
func (enum ListIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListIPsRequestOrderBy(ListIPsRequestOrderBy(tmp).String())
return nil
}
type ListPATRulesRequestOrderBy string
const (
ListPATRulesRequestOrderByCreatedAtAsc = ListPATRulesRequestOrderBy("created_at_asc")
ListPATRulesRequestOrderByCreatedAtDesc = ListPATRulesRequestOrderBy("created_at_desc")
ListPATRulesRequestOrderByPublicPortAsc = ListPATRulesRequestOrderBy("public_port_asc")
ListPATRulesRequestOrderByPublicPortDesc = ListPATRulesRequestOrderBy("public_port_desc")
)
func (enum ListPATRulesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPATRulesRequestOrderBy) Values() []ListPATRulesRequestOrderBy {
return []ListPATRulesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"public_port_asc",
"public_port_desc",
}
}
func (enum ListPATRulesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPATRulesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPATRulesRequestOrderBy(ListPATRulesRequestOrderBy(tmp).String())
return nil
}
type PATRuleProtocol string
const (
PATRuleProtocolUnknown = PATRuleProtocol("unknown")
PATRuleProtocolBoth = PATRuleProtocol("both")
PATRuleProtocolTCP = PATRuleProtocol("tcp")
PATRuleProtocolUDP = PATRuleProtocol("udp")
)
func (enum PATRuleProtocol) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum PATRuleProtocol) Values() []PATRuleProtocol {
return []PATRuleProtocol{
"unknown",
"both",
"tcp",
"udp",
}
}
func (enum PATRuleProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PATRuleProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PATRuleProtocol(PATRuleProtocol(tmp).String())
return nil
}
// DHCP: dhcp.
type DHCP struct {
// ID: ID of the DHCP config.
ID string `json:"id"`
// OrganizationID: owning Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: owning Project.
ProjectID string `json:"project_id"`
// CreatedAt: date the DHCP configuration was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: configuration last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Subnet: subnet for the DHCP server.
Subnet scw.IPNet `json:"subnet"`
// Address: IP address of the DHCP server. This will be the Public Gateway's address in the Private Network. It must be part of config's subnet.
Address net.IP `json:"address"`
// PoolLow: low IP (inclusive) of the dynamic address pool. Must be in the config's subnet.
PoolLow net.IP `json:"pool_low"`
// PoolHigh: high IP (inclusive) of the dynamic address pool. Must be in the config's subnet.
PoolHigh net.IP `json:"pool_high"`
// EnableDynamic: defines whether to enable dynamic pooling of IPs. When false, only pre-existing DHCP reservations will be handed out.
EnableDynamic bool `json:"enable_dynamic"`
// ValidLifetime: how long DHCP entries will be valid for.
ValidLifetime *scw.Duration `json:"valid_lifetime"`
// RenewTimer: after how long a renew will be attempted. Must be 30s lower than `rebind_timer`.
RenewTimer *scw.Duration `json:"renew_timer"`
// RebindTimer: after how long a DHCP client will query for a new lease if previous renews fail. Must be 30s lower than `valid_lifetime`.
RebindTimer *scw.Duration `json:"rebind_timer"`
// PushDefaultRoute: defines whether the gateway should push a default route to DHCP clients, or only hand out IPs.
PushDefaultRoute bool `json:"push_default_route"`
// PushDNSServer: defines whether the gateway should push custom DNS servers to clients. This allows for instance hostname -> IP resolution.
PushDNSServer bool `json:"push_dns_server"`
// DNSServersOverride: array of DNS server IP addresses used to override the DNS server list pushed to DHCP clients, instead of the gateway itself.
DNSServersOverride []string `json:"dns_servers_override"`
// DNSSearch: array of search paths in addition to the pushed DNS configuration.
DNSSearch []string `json:"dns_search"`
// DNSLocalName: tLD given to hostnames in the Private Networks. If an Instance with hostname `foo` gets a lease, and this is set to `bar`, `foo.bar` will resolve.
DNSLocalName string `json:"dns_local_name"`
// Zone: zone of this DHCP configuration.
Zone scw.Zone `json:"zone"`
}
// IpamConfig: ipam config.
type IpamConfig struct {
// PushDefaultRoute: defines whether the default route is enabled on that Gateway Network.
PushDefaultRoute bool `json:"push_default_route"`
// IpamIPID: iPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID string `json:"ipam_ip_id"`
}
// GatewayNetwork: gateway network.
type GatewayNetwork struct {
// ID: ID of the Public Gateway-Private Network connection.
ID string `json:"id"`
// CreatedAt: connection creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: connection last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// GatewayID: ID of the connected Public Gateway.
GatewayID string `json:"gateway_id"`
// PrivateNetworkID: ID of the connected Private Network.
PrivateNetworkID string `json:"private_network_id"`
// MacAddress: mAC address of the gateway in the Private Network (if the gateway is up and running).
MacAddress *string `json:"mac_address"`
// EnableMasquerade: defines whether the gateway masquerades traffic for this Private Network (Dynamic NAT).
EnableMasquerade bool `json:"enable_masquerade"`
// Status: current status of the Public Gateway's connection to the Private Network.
// Default value: unknown
Status GatewayNetworkStatus `json:"status"`
// DHCP: DHCP configuration for the connected Private Network.
DHCP *DHCP `json:"dhcp"`
// EnableDHCP: defines whether DHCP is enabled on the connected Private Network.
EnableDHCP bool `json:"enable_dhcp"`
// Address: address of the Gateway (in CIDR form) to use when DHCP is not used.
Address *scw.IPNet `json:"address"`
// IpamConfig: iPAM IP configuration used.
IpamConfig *IpamConfig `json:"ipam_config"`
// Zone: zone of the GatewayNetwork connection.
Zone scw.Zone `json:"zone"`
}
// GatewayType: gateway type.
type GatewayType struct {
// Name: public Gateway type name.
Name string `json:"name"`
// Bandwidth: bandwidth, in bps, of the Public Gateway. This is the public bandwidth to the outer Internet, and the internal bandwidth to each connected Private Networks.
Bandwidth uint64 `json:"bandwidth"`
// Zone: zone the Public Gateway type is available in.
Zone scw.Zone `json:"zone"`
}
// IP: ip.
type IP struct {
// ID: IP address ID.
ID string `json:"id"`
// OrganizationID: owning Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: owning Project.
ProjectID string `json:"project_id"`
// CreatedAt: IP address creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: IP address last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Tags: tags associated with the IP address.
Tags []string `json:"tags"`
// Address: the IP address itself.
Address net.IP `json:"address"`
// Reverse: reverse domain name for the IP address.
Reverse *string `json:"reverse"`
// GatewayID: public Gateway associated with the IP address.
GatewayID *string `json:"gateway_id"`
// Zone: zone of the IP address.
Zone scw.Zone `json:"zone"`
}
// CreateDHCPRequest: create dhcp request.
type CreateDHCPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: project to create the DHCP configuration in.
ProjectID string `json:"project_id"`
// Subnet: subnet for the DHCP server.
Subnet scw.IPNet `json:"subnet"`
// Address: IP address of the DHCP server. This will be the gateway's address in the Private Network. Defaults to the first address of the subnet.
Address *net.IP `json:"address,omitempty"`
// PoolLow: low IP (inclusive) of the dynamic address pool. Must be in the config's subnet. Defaults to the second address of the subnet.
PoolLow *net.IP `json:"pool_low,omitempty"`
// PoolHigh: high IP (inclusive) of the dynamic address pool. Must be in the config's subnet. Defaults to the last address of the subnet.
PoolHigh *net.IP `json:"pool_high,omitempty"`
// EnableDynamic: defines whether to enable dynamic pooling of IPs. When false, only pre-existing DHCP reservations will be handed out. Defaults to true.
EnableDynamic *bool `json:"enable_dynamic,omitempty"`
// ValidLifetime: how long DHCP entries will be valid for. Defaults to 1h (3600s).
ValidLifetime *scw.Duration `json:"valid_lifetime,omitempty"`
// RenewTimer: after how long a renew will be attempted. Must be 30s lower than `rebind_timer`. Defaults to 50m (3000s).
RenewTimer *scw.Duration `json:"renew_timer,omitempty"`
// RebindTimer: after how long a DHCP client will query for a new lease if previous renews fail. Must be 30s lower than `valid_lifetime`. Defaults to 51m (3060s).
RebindTimer *scw.Duration `json:"rebind_timer,omitempty"`
// PushDefaultRoute: defines whether the gateway should push a default route to DHCP clients or only hand out IPs. Defaults to true.
PushDefaultRoute *bool `json:"push_default_route,omitempty"`
// PushDNSServer: defines whether the gateway should push custom DNS servers to clients. This allows for Instance hostname -> IP resolution. Defaults to true.
PushDNSServer *bool `json:"push_dns_server,omitempty"`
// DNSServersOverride: array of DNS server IP addresses used to override the DNS server list pushed to DHCP clients, instead of the gateway itself.
DNSServersOverride *[]string `json:"dns_servers_override,omitempty"`
// DNSSearch: array of search paths in addition to the pushed DNS configuration.
DNSSearch *[]string `json:"dns_search,omitempty"`
// DNSLocalName: tLD given to hostnames in the Private Network. Allowed characters are `a-z0-9-.`. Defaults to the slugified Private Network name if created along a GatewayNetwork, or else to `priv`.
DNSLocalName *string `json:"dns_local_name,omitempty"`
}
// CreateGatewayNetworkRequestIpamConfig: create gateway network request ipam config.
type CreateGatewayNetworkRequestIpamConfig struct {
// PushDefaultRoute: enabling the default route also enables masquerading.
PushDefaultRoute bool `json:"push_default_route"`
// IpamIPID: use this IPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID *string `json:"ipam_ip_id"`
}
// DHCPEntry: dhcp entry.
type DHCPEntry struct {
// ID: DHCP entry ID.
ID string `json:"id"`
// CreatedAt: DHCP entry creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: DHCP entry last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// GatewayNetworkID: owning GatewayNetwork.
GatewayNetworkID string `json:"gateway_network_id"`
// MacAddress: mAC address of the client device.
MacAddress string `json:"mac_address"`
// IPAddress: assigned IP address.
IPAddress net.IP `json:"ip_address"`
// Hostname: hostname of the client device.
Hostname string `json:"hostname"`
// Type: entry type, either static (DHCP reservation) or dynamic (DHCP lease).
// Default value: unknown
Type DHCPEntryType `json:"type"`
// Zone: zone of this DHCP entry.
Zone scw.Zone `json:"zone"`
}
// Gateway: gateway.
type Gateway struct {
// ID: ID of the gateway.
ID string `json:"id"`
// OrganizationID: owning Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: owning Project.
ProjectID string `json:"project_id"`
// CreatedAt: gateway creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: gateway last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Type: gateway type (commercial offer).
Type *GatewayType `json:"type"`
// Status: current status of the gateway.
// Default value: unknown
Status GatewayStatus `json:"status"`
// Name: name of the gateway.
Name string `json:"name"`
// Tags: tags associated with the gateway.
Tags []string `json:"tags"`
// IP: public IP address of the gateway.
IP *IP `json:"ip"`
// GatewayNetworks: gatewayNetwork objects attached to the gateway (each one represents a connection to a Private Network).
GatewayNetworks []*GatewayNetwork `json:"gateway_networks"`
// UpstreamDNSServers: array of DNS server IP addresses to override the gateway's default recursive DNS servers.
UpstreamDNSServers []string `json:"upstream_dns_servers"`
// Version: version of the running gateway software.
Version *string `json:"version"`
// CanUpgradeTo: newly available gateway software version that can be updated to.
CanUpgradeTo *string `json:"can_upgrade_to"`
// BastionEnabled: defines whether SSH bastion is enabled on the gateway.
BastionEnabled bool `json:"bastion_enabled"`
// BastionPort: port of the SSH bastion.
BastionPort uint32 `json:"bastion_port"`
// SMTPEnabled: defines whether SMTP traffic is allowed to pass through the gateway.
SMTPEnabled bool `json:"smtp_enabled"`
// IsLegacy: defines whether the gateway uses non-IPAM IP configurations.
IsLegacy bool `json:"is_legacy"`
// IPMobilityEnabled: defines whether the gateway uses routed IPs (IP mobility) instead of NAT IPs.
IPMobilityEnabled bool `json:"ip_mobility_enabled"`
// Zone: zone of the gateway.
Zone scw.Zone `json:"zone"`
}
// PATRule: pat rule.
type PATRule struct {
// ID: pAT rule ID.
ID string `json:"id"`
// GatewayID: gateway the PAT rule applies to.
GatewayID string `json:"gateway_id"`
// CreatedAt: pAT rule creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: pAT rule last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// PublicPort: public port to listen on.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP address to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule applies to.
// Default value: unknown
Protocol PATRuleProtocol `json:"protocol"`
// Zone: zone of the PAT rule.
Zone scw.Zone `json:"zone"`
}
// SetDHCPEntriesRequestEntry: set dhcp entries request entry.
type SetDHCPEntriesRequestEntry struct {
// MacAddress: mAC address to give a static entry to. A matching entry will be upgraded to a reservation, and a matching reservation will be updated.
MacAddress string `json:"mac_address"`
// IPAddress: IP address to give to the device.
IPAddress net.IP `json:"ip_address"`
}
// SetPATRulesRequestRule: set pat rules request rule.
type SetPATRulesRequestRule struct {
// PublicPort: public port to listen on. Uniquely identifies the rule, and a matching rule will be updated with the new parameters.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule should apply to.
// Default value: unknown
Protocol PATRuleProtocol `json:"protocol"`
}
// UpdateGatewayNetworkRequestIpamConfig: update gateway network request ipam config.
type UpdateGatewayNetworkRequestIpamConfig struct {
// PushDefaultRoute: enabling the default route also enables masquerading.
PushDefaultRoute *bool `json:"push_default_route"`
// IpamIPID: use this IPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID *string `json:"ipam_ip_id"`
}
// CreateDHCPEntryRequest: create dhcp entry request.
type CreateDHCPEntryRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: gatewayNetwork on which to create a DHCP reservation.
GatewayNetworkID string `json:"gateway_network_id"`
// MacAddress: mAC address to give a static entry to.
MacAddress string `json:"mac_address"`
// IPAddress: IP address to give to the device.
IPAddress net.IP `json:"ip_address"`
}
// CreateGatewayNetworkRequest: create gateway network request.
type CreateGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: public Gateway to connect.
GatewayID string `json:"gateway_id"`
// PrivateNetworkID: private Network to connect.
PrivateNetworkID string `json:"private_network_id"`
// EnableMasquerade: note: this setting is ignored when passing `ipam_config`.
EnableMasquerade bool `json:"enable_masquerade"`
// EnableDHCP: defaults to `true` if either `dhcp_id` or `dhcp` are present. If set to `true`, either `dhcp_id` or `dhcp` must be present.
// Note: this setting is ignored when passing `ipam_config`.
EnableDHCP *bool `json:"enable_dhcp,omitempty"`
// DHCPID: ID of an existing DHCP configuration object to use for this GatewayNetwork.
// Precisely one of DHCPID, DHCP, Address, IpamConfig must be set.
DHCPID *string `json:"dhcp_id,omitempty"`
// DHCP: new DHCP configuration object to use for this GatewayNetwork.
// Precisely one of DHCPID, DHCP, Address, IpamConfig must be set.
DHCP *CreateDHCPRequest `json:"dhcp,omitempty"`
// Address: static IP address in CIDR format to to use without DHCP.
// Precisely one of DHCPID, DHCP, Address, IpamConfig must be set.
Address *scw.IPNet `json:"address,omitempty"`
// IpamConfig: note: all or none of the GatewayNetworks for a single gateway can use the IPAM. DHCP and IPAM configurations cannot be mixed. Some products may require that the Public Gateway uses the IPAM, to ensure correct functionality.
// Precisely one of DHCPID, DHCP, Address, IpamConfig must be set.
IpamConfig *CreateGatewayNetworkRequestIpamConfig `json:"ipam_config,omitempty"`
}
// CreateGatewayRequest: create gateway request.
type CreateGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: scaleway Project to create the gateway in.
ProjectID string `json:"project_id"`
// Name: name for the gateway.
Name string `json:"name"`
// Tags: tags for the gateway.
Tags []string `json:"tags"`
// Type: gateway type (commercial offer type).
Type string `json:"type"`
// UpstreamDNSServers: array of DNS server IP addresses to override the gateway's default recursive DNS servers.
UpstreamDNSServers []string `json:"upstream_dns_servers"`
// IPID: existing IP address to attach to the gateway.
IPID *string `json:"ip_id,omitempty"`
// EnableSMTP: defines whether SMTP traffic should be allowed pass through the gateway.
EnableSMTP bool `json:"enable_smtp"`
// EnableBastion: defines whether SSH bastion should be enabled the gateway.
EnableBastion bool `json:"enable_bastion"`
// BastionPort: port of the SSH bastion.
BastionPort *uint32 `json:"bastion_port,omitempty"`
}
// CreateIPRequest: create ip request.
type CreateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: project to create the IP address in.
ProjectID string `json:"project_id"`
// Tags: tags to give to the IP address.
Tags []string `json:"tags"`
}
// CreatePATRuleRequest: create pat rule request.
type CreatePATRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the Gateway on which to create the rule.
GatewayID string `json:"gateway_id"`
// PublicPort: public port to listen on.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule should apply to.
// Default value: unknown
Protocol PATRuleProtocol `json:"protocol"`
}
// DeleteDHCPEntryRequest: delete dhcp entry request.
type DeleteDHCPEntryRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPEntryID: ID of the DHCP entry to delete.
DHCPEntryID string `json:"-"`
}
// DeleteDHCPRequest: delete dhcp request.
type DeleteDHCPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPID: DHCP configuration ID to delete.
DHCPID string `json:"-"`
}
// DeleteGatewayNetworkRequest: delete gateway network request.
type DeleteGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to delete.
GatewayNetworkID string `json:"-"`
// CleanupDHCP: defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network).
CleanupDHCP bool `json:"cleanup_dhcp"`
}
// DeleteGatewayRequest: delete gateway request.
type DeleteGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to delete.
GatewayID string `json:"-"`
// CleanupDHCP: defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network).
CleanupDHCP bool `json:"cleanup_dhcp"`
}
// DeleteIPRequest: delete ip request.
type DeleteIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to delete.
IPID string `json:"-"`
}
// DeletePATRuleRequest: delete pat rule request.
type DeletePATRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to delete.
PatRuleID string `json:"-"`
}
// EnableIPMobilityRequest: enable ip mobility request.
type EnableIPMobilityRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to upgrade to IP mobility.
GatewayID string `json:"-"`
}
// GetDHCPEntryRequest: get dhcp entry request.
type GetDHCPEntryRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPEntryID: ID of the DHCP entry to fetch.
DHCPEntryID string `json:"-"`
}
// GetDHCPRequest: get dhcp request.
type GetDHCPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPID: ID of the DHCP configuration to fetch.
DHCPID string `json:"-"`
}
// GetGatewayNetworkRequest: get gateway network request.
type GetGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to fetch.
GatewayNetworkID string `json:"-"`
}
// GetGatewayRequest: get gateway request.
type GetGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to fetch.
GatewayID string `json:"-"`
}
// GetIPRequest: get ip request.
type GetIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to get.
IPID string `json:"-"`
}
// GetPATRuleRequest: get pat rule request.
type GetPATRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to get.
PatRuleID string `json:"-"`
}
// ListDHCPEntriesRequest: list dhcp entries request.
type ListDHCPEntriesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListDHCPEntriesRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: DHCP entries per page.
PageSize *uint32 `json:"-"`
// GatewayNetworkID: filter for entries on this GatewayNetwork.
GatewayNetworkID *string `json:"-"`
// MacAddress: filter for entries with this MAC address.
MacAddress *string `json:"-"`
// IPAddress: filter for entries with this IP address.
IPAddress *net.IP `json:"-"`
// Hostname: filter for entries with this hostname substring.
Hostname *string `json:"-"`
// Type: filter for entries of this type.
// Default value: unknown
Type DHCPEntryType `json:"-"`
}
// ListDHCPEntriesResponse: list dhcp entries response.
type ListDHCPEntriesResponse struct {
// DHCPEntries: DHCP entries in this page.
DHCPEntries []*DHCPEntry `json:"dhcp_entries"`
// TotalCount: total count of DHCP entries matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDHCPEntriesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDHCPEntriesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDHCPEntriesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.DHCPEntries = append(r.DHCPEntries, results.DHCPEntries...)
r.TotalCount += uint32(len(results.DHCPEntries))
return uint32(len(results.DHCPEntries)), nil
}
// ListDHCPsRequest: list dhc ps request.
type ListDHCPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListDHCPsRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: DHCP configurations per page.
PageSize *uint32 `json:"-"`
// OrganizationID: include only DHCP configuration objects in this Organization.
OrganizationID *string `json:"-"`
// ProjectID: include only DHCP configuration objects in this Project.
ProjectID *string `json:"-"`
// Address: filter for DHCP configuration objects with this DHCP server IP address (the gateway's address in the Private Network).
Address *net.IP `json:"-"`
// HasAddress: filter for DHCP configuration objects with subnets containing this IP address.
HasAddress *net.IP `json:"-"`
}
// ListDHCPsResponse: list dhc ps response.
type ListDHCPsResponse struct {
// Dhcps: first page of DHCP configuration objects.
Dhcps []*DHCP `json:"dhcps"`
// TotalCount: total count of DHCP configuration objects matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDHCPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDHCPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListDHCPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Dhcps = append(r.Dhcps, results.Dhcps...)
r.TotalCount += uint32(len(results.Dhcps))
return uint32(len(results.Dhcps)), nil
}
// ListGatewayNetworksRequest: list gateway networks request.
type ListGatewayNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListGatewayNetworksRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: gatewayNetworks per page.
PageSize *uint32 `json:"-"`
// GatewayID: filter for GatewayNetworks connected to this gateway.
GatewayID *string `json:"-"`
// PrivateNetworkID: filter for GatewayNetworks connected to this Private Network.
PrivateNetworkID *string `json:"-"`
// EnableMasquerade: filter for GatewayNetworks with this `enable_masquerade` setting.
EnableMasquerade *bool `json:"-"`
// DHCPID: filter for GatewayNetworks using this DHCP configuration.
DHCPID *string `json:"-"`
// Status: filter for GatewayNetworks with this current status this status. Use `unknown` to include all statuses.
// Default value: unknown
Status GatewayNetworkStatus `json:"-"`
}
// ListGatewayNetworksResponse: list gateway networks response.
type ListGatewayNetworksResponse struct {
// GatewayNetworks: gatewayNetworks on this page.
GatewayNetworks []*GatewayNetwork `json:"gateway_networks"`
// TotalCount: total GatewayNetworks count matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGatewayNetworksResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGatewayNetworksResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListGatewayNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.GatewayNetworks = append(r.GatewayNetworks, results.GatewayNetworks...)
r.TotalCount += uint32(len(results.GatewayNetworks))
return uint32(len(results.GatewayNetworks)), nil
}
// ListGatewayTypesRequest: list gateway types request.
type ListGatewayTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
}
// ListGatewayTypesResponse: list gateway types response.
type ListGatewayTypesResponse struct {
// Types: available types of Public Gateway.
Types []*GatewayType `json:"types"`
}
// ListGatewaysRequest: list gateways request.
type ListGatewaysRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListGatewaysRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: gateways per page.
PageSize *uint32 `json:"-"`
// OrganizationID: include only gateways in this Organization.
OrganizationID *string `json:"-"`
// ProjectID: include only gateways in this Project.
ProjectID *string `json:"-"`
// Name: filter for gateways which have this search term in their name.
Name *string `json:"-"`
// Tags: filter for gateways with these tags.
Tags []string `json:"-"`
// Type: filter for gateways of this type.
Type *string `json:"-"`
// Status: filter for gateways with this current status. Use `unknown` to include all statuses.
// Default value: unknown
Status GatewayStatus `json:"-"`
// PrivateNetworkID: filter for gateways attached to this Private nNetwork.
PrivateNetworkID *string `json:"-"`
}
// ListGatewaysResponse: list gateways response.
type ListGatewaysResponse struct {
// Gateways: gateways on this page.
Gateways []*Gateway `json:"gateways"`
// TotalCount: total count of gateways matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGatewaysResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGatewaysResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListGatewaysResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Gateways = append(r.Gateways, results.Gateways...)
r.TotalCount += uint32(len(results.Gateways))
return uint32(len(results.Gateways)), nil
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListIPsRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: IP addresses per page.
PageSize *uint32 `json:"-"`
// OrganizationID: filter for IP addresses in this Organization.
OrganizationID *string `json:"-"`
// ProjectID: filter for IP addresses in this Project.
ProjectID *string `json:"-"`
// Tags: filter for IP addresses with these tags.
Tags []string `json:"-"`
// Reverse: filter for IP addresses that have a reverse containing this string.
Reverse *string `json:"-"`
// IsFree: filter based on whether the IP is attached to a gateway or not.
IsFree *bool `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
// IPs: IP addresses on this page.
IPs []*IP `json:"ips"`
// TotalCount: total count of IP addresses matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint32(len(results.IPs))
return uint32(len(results.IPs)), nil
}
// ListPATRulesRequest: list pat rules request.
type ListPATRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListPATRulesRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: pAT rules per page.
PageSize *uint32 `json:"-"`
// GatewayID: filter for PAT rules on this Gateway.
GatewayID *string `json:"-"`
// PrivateIP: filter for PAT rules targeting this private ip.
PrivateIP *net.IP `json:"-"`
// Protocol: filter for PAT rules with this protocol.
// Default value: unknown
Protocol PATRuleProtocol `json:"-"`
}
// ListPATRulesResponse: list pat rules response.
type ListPATRulesResponse struct {
// PatRules: array of PAT rules matching the filter.
PatRules []*PATRule `json:"pat_rules"`
// TotalCount: total count of PAT rules matching the filter.
TotalCount uint32 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPATRulesResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPATRulesResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListPATRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PatRules = append(r.PatRules, results.PatRules...)
r.TotalCount += uint32(len(results.PatRules))
return uint32(len(results.PatRules)), nil
}
// RefreshSSHKeysRequest: refresh ssh keys request.
type RefreshSSHKeysRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to refresh SSH keys on.
GatewayID string `json:"-"`
}
// SetDHCPEntriesRequest: set dhcp entries request.
type SetDHCPEntriesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the Gateway Network on which to set DHCP reservation list.
GatewayNetworkID string `json:"gateway_network_id"`
// DHCPEntries: new list of DHCP reservations.
DHCPEntries []*SetDHCPEntriesRequestEntry `json:"dhcp_entries"`
}
// SetDHCPEntriesResponse: set dhcp entries response.
type SetDHCPEntriesResponse struct {
// DHCPEntries: list of DHCP entries.
DHCPEntries []*DHCPEntry `json:"dhcp_entries"`
}
// SetPATRulesRequest: set pat rules request.
type SetPATRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway on which to set the PAT rules.
GatewayID string `json:"gateway_id"`
// PatRules: new list of PAT rules.
PatRules []*SetPATRulesRequestRule `json:"pat_rules"`
}
// SetPATRulesResponse: set pat rules response.
type SetPATRulesResponse struct {
// PatRules: list of PAT rules.
PatRules []*PATRule `json:"pat_rules"`
}
// UpdateDHCPEntryRequest: update dhcp entry request.
type UpdateDHCPEntryRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPEntryID: ID of the DHCP entry to update.
DHCPEntryID string `json:"-"`
// IPAddress: new IP address to give to the device.
IPAddress *net.IP `json:"ip_address,omitempty"`
}
// UpdateDHCPRequest: update dhcp request.
type UpdateDHCPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// DHCPID: DHCP configuration to update.
DHCPID string `json:"-"`
// Subnet: subnet for the DHCP server.
Subnet *scw.IPNet `json:"subnet,omitempty"`
// Address: IP address of the DHCP server. This will be the Public Gateway's address in the Private Network. It must be part of config's subnet.
Address *net.IP `json:"address,omitempty"`
// PoolLow: low IP (inclusive) of the dynamic address pool. Must be in the config's subnet.
PoolLow *net.IP `json:"pool_low,omitempty"`
// PoolHigh: high IP (inclusive) of the dynamic address pool. Must be in the config's subnet.
PoolHigh *net.IP `json:"pool_high,omitempty"`
// EnableDynamic: defines whether to enable dynamic pooling of IPs. When false, only pre-existing DHCP reservations will be handed out. Defaults to true.
EnableDynamic *bool `json:"enable_dynamic,omitempty"`
// ValidLifetime: how long DHCP entries will be valid for.
ValidLifetime *scw.Duration `json:"valid_lifetime,omitempty"`
// RenewTimer: after how long a renew will be attempted. Must be 30s lower than `rebind_timer`.
RenewTimer *scw.Duration `json:"renew_timer,omitempty"`
// RebindTimer: after how long a DHCP client will query for a new lease if previous renews fail. Must be 30s lower than `valid_lifetime`.
RebindTimer *scw.Duration `json:"rebind_timer,omitempty"`
// PushDefaultRoute: defines whether the gateway should push a default route to DHCP clients, or only hand out IPs.
PushDefaultRoute *bool `json:"push_default_route,omitempty"`
// PushDNSServer: defines whether the gateway should push custom DNS servers to clients. This allows for instance hostname -> IP resolution.
PushDNSServer *bool `json:"push_dns_server,omitempty"`
// DNSServersOverride: array of DNS server IP addresses used to override the DNS server list pushed to DHCP clients, instead of the gateway itself.
DNSServersOverride *[]string `json:"dns_servers_override,omitempty"`
// DNSSearch: array of search paths in addition to the pushed DNS configuration.
DNSSearch *[]string `json:"dns_search,omitempty"`
// DNSLocalName: tLD given to hostnames in the Private Networks. If an instance with hostname `foo` gets a lease, and this is set to `bar`, `foo.bar` will resolve. Allowed characters are `a-z0-9-.`.
DNSLocalName *string `json:"dns_local_name,omitempty"`
}
// UpdateGatewayNetworkRequest: update gateway network request.
type UpdateGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to update.
GatewayNetworkID string `json:"-"`
// EnableMasquerade: note: this setting is ignored when passing `ipam_config`.
EnableMasquerade *bool `json:"enable_masquerade,omitempty"`
// EnableDHCP: defaults to `true` if `dhcp_id` is present. If set to `true`, `dhcp_id` must be present.
// Note: this setting is ignored when passing `ipam_config`.
EnableDHCP *bool `json:"enable_dhcp,omitempty"`
// DHCPID: ID of the new DHCP configuration object to use with this GatewayNetwork.
// Precisely one of DHCPID, Address, IpamConfig must be set.
DHCPID *string `json:"dhcp_id,omitempty"`
// Address: new static IP address.
// Precisely one of DHCPID, Address, IpamConfig must be set.
Address *scw.IPNet `json:"address,omitempty"`
// IpamConfig: note: all or none of the GatewayNetworks for a single gateway can use the IPAM. DHCP and IPAM configurations cannot be mixed. Some products may require that the Public Gateway uses the IPAM, to ensure correct functionality.
// Precisely one of DHCPID, Address, IpamConfig must be set.
IpamConfig *UpdateGatewayNetworkRequestIpamConfig `json:"ipam_config,omitempty"`
}
// UpdateGatewayRequest: update gateway request.
type UpdateGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to update.
GatewayID string `json:"-"`
// Name: name for the gateway.
Name *string `json:"name,omitempty"`
// Tags: tags for the gateway.
Tags *[]string `json:"tags,omitempty"`
// UpstreamDNSServers: array of DNS server IP addresses to override the gateway's default recursive DNS servers.
UpstreamDNSServers *[]string `json:"upstream_dns_servers,omitempty"`
// EnableBastion: defines whether SSH bastion should be enabled the gateway.
EnableBastion *bool `json:"enable_bastion,omitempty"`
// BastionPort: port of the SSH bastion.
BastionPort *uint32 `json:"bastion_port,omitempty"`
// EnableSMTP: defines whether SMTP traffic should be allowed to pass through the gateway.
EnableSMTP *bool `json:"enable_smtp,omitempty"`
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to update.
IPID string `json:"-"`
// Tags: tags to give to the IP address.
Tags *[]string `json:"tags,omitempty"`
// Reverse: reverse to set on the address. Empty string to unset.
Reverse *string `json:"reverse,omitempty"`
// GatewayID: gateway to attach the IP address to. Empty string to detach.
GatewayID *string `json:"gateway_id,omitempty"`
}
// UpdatePATRuleRequest: update pat rule request.
type UpdatePATRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to update.
PatRuleID string `json:"-"`
// PublicPort: public port to listen on.
PublicPort *uint32 `json:"public_port,omitempty"`
// PrivateIP: private IP to forward data to.
PrivateIP *net.IP `json:"private_ip,omitempty"`
// PrivatePort: private port to translate to.
PrivatePort *uint32 `json:"private_port,omitempty"`
// Protocol: protocol the rule should apply to.
// Default value: unknown
Protocol PATRuleProtocol `json:"protocol"`
}
// UpgradeGatewayRequest: upgrade gateway request.
type UpgradeGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to upgrade.
GatewayID string `json:"-"`
// Type: gateway type (commercial offer).
Type *string `json:"type,omitempty"`
}
// This API allows you to manage your Public Gateways.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// ListGateways: List Public Gateways in a given Scaleway Organization or Project. By default, results are displayed in ascending order of creation date.
func (s *API) ListGateways(req *ListGatewaysRequest, opts ...scw.RequestOption) (*ListGatewaysResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "type", req.Type)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways",
Query: query,
}
var resp ListGatewaysResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGateway: Get details of a Public Gateway, specified by its gateway ID. The response object contains full details of the gateway, including its **name**, **type**, **status** and more.
func (s *API) GetGateway(req *GetGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateGateway: Create a new Public Gateway in the specified Scaleway Project, defining its **name**, **type** and other configuration details such as whether to enable SSH bastion.
func (s *API) CreateGateway(req *CreateGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("gw")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateGateway: Update the parameters of an existing Public Gateway, for example, its **name**, **tags**, **SSH bastion configuration**, and **DNS servers**.
func (s *API) UpdateGateway(req *UpdateGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGateway: Delete an existing Public Gateway, specified by its gateway ID. This action is irreversible.
func (s *API) DeleteGateway(req *DeleteGatewayRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "cleanup_dhcp", req.CleanupDHCP)
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// UpgradeGateway: Upgrade a given Public Gateway to the newest software version or to a different commercial offer type. This applies the latest bugfixes and features to your Public Gateway. Note that gateway service will be interrupted during the update.
func (s *API) UpgradeGateway(req *UpgradeGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// EnableIPMobility: Upgrade a Public Gateway to IP mobility (move from NAT IP to routed IP). This is idempotent: repeated calls after the first will return no error but have no effect.
func (s *API) EnableIPMobility(req *EnableIPMobilityRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/enable-ip-mobility",
}
err = scwReq.SetBody(req)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListGatewayNetworks: List the connections between Public Gateways and Private Networks (a connection = a GatewayNetwork). You can choose to filter by `gateway-id` to list all Private Networks attached to the specified Public Gateway, or by `private_network_id` to list all Public Gateways attached to the specified Private Network. Other query parameters are also available. The result is an array of GatewayNetwork objects, each giving details of the connection between a given Public Gateway and a given Private Network.
func (s *API) ListGatewayNetworks(req *ListGatewayNetworksRequest, opts ...scw.RequestOption) (*ListGatewayNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "gateway_id", req.GatewayID)
parameter.AddToQuery(query, "private_network_id", req.PrivateNetworkID)
parameter.AddToQuery(query, "enable_masquerade", req.EnableMasquerade)
parameter.AddToQuery(query, "dhcp_id", req.DHCPID)
parameter.AddToQuery(query, "status", req.Status)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks",
Query: query,
}
var resp ListGatewayNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGatewayNetwork: Get details of a given connection between a Public Gateway and a Private Network (this connection = a GatewayNetwork), specified by its `gateway_network_id`. The response object contains details of the connection including the IDs of the Public Gateway and Private Network, the dates the connection was created/updated and its configuration settings.
func (s *API) GetGatewayNetwork(req *GetGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return nil, errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateGatewayNetwork: Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including DHCP settings, whether to enable masquerade (dynamic NAT), and more.
func (s *API) CreateGatewayNetwork(req *CreateGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateGatewayNetwork: Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include DHCP settings and whether to enable traffic masquerade (dynamic NAT).
func (s *API) UpdateGatewayNetwork(req *UpdateGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return nil, errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGatewayNetwork: Detach a given Public Gateway from a given Private Network, i.e. delete a GatewayNetwork specified by a gateway_network_id.
func (s *API) DeleteGatewayNetwork(req *DeleteGatewayNetworkRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "cleanup_dhcp", req.CleanupDHCP)
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
Query: query,
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDHCPs: List DHCP configurations, optionally filtering by Organization, Project, Public Gateway IP address or more. The response is an array of DHCP configuration objects, each identified by a DHCP ID and containing configuration settings for the assignment of IP addresses to devices on a Private Network attached to a Public Gateway. Note that the response does not contain the IDs of any Private Network / Public Gateway the configuration is attached to. Use the `List Public Gateway connections to Private Networks` method for that purpose, filtering on DHCP ID.
func (s *API) ListDHCPs(req *ListDHCPsRequest, opts ...scw.RequestOption) (*ListDHCPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "address", req.Address)
parameter.AddToQuery(query, "has_address", req.HasAddress)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcps",
Query: query,
}
var resp ListDHCPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDHCP: Get a DHCP configuration object, identified by its DHCP ID. The response object contains configuration settings for the assignment of IP addresses to devices on a Private Network attached to a Public Gateway. Note that the response does not contain the IDs of any Private Network / Public Gateway the configuration is attached to. Use the `List Public Gateway connections to Private Networks` method for that purpose, filtering on DHCP ID.
func (s *API) GetDHCP(req *GetDHCPRequest, opts ...scw.RequestOption) (*DHCP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPID) == "" {
return nil, errors.New("field DHCPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcps/" + fmt.Sprint(req.DHCPID) + "",
}
var resp DHCP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDHCP: Create a new DHCP configuration object, containing settings for the assignment of IP addresses to devices on a Private Network attached to a Public Gateway. The response object includes the ID of the DHCP configuration object. You can use this ID as part of a call to `Create a Public Gateway connection to a Private Network` or `Update a Public Gateway connection to a Private Network` to directly apply this DHCP configuration.
func (s *API) CreateDHCP(req *CreateDHCPRequest, opts ...scw.RequestOption) (*DHCP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcps",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DHCP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDHCP: Update a DHCP configuration object, identified by its DHCP ID.
func (s *API) UpdateDHCP(req *UpdateDHCPRequest, opts ...scw.RequestOption) (*DHCP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPID) == "" {
return nil, errors.New("field DHCPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcps/" + fmt.Sprint(req.DHCPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DHCP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDHCP: Delete a DHCP configuration object, identified by its DHCP ID. Note that you cannot delete a DHCP configuration object that is currently being used by a Gateway Network.
func (s *API) DeleteDHCP(req *DeleteDHCPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPID) == "" {
return errors.New("field DHCPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcps/" + fmt.Sprint(req.DHCPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListDHCPEntries: List DHCP entries, whether dynamically assigned and/or statically reserved. DHCP entries can be filtered by the Gateway Network they are on, their MAC address, IP address, type or hostname.
func (s *API) ListDHCPEntries(req *ListDHCPEntriesRequest, opts ...scw.RequestOption) (*ListDHCPEntriesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "gateway_network_id", req.GatewayNetworkID)
parameter.AddToQuery(query, "mac_address", req.MacAddress)
parameter.AddToQuery(query, "ip_address", req.IPAddress)
parameter.AddToQuery(query, "hostname", req.Hostname)
parameter.AddToQuery(query, "type", req.Type)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries",
Query: query,
}
var resp ListDHCPEntriesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDHCPEntry: Get a DHCP entry, specified by its DHCP entry ID.
func (s *API) GetDHCPEntry(req *GetDHCPEntryRequest, opts ...scw.RequestOption) (*DHCPEntry, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPEntryID) == "" {
return nil, errors.New("field DHCPEntryID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries/" + fmt.Sprint(req.DHCPEntryID) + "",
}
var resp DHCPEntry
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDHCPEntry: Create a static DHCP reservation, specifying the Gateway Network for the reservation, the MAC address of the target device and the IP address to assign this device. The response is a DHCP entry object, confirming the ID and configuration details of the static DHCP reservation.
func (s *API) CreateDHCPEntry(req *CreateDHCPEntryRequest, opts ...scw.RequestOption) (*DHCPEntry, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DHCPEntry
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateDHCPEntry: Update the IP address for a DHCP entry, specified by its DHCP entry ID. You can update an existing DHCP entry of any type (`reservation` (static), `lease` (dynamic) or `unknown`), but in manually updating the IP address the entry will necessarily be of type `reservation` after the update.
func (s *API) UpdateDHCPEntry(req *UpdateDHCPEntryRequest, opts ...scw.RequestOption) (*DHCPEntry, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPEntryID) == "" {
return nil, errors.New("field DHCPEntryID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries/" + fmt.Sprint(req.DHCPEntryID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DHCPEntry
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetDHCPEntries: Set the list of DHCP reservations attached to a Gateway Network. Reservations are identified by their MAC address, and will sync the current DHCP entry list to the given list, creating, updating or deleting DHCP entries accordingly.
func (s *API) SetDHCPEntries(req *SetDHCPEntriesRequest, opts ...scw.RequestOption) (*SetDHCPEntriesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetDHCPEntriesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDHCPEntry: Delete a static DHCP reservation, identified by its DHCP entry ID. Note that you cannot delete DHCP entries of type `lease`, these are deleted automatically when their time-to-live expires.
func (s *API) DeleteDHCPEntry(req *DeleteDHCPEntryRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.DHCPEntryID) == "" {
return errors.New("field DHCPEntryID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/dhcp-entries/" + fmt.Sprint(req.DHCPEntryID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListPATRules: List PAT rules. You can filter by gateway ID to list all PAT rules for a particular gateway, or filter for PAT rules targeting a specific IP address or using a specific protocol.
func (s *API) ListPATRules(req *ListPATRulesRequest, opts ...scw.RequestOption) (*ListPATRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "gateway_id", req.GatewayID)
parameter.AddToQuery(query, "private_ip", req.PrivateIP)
parameter.AddToQuery(query, "protocol", req.Protocol)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
Query: query,
}
var resp ListPATRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPATRule: Get a PAT rule, specified by its PAT rule ID. The response object gives full details of the PAT rule, including the Public Gateway it belongs to and the configuration settings in terms of public / private ports, private IP and protocol.
func (s *API) GetPATRule(req *GetPATRuleRequest, opts ...scw.RequestOption) (*PATRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return nil, errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
var resp PATRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePATRule: Create a new PAT rule on a specified Public Gateway, defining the protocol to use, public port to listen on, and private port / IP address to map to.
func (s *API) CreatePATRule(req *CreatePATRuleRequest, opts ...scw.RequestOption) (*PATRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PATRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePATRule: Update a PAT rule, specified by its PAT rule ID. Configuration settings including private/public port, private IP address and protocol can all be updated.
func (s *API) UpdatePATRule(req *UpdatePATRuleRequest, opts ...scw.RequestOption) (*PATRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return nil, errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PATRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPATRules: Set a definitive list of PAT rules attached to a Public Gateway. Each rule is identified by its public port and protocol. This will sync the current PAT rule list on the gateway with the new list, creating, updating or deleting PAT rules accordingly.
func (s *API) SetPATRules(req *SetPATRulesRequest, opts ...scw.RequestOption) (*SetPATRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetPATRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePATRule: Delete a PAT rule, identified by its PAT rule ID. This action is irreversible.
func (s *API) DeletePATRule(req *DeletePATRuleRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListGatewayTypes: List the different Public Gateway commercial offer types available at Scaleway. The response is an array of objects describing the name and technical details of each available gateway type.
func (s *API) ListGatewayTypes(req *ListGatewayTypesRequest, opts ...scw.RequestOption) (*ListGatewayTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateway-types",
}
var resp ListGatewayTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List Public Gateway flexible IP addresses. A number of filter options are available for limiting results in the response.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "reverse", req.Reverse)
parameter.AddToQuery(query, "is_free", req.IsFree)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIP: Get details of a Public Gateway flexible IP address, identified by its IP ID. The response object contains information including which (if any) Public Gateway using this IP address, the reverse and various other metadata.
func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIP: Create (reserve) a new flexible IP address that can be used for a Public Gateway in a specified Scaleway Project.
func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateIP: Update details of an existing flexible IP address, including its tags, reverse and the Public Gateway it is assigned to.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteIP: Delete a flexible IP address from your account. This action is irreversible.
func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RefreshSSHKeys: Refresh the SSH keys of a given Public Gateway, specified by its gateway ID. This adds any new SSH keys in the gateway's Scaleway Project to the gateway itself.
func (s *API) RefreshSSHKeys(req *RefreshSSHKeysRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v1/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/refresh-ssh-keys",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v1/vpcgw_utils.go 0000664 0000000 0000000 00000011241 14747113137 0027365 0 ustar 00root root 0000000 0000000 package vpcgw
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 15 * time.Second
)
// WaitForGatewayRequest is used by WaitForGateway method
type WaitForGatewayRequest struct {
GatewayID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForGateway waits for the gateway to be in a "terminal state" before returning.
// This function can be used to wait for a gateway to be ready for example.
func (s *API) WaitForGateway(req *WaitForGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[GatewayStatus]struct{}{
GatewayStatusUnknown: {},
GatewayStatusStopped: {},
GatewayStatusRunning: {},
GatewayStatusFailed: {},
GatewayStatusDeleted: {},
GatewayStatusLocked: {},
}
gateway, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
ns, err := s.GetGateway(&GetGatewayRequest{
Zone: req.Zone,
GatewayID: req.GatewayID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[ns.Status]
return ns, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for gateway failed")
}
return gateway.(*Gateway), nil
}
// WaitForGatewayNetworkRequest is used by WaitForGatewayNetwork method
type WaitForGatewayNetworkRequest struct {
GatewayNetworkID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForGatewayNetwork waits for the gateway network to be in a "terminal state" before returning.
// This function can be used to wait for a gateway network to be ready for example.
func (s *API) WaitForGatewayNetwork(req *WaitForGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[GatewayNetworkStatus]struct{}{
GatewayNetworkStatusReady: {},
GatewayNetworkStatusUnknown: {},
GatewayNetworkStatusDeleted: {},
}
gatewayNetwork, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
ns, err := s.GetGatewayNetwork(&GetGatewayNetworkRequest{
Zone: req.Zone,
GatewayNetworkID: req.GatewayNetworkID,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[ns.Status]
return ns, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for gateway network failed")
}
return gatewayNetwork.(*GatewayNetwork), nil
}
// WaitForDHCPEntriesRequest is used by WaitForDHCPEntries method
type WaitForDHCPEntriesRequest struct {
GatewayNetworkID *string
MacAddress string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForDHCPEntries waits for at least one dhcp entry with the correct mac address.
// This function can be used to wait for an instance to use dhcp
func (s *API) WaitForDHCPEntries(req *WaitForDHCPEntriesRequest, opts ...scw.RequestOption) (*ListDHCPEntriesResponse, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
dhcpEntries, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
entries, err := s.ListDHCPEntries(&ListDHCPEntriesRequest{
Zone: req.Zone,
GatewayNetworkID: req.GatewayNetworkID,
MacAddress: &req.MacAddress,
}, opts...)
if err != nil {
return nil, false, err
}
containsMacAddress := false
for _, entry := range entries.DHCPEntries {
if entry.MacAddress == req.MacAddress {
containsMacAddress = true
break
}
}
return entries, containsMacAddress, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for gateway network failed")
}
return dhcpEntries.(*ListDHCPEntriesResponse), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v2/ 0000775 0000000 0000000 00000000000 14747113137 0024472 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/vpcgw/v2/vpcgw_sdk.go 0000664 0000000 0000000 00000167347 14747113137 0027032 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package vpcgw provides methods and message types of the vpcgw v2 API.
package vpcgw
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type GatewayNetworkStatus string
const (
GatewayNetworkStatusUnknownStatus = GatewayNetworkStatus("unknown_status")
GatewayNetworkStatusCreated = GatewayNetworkStatus("created")
GatewayNetworkStatusAttaching = GatewayNetworkStatus("attaching")
GatewayNetworkStatusConfiguring = GatewayNetworkStatus("configuring")
GatewayNetworkStatusReady = GatewayNetworkStatus("ready")
GatewayNetworkStatusDetaching = GatewayNetworkStatus("detaching")
)
func (enum GatewayNetworkStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum GatewayNetworkStatus) Values() []GatewayNetworkStatus {
return []GatewayNetworkStatus{
"unknown_status",
"created",
"attaching",
"configuring",
"ready",
"detaching",
}
}
func (enum GatewayNetworkStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GatewayNetworkStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GatewayNetworkStatus(GatewayNetworkStatus(tmp).String())
return nil
}
type GatewayStatus string
const (
GatewayStatusUnknownStatus = GatewayStatus("unknown_status")
GatewayStatusStopped = GatewayStatus("stopped")
GatewayStatusAllocating = GatewayStatus("allocating")
GatewayStatusConfiguring = GatewayStatus("configuring")
GatewayStatusRunning = GatewayStatus("running")
GatewayStatusStopping = GatewayStatus("stopping")
GatewayStatusFailed = GatewayStatus("failed")
GatewayStatusDeleting = GatewayStatus("deleting")
GatewayStatusLocked = GatewayStatus("locked")
)
func (enum GatewayStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum GatewayStatus) Values() []GatewayStatus {
return []GatewayStatus{
"unknown_status",
"stopped",
"allocating",
"configuring",
"running",
"stopping",
"failed",
"deleting",
"locked",
}
}
func (enum GatewayStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *GatewayStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = GatewayStatus(GatewayStatus(tmp).String())
return nil
}
type ListGatewayNetworksRequestOrderBy string
const (
ListGatewayNetworksRequestOrderByCreatedAtAsc = ListGatewayNetworksRequestOrderBy("created_at_asc")
ListGatewayNetworksRequestOrderByCreatedAtDesc = ListGatewayNetworksRequestOrderBy("created_at_desc")
ListGatewayNetworksRequestOrderByStatusAsc = ListGatewayNetworksRequestOrderBy("status_asc")
ListGatewayNetworksRequestOrderByStatusDesc = ListGatewayNetworksRequestOrderBy("status_desc")
)
func (enum ListGatewayNetworksRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListGatewayNetworksRequestOrderBy) Values() []ListGatewayNetworksRequestOrderBy {
return []ListGatewayNetworksRequestOrderBy{
"created_at_asc",
"created_at_desc",
"status_asc",
"status_desc",
}
}
func (enum ListGatewayNetworksRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGatewayNetworksRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGatewayNetworksRequestOrderBy(ListGatewayNetworksRequestOrderBy(tmp).String())
return nil
}
type ListGatewaysRequestOrderBy string
const (
ListGatewaysRequestOrderByCreatedAtAsc = ListGatewaysRequestOrderBy("created_at_asc")
ListGatewaysRequestOrderByCreatedAtDesc = ListGatewaysRequestOrderBy("created_at_desc")
ListGatewaysRequestOrderByNameAsc = ListGatewaysRequestOrderBy("name_asc")
ListGatewaysRequestOrderByNameDesc = ListGatewaysRequestOrderBy("name_desc")
ListGatewaysRequestOrderByTypeAsc = ListGatewaysRequestOrderBy("type_asc")
ListGatewaysRequestOrderByTypeDesc = ListGatewaysRequestOrderBy("type_desc")
ListGatewaysRequestOrderByStatusAsc = ListGatewaysRequestOrderBy("status_asc")
ListGatewaysRequestOrderByStatusDesc = ListGatewaysRequestOrderBy("status_desc")
)
func (enum ListGatewaysRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListGatewaysRequestOrderBy) Values() []ListGatewaysRequestOrderBy {
return []ListGatewaysRequestOrderBy{
"created_at_asc",
"created_at_desc",
"name_asc",
"name_desc",
"type_asc",
"type_desc",
"status_asc",
"status_desc",
}
}
func (enum ListGatewaysRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListGatewaysRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListGatewaysRequestOrderBy(ListGatewaysRequestOrderBy(tmp).String())
return nil
}
type ListIPsRequestOrderBy string
const (
ListIPsRequestOrderByCreatedAtAsc = ListIPsRequestOrderBy("created_at_asc")
ListIPsRequestOrderByCreatedAtDesc = ListIPsRequestOrderBy("created_at_desc")
ListIPsRequestOrderByAddressAsc = ListIPsRequestOrderBy("address_asc")
ListIPsRequestOrderByAddressDesc = ListIPsRequestOrderBy("address_desc")
ListIPsRequestOrderByReverseAsc = ListIPsRequestOrderBy("reverse_asc")
ListIPsRequestOrderByReverseDesc = ListIPsRequestOrderBy("reverse_desc")
)
func (enum ListIPsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListIPsRequestOrderBy) Values() []ListIPsRequestOrderBy {
return []ListIPsRequestOrderBy{
"created_at_asc",
"created_at_desc",
"address_asc",
"address_desc",
"reverse_asc",
"reverse_desc",
}
}
func (enum ListIPsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListIPsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListIPsRequestOrderBy(ListIPsRequestOrderBy(tmp).String())
return nil
}
type ListPatRulesRequestOrderBy string
const (
ListPatRulesRequestOrderByCreatedAtAsc = ListPatRulesRequestOrderBy("created_at_asc")
ListPatRulesRequestOrderByCreatedAtDesc = ListPatRulesRequestOrderBy("created_at_desc")
ListPatRulesRequestOrderByPublicPortAsc = ListPatRulesRequestOrderBy("public_port_asc")
ListPatRulesRequestOrderByPublicPortDesc = ListPatRulesRequestOrderBy("public_port_desc")
)
func (enum ListPatRulesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListPatRulesRequestOrderBy) Values() []ListPatRulesRequestOrderBy {
return []ListPatRulesRequestOrderBy{
"created_at_asc",
"created_at_desc",
"public_port_asc",
"public_port_desc",
}
}
func (enum ListPatRulesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListPatRulesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListPatRulesRequestOrderBy(ListPatRulesRequestOrderBy(tmp).String())
return nil
}
type PatRuleProtocol string
const (
PatRuleProtocolUnknownProtocol = PatRuleProtocol("unknown_protocol")
PatRuleProtocolBoth = PatRuleProtocol("both")
PatRuleProtocolTCP = PatRuleProtocol("tcp")
PatRuleProtocolUDP = PatRuleProtocol("udp")
)
func (enum PatRuleProtocol) String() string {
if enum == "" {
// return default value if empty
return "unknown_protocol"
}
return string(enum)
}
func (enum PatRuleProtocol) Values() []PatRuleProtocol {
return []PatRuleProtocol{
"unknown_protocol",
"both",
"tcp",
"udp",
}
}
func (enum PatRuleProtocol) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PatRuleProtocol) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PatRuleProtocol(PatRuleProtocol(tmp).String())
return nil
}
// GatewayNetwork: gateway network.
type GatewayNetwork struct {
// ID: ID of the Public Gateway-Private Network connection.
ID string `json:"id"`
// CreatedAt: connection creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: connection last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// GatewayID: ID of the connected Public Gateway.
GatewayID string `json:"gateway_id"`
// PrivateNetworkID: ID of the connected Private Network.
PrivateNetworkID string `json:"private_network_id"`
// MacAddress: mAC address of the gateway in the Private Network (if the gateway is up and running).
MacAddress *string `json:"mac_address"`
// MasqueradeEnabled: defines whether the gateway masquerades traffic for this Private Network (Dynamic NAT).
MasqueradeEnabled bool `json:"masquerade_enabled"`
// Status: current status of the Public Gateway's connection to the Private Network.
// Default value: unknown_status
Status GatewayNetworkStatus `json:"status"`
// PushDefaultRoute: enabling the default route also enables masquerading.
PushDefaultRoute bool `json:"push_default_route"`
// IpamIPID: use this IPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID string `json:"ipam_ip_id"`
// Zone: zone of the GatewayNetwork connection.
Zone scw.Zone `json:"zone"`
}
// IP: ip.
type IP struct {
// ID: IP address ID.
ID string `json:"id"`
// OrganizationID: owning Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: owning Project.
ProjectID string `json:"project_id"`
// CreatedAt: IP address creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: IP address last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Tags: tags associated with the IP address.
Tags []string `json:"tags"`
// Address: the IP address itself.
Address net.IP `json:"address"`
// Reverse: reverse domain name for the IP address.
Reverse *string `json:"reverse"`
// GatewayID: public Gateway associated with the IP address.
GatewayID *string `json:"gateway_id"`
// Zone: zone of the IP address.
Zone scw.Zone `json:"zone"`
}
// GatewayType: gateway type.
type GatewayType struct {
// Name: public Gateway type name.
Name string `json:"name"`
// Bandwidth: bandwidth, in bps, of the Public Gateway. This is the public bandwidth to the outer Internet, and the internal bandwidth to each connected Private Networks.
Bandwidth uint64 `json:"bandwidth"`
// Zone: zone the Public Gateway type is available in.
Zone scw.Zone `json:"zone"`
}
// Gateway: gateway.
type Gateway struct {
// ID: ID of the gateway.
ID string `json:"id"`
// OrganizationID: owning Organization.
OrganizationID string `json:"organization_id"`
// ProjectID: owning Project.
ProjectID string `json:"project_id"`
// CreatedAt: gateway creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: gateway last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// Type: gateway type name (commercial offer).
Type string `json:"type"`
// Bandwidth: bandwidth available of the gateway.
Bandwidth uint64 `json:"bandwidth"`
// Status: current status of the gateway.
// Default value: unknown_status
Status GatewayStatus `json:"status"`
// Name: name of the gateway.
Name string `json:"name"`
// Tags: tags associated with the gateway.
Tags []string `json:"tags"`
// IPv4: public IPv4 address of the gateway.
IPv4 *IP `json:"ipv4"`
// GatewayNetworks: gatewayNetwork objects attached to the gateway (each one represents a connection to a Private Network).
GatewayNetworks []*GatewayNetwork `json:"gateway_networks"`
// Version: version of the running gateway software.
Version *string `json:"version"`
// CanUpgradeTo: newly available gateway software version that can be updated to.
CanUpgradeTo *string `json:"can_upgrade_to"`
// BastionEnabled: defines whether SSH bastion is enabled on the gateway.
BastionEnabled bool `json:"bastion_enabled"`
// BastionPort: port of the SSH bastion.
BastionPort uint32 `json:"bastion_port"`
// SMTPEnabled: defines whether SMTP traffic is allowed to pass through the gateway.
SMTPEnabled bool `json:"smtp_enabled"`
// IsLegacy: defines whether the gateway uses non-IPAM IP configurations.
IsLegacy bool `json:"is_legacy"`
// BastionAllowedIPs: ranges of IP addresses allowed to connect to the gateway's SSH bastion.
BastionAllowedIPs []scw.IPNet `json:"bastion_allowed_ips"`
// Zone: zone of the gateway.
Zone scw.Zone `json:"zone"`
}
// PatRule: pat rule.
type PatRule struct {
// ID: pAT rule ID.
ID string `json:"id"`
// GatewayID: gateway the PAT rule applies to.
GatewayID string `json:"gateway_id"`
// CreatedAt: pAT rule creation date.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: pAT rule last modification date.
UpdatedAt *time.Time `json:"updated_at"`
// PublicPort: public port to listen on.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP address to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule applies to.
// Default value: unknown_protocol
Protocol PatRuleProtocol `json:"protocol"`
// Zone: zone of the PAT rule.
Zone scw.Zone `json:"zone"`
}
// SetPatRulesRequestRule: set pat rules request rule.
type SetPatRulesRequestRule struct {
// PublicPort: public port to listen on. Uniquely identifies the rule, and a matching rule will be updated with the new parameters.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule should apply to.
// Default value: unknown_protocol
Protocol PatRuleProtocol `json:"protocol"`
}
// AddBastionAllowedIPsRequest: add bastion allowed i ps request.
type AddBastionAllowedIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to add the allowed IP range to.
GatewayID string `json:"-"`
// IPRange: IP range allowed to connect to the SSH bastion.
IPRange scw.IPNet `json:"ip_range"`
}
// AddBastionAllowedIPsResponse: add bastion allowed i ps response.
type AddBastionAllowedIPsResponse struct {
// IPRanges: ranges of IP addresses allowed to connect to the gateway's SSH bastion.
IPRanges []scw.IPNet `json:"ip_ranges"`
}
// CreateGatewayNetworkRequest: create gateway network request.
type CreateGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: public Gateway to connect.
GatewayID string `json:"gateway_id"`
// PrivateNetworkID: private Network to connect.
PrivateNetworkID string `json:"private_network_id"`
// EnableMasquerade: defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork.
EnableMasquerade bool `json:"enable_masquerade"`
// PushDefaultRoute: enabling the default route also enables masquerading.
PushDefaultRoute bool `json:"push_default_route"`
// IpamIPID: use this IPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID *string `json:"ipam_ip_id,omitempty"`
}
// CreateGatewayRequest: create gateway request.
type CreateGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: scaleway Project to create the gateway in.
ProjectID string `json:"project_id"`
// Name: name for the gateway.
Name string `json:"name"`
// Tags: tags for the gateway.
Tags []string `json:"tags"`
// Type: gateway type (commercial offer type).
Type string `json:"type"`
// IPID: existing IP address to attach to the gateway.
IPID *string `json:"ip_id,omitempty"`
// EnableSMTP: defines whether SMTP traffic should be allowed pass through the gateway.
EnableSMTP bool `json:"enable_smtp"`
// EnableBastion: defines whether SSH bastion should be enabled the gateway.
EnableBastion bool `json:"enable_bastion"`
// BastionPort: port of the SSH bastion.
BastionPort *uint32 `json:"bastion_port,omitempty"`
}
// CreateIPRequest: create ip request.
type CreateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// ProjectID: project to create the IP address in.
ProjectID string `json:"project_id"`
// Tags: tags to give to the IP address.
Tags []string `json:"tags"`
}
// CreatePatRuleRequest: create pat rule request.
type CreatePatRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the Gateway on which to create the rule.
GatewayID string `json:"gateway_id"`
// PublicPort: public port to listen on.
PublicPort uint32 `json:"public_port"`
// PrivateIP: private IP to forward data to.
PrivateIP net.IP `json:"private_ip"`
// PrivatePort: private port to translate to.
PrivatePort uint32 `json:"private_port"`
// Protocol: protocol the rule should apply to.
// Default value: unknown_protocol
Protocol PatRuleProtocol `json:"protocol"`
}
// DeleteBastionAllowedIPsRequest: delete bastion allowed i ps request.
type DeleteBastionAllowedIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway on which to delete the allowed IP range.
GatewayID string `json:"-"`
// IPRange: IP range to delete from SSH bastion's list of allowed IPs.
IPRange scw.IPNet `json:"-"`
}
// DeleteGatewayNetworkRequest: delete gateway network request.
type DeleteGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to delete.
GatewayNetworkID string `json:"-"`
}
// DeleteGatewayRequest: delete gateway request.
type DeleteGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to delete.
GatewayID string `json:"-"`
// DeleteIP: defines whether the PGW's IP should be deleted.
DeleteIP bool `json:"delete_ip"`
}
// DeleteIPRequest: delete ip request.
type DeleteIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to delete.
IPID string `json:"-"`
}
// DeletePatRuleRequest: delete pat rule request.
type DeletePatRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to delete.
PatRuleID string `json:"-"`
}
// GetGatewayNetworkRequest: get gateway network request.
type GetGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to fetch.
GatewayNetworkID string `json:"-"`
}
// GetGatewayRequest: get gateway request.
type GetGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to fetch.
GatewayID string `json:"-"`
}
// GetIPRequest: get ip request.
type GetIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to get.
IPID string `json:"-"`
}
// GetPatRuleRequest: get pat rule request.
type GetPatRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to get.
PatRuleID string `json:"-"`
}
// ListGatewayNetworksRequest: list gateway networks request.
type ListGatewayNetworksRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListGatewayNetworksRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: gatewayNetworks per page.
PageSize *uint32 `json:"-"`
// Status: filter for GatewayNetworks with these status. Use `unknown` to include all statuses.
Status []GatewayNetworkStatus `json:"-"`
// GatewayIDs: filter for GatewayNetworks connected to these gateways.
GatewayIDs []string `json:"-"`
// PrivateNetworkIDs: filter for GatewayNetworks connected to these Private Networks.
PrivateNetworkIDs []string `json:"-"`
// MasqueradeEnabled: filter for GatewayNetworks with this `enable_masquerade` setting.
MasqueradeEnabled *bool `json:"-"`
}
// ListGatewayNetworksResponse: list gateway networks response.
type ListGatewayNetworksResponse struct {
// GatewayNetworks: gatewayNetworks on this page.
GatewayNetworks []*GatewayNetwork `json:"gateway_networks"`
// TotalCount: total GatewayNetworks count matching the filter.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGatewayNetworksResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGatewayNetworksResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListGatewayNetworksResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.GatewayNetworks = append(r.GatewayNetworks, results.GatewayNetworks...)
r.TotalCount += uint64(len(results.GatewayNetworks))
return uint64(len(results.GatewayNetworks)), nil
}
// ListGatewayTypesRequest: list gateway types request.
type ListGatewayTypesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
}
// ListGatewayTypesResponse: list gateway types response.
type ListGatewayTypesResponse struct {
// Types: available types of Public Gateway.
Types []*GatewayType `json:"types"`
}
// ListGatewaysRequest: list gateways request.
type ListGatewaysRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListGatewaysRequestOrderBy `json:"-"`
// Page: page number to return.
Page *int32 `json:"-"`
// PageSize: gateways per page.
PageSize *uint32 `json:"-"`
// OrganizationID: include only gateways in this Organization.
OrganizationID *string `json:"-"`
// ProjectID: include only gateways in this Project.
ProjectID *string `json:"-"`
// Name: filter for gateways which have this search term in their name.
Name *string `json:"-"`
// Tags: filter for gateways with these tags.
Tags []string `json:"-"`
// Types: filter for gateways of these types.
Types []string `json:"-"`
// Status: filter for gateways with these status. Use `unknown` to include all statuses.
Status []GatewayStatus `json:"-"`
// PrivateNetworkIDs: filter for gateways attached to these Private Networks.
PrivateNetworkIDs []string `json:"-"`
// IncludeLegacy: include also legacy gateways.
IncludeLegacy *bool `json:"-"`
}
// ListGatewaysResponse: list gateways response.
type ListGatewaysResponse struct {
// Gateways: gateways on this page.
Gateways []*Gateway `json:"gateways"`
// TotalCount: total count of gateways matching the filter.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListGatewaysResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListGatewaysResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListGatewaysResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Gateways = append(r.Gateways, results.Gateways...)
r.TotalCount += uint64(len(results.Gateways))
return uint64(len(results.Gateways)), nil
}
// ListIPsRequest: list i ps request.
type ListIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListIPsRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: IP addresses per page.
PageSize *uint32 `json:"-"`
// OrganizationID: include only gateways in this Organization.
OrganizationID *string `json:"-"`
// ProjectID: filter for IP addresses in this Project.
ProjectID *string `json:"-"`
// Tags: filter for IP addresses with these tags.
Tags []string `json:"-"`
// Reverse: filter for IP addresses that have a reverse containing this string.
Reverse *string `json:"-"`
// IsFree: filter based on whether the IP is attached to a gateway or not.
IsFree *bool `json:"-"`
}
// ListIPsResponse: list i ps response.
type ListIPsResponse struct {
// IPs: IP addresses on this page.
IPs []*IP `json:"ips"`
// TotalCount: total count of IP addresses matching the filter.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListIPsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.IPs = append(r.IPs, results.IPs...)
r.TotalCount += uint64(len(results.IPs))
return uint64(len(results.IPs)), nil
}
// ListPatRulesRequest: list pat rules request.
type ListPatRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// OrderBy: order in which to return results.
// Default value: created_at_asc
OrderBy ListPatRulesRequestOrderBy `json:"-"`
// Page: page number.
Page *int32 `json:"-"`
// PageSize: pAT rules per page.
PageSize *uint32 `json:"-"`
// GatewayIDs: filter for PAT rules on these gateways.
GatewayIDs []string `json:"-"`
// PrivateIPs: filter for PAT rules targeting these private ips.
PrivateIPs []string `json:"-"`
// Protocol: filter for PAT rules with this protocol.
// Default value: unknown_protocol
Protocol PatRuleProtocol `json:"-"`
}
// ListPatRulesResponse: list pat rules response.
type ListPatRulesResponse struct {
// PatRules: array of PAT rules matching the filter.
PatRules []*PatRule `json:"pat_rules"`
// TotalCount: total count of PAT rules matching the filter.
TotalCount uint64 `json:"total_count"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListPatRulesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListPatRulesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListPatRulesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.PatRules = append(r.PatRules, results.PatRules...)
r.TotalCount += uint64(len(results.PatRules))
return uint64(len(results.PatRules)), nil
}
// RefreshSSHKeysRequest: refresh ssh keys request.
type RefreshSSHKeysRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to refresh SSH keys on.
GatewayID string `json:"-"`
}
// SetBastionAllowedIPsRequest: set bastion allowed i ps request.
type SetBastionAllowedIPsRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway on which to set the allowed IP range.
GatewayID string `json:"-"`
// IPRanges: new list of IP ranges (each range in CIDR notation) allowed to connect to the SSH bastion.
IPRanges []string `json:"ip_ranges"`
}
// SetBastionAllowedIPsResponse: set bastion allowed i ps response.
type SetBastionAllowedIPsResponse struct {
// IPRanges: ranges of IP addresses allowed to connect to the gateway's SSH bastion.
IPRanges []scw.IPNet `json:"ip_ranges"`
}
// SetPatRulesRequest: set pat rules request.
type SetPatRulesRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway on which to set the PAT rules.
GatewayID string `json:"gateway_id"`
// PatRules: new list of PAT rules.
PatRules []*SetPatRulesRequestRule `json:"pat_rules"`
}
// SetPatRulesResponse: set pat rules response.
type SetPatRulesResponse struct {
// PatRules: list of PAT rules.
PatRules []*PatRule `json:"pat_rules"`
}
// UpdateGatewayNetworkRequest: update gateway network request.
type UpdateGatewayNetworkRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayNetworkID: ID of the GatewayNetwork to update.
GatewayNetworkID string `json:"-"`
// EnableMasquerade: defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork.
EnableMasquerade *bool `json:"enable_masquerade,omitempty"`
// PushDefaultRoute: enabling the default route also enables masquerading.
PushDefaultRoute *bool `json:"push_default_route,omitempty"`
// IpamIPID: use this IPAM-booked IP ID as the Gateway's IP in this Private Network.
IpamIPID *string `json:"ipam_ip_id,omitempty"`
}
// UpdateGatewayRequest: update gateway request.
type UpdateGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to update.
GatewayID string `json:"-"`
// Name: name for the gateway.
Name *string `json:"name,omitempty"`
// Tags: tags for the gateway.
Tags *[]string `json:"tags,omitempty"`
// EnableBastion: defines whether SSH bastion should be enabled the gateway.
EnableBastion *bool `json:"enable_bastion,omitempty"`
// BastionPort: port of the SSH bastion.
BastionPort *uint32 `json:"bastion_port,omitempty"`
// EnableSMTP: defines whether SMTP traffic should be allowed to pass through the gateway.
EnableSMTP *bool `json:"enable_smtp,omitempty"`
}
// UpdateIPRequest: update ip request.
type UpdateIPRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// IPID: ID of the IP address to update.
IPID string `json:"-"`
// Tags: tags to give to the IP address.
Tags *[]string `json:"tags,omitempty"`
// Reverse: reverse to set on the address. Empty string to unset.
Reverse *string `json:"reverse,omitempty"`
// GatewayID: gateway to attach the IP address to. Empty string to detach.
GatewayID *string `json:"gateway_id,omitempty"`
}
// UpdatePatRuleRequest: update pat rule request.
type UpdatePatRuleRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// PatRuleID: ID of the PAT rule to update.
PatRuleID string `json:"-"`
// PublicPort: public port to listen on.
PublicPort *uint32 `json:"public_port,omitempty"`
// PrivateIP: private IP to forward data to.
PrivateIP *net.IP `json:"private_ip,omitempty"`
// PrivatePort: private port to translate to.
PrivatePort *uint32 `json:"private_port,omitempty"`
// Protocol: protocol the rule should apply to.
// Default value: unknown_protocol
Protocol PatRuleProtocol `json:"protocol"`
}
// UpgradeGatewayRequest: upgrade gateway request.
type UpgradeGatewayRequest struct {
// Zone: zone to target. If none is passed will use default zone from the config.
Zone scw.Zone `json:"-"`
// GatewayID: ID of the gateway to upgrade.
GatewayID string `json:"-"`
// Type: gateway type (commercial offer).
Type *string `json:"type,omitempty"`
}
// This API allows you to manage your Public Gateways.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Zones() []scw.Zone {
return []scw.Zone{scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3}
}
// ListGateways: List Public Gateways in a given Scaleway Organization or Project. By default, results are displayed in ascending order of creation date.
func (s *API) ListGateways(req *ListGatewaysRequest, opts ...scw.RequestOption) (*ListGatewaysResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "name", req.Name)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "types", req.Types)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "private_network_ids", req.PrivateNetworkIDs)
parameter.AddToQuery(query, "include_legacy", req.IncludeLegacy)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways",
Query: query,
}
var resp ListGatewaysResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGateway: Get details of a Public Gateway, specified by its gateway ID. The response object contains full details of the gateway, including its **name**, **type**, **status** and more.
func (s *API) GetGateway(req *GetGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateGateway: Create a new Public Gateway in the specified Scaleway Project, defining its **name**, **type** and other configuration details such as whether to enable SSH bastion.
func (s *API) CreateGateway(req *CreateGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if req.Name == "" {
req.Name = namegenerator.GetRandomName("gw")
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateGateway: Update the parameters of an existing Public Gateway, for example, its **name**, **tags**, **SSH bastion configuration**, and **DNS servers**.
func (s *API) UpdateGateway(req *UpdateGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGateway: Delete an existing Public Gateway, specified by its gateway ID. This action is irreversible.
func (s *API) DeleteGateway(req *DeleteGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
query := url.Values{}
parameter.AddToQuery(query, "delete_ip", req.DeleteIP)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "",
Query: query,
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpgradeGateway: Upgrade a given Public Gateway to the newest software version or to a different commercial offer type. This applies the latest bugfixes and features to your Public Gateway. Note that gateway service will be interrupted during the update.
func (s *API) UpgradeGateway(req *UpgradeGatewayRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/upgrade",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListGatewayNetworks: List the connections between Public Gateways and Private Networks (a connection = a GatewayNetwork). You can choose to filter by `gateway-id` to list all Private Networks attached to the specified Public Gateway, or by `private_network_id` to list all Public Gateways attached to the specified Private Network. Other query parameters are also available. The result is an array of GatewayNetwork objects, each giving details of the connection between a given Public Gateway and a given Private Network.
func (s *API) ListGatewayNetworks(req *ListGatewayNetworksRequest, opts ...scw.RequestOption) (*ListGatewayNetworksResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "status", req.Status)
parameter.AddToQuery(query, "gateway_ids", req.GatewayIDs)
parameter.AddToQuery(query, "private_network_ids", req.PrivateNetworkIDs)
parameter.AddToQuery(query, "masquerade_enabled", req.MasqueradeEnabled)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks",
Query: query,
}
var resp ListGatewayNetworksResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetGatewayNetwork: Get details of a given connection between a Public Gateway and a Private Network (this connection = a GatewayNetwork), specified by its `gateway_network_id`. The response object contains details of the connection including the IDs of the Public Gateway and Private Network, the dates the connection was created/updated and its configuration settings.
func (s *API) GetGatewayNetwork(req *GetGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return nil, errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateGatewayNetwork: Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including whether to enable masquerade (dynamic NAT), and more.
func (s *API) CreateGatewayNetwork(req *CreateGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateGatewayNetwork: Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include whether to enable traffic masquerade (dynamic NAT).
func (s *API) UpdateGatewayNetwork(req *UpdateGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return nil, errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteGatewayNetwork: Detach a given Public Gateway from a given Private Network, i.e. delete a GatewayNetwork specified by a gateway_network_id.
func (s *API) DeleteGatewayNetwork(req *DeleteGatewayNetworkRequest, opts ...scw.RequestOption) (*GatewayNetwork, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayNetworkID) == "" {
return nil, errors.New("field GatewayNetworkID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-networks/" + fmt.Sprint(req.GatewayNetworkID) + "",
}
var resp GatewayNetwork
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListPatRules: List PAT rules. You can filter by gateway ID to list all PAT rules for a particular gateway, or filter for PAT rules targeting a specific IP address or using a specific protocol.
func (s *API) ListPatRules(req *ListPatRulesRequest, opts ...scw.RequestOption) (*ListPatRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "gateway_ids", req.GatewayIDs)
parameter.AddToQuery(query, "private_ips", req.PrivateIPs)
parameter.AddToQuery(query, "protocol", req.Protocol)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
Query: query,
}
var resp ListPatRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetPatRule: Get a PAT rule, specified by its PAT rule ID. The response object gives full details of the PAT rule, including the Public Gateway it belongs to and the configuration settings in terms of public / private ports, private IP and protocol.
func (s *API) GetPatRule(req *GetPatRuleRequest, opts ...scw.RequestOption) (*PatRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return nil, errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
var resp PatRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreatePatRule: Create a new PAT rule on a specified Public Gateway, defining the protocol to use, public port to listen on, and private port / IP address to map to.
func (s *API) CreatePatRule(req *CreatePatRuleRequest, opts ...scw.RequestOption) (*PatRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PatRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdatePatRule: Update a PAT rule, specified by its PAT rule ID. Configuration settings including private/public port, private IP address and protocol can all be updated.
func (s *API) UpdatePatRule(req *UpdatePatRuleRequest, opts ...scw.RequestOption) (*PatRule, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return nil, errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp PatRule
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetPatRules: Set a definitive list of PAT rules attached to a Public Gateway. Each rule is identified by its public port and protocol. This will sync the current PAT rule list on the gateway with the new list, creating, updating or deleting PAT rules accordingly.
func (s *API) SetPatRules(req *SetPatRulesRequest, opts ...scw.RequestOption) (*SetPatRulesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetPatRulesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeletePatRule: Delete a PAT rule, identified by its PAT rule ID. This action is irreversible.
func (s *API) DeletePatRule(req *DeletePatRuleRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.PatRuleID) == "" {
return errors.New("field PatRuleID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/pat-rules/" + fmt.Sprint(req.PatRuleID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// ListGatewayTypes: List the different Public Gateway commercial offer types available at Scaleway. The response is an array of objects describing the name and technical details of each available gateway type.
func (s *API) ListGatewayTypes(req *ListGatewayTypesRequest, opts ...scw.RequestOption) (*ListGatewayTypesResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateway-types",
}
var resp ListGatewayTypesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListIPs: List Public Gateway flexible IP addresses. A number of filter options are available for limiting results in the response.
func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "reverse", req.Reverse)
parameter.AddToQuery(query, "is_free", req.IsFree)
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/ips",
Query: query,
}
var resp ListIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetIP: Get details of a Public Gateway flexible IP address, identified by its IP ID. The response object contains information including which (if any) Public Gateway using this IP address, the reverse and various other metadata.
func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateIP: Create (reserve) a new flexible IP address that can be used for a Public Gateway in a specified Scaleway Project.
func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateIP: Update details of an existing flexible IP address, including its tags, reverse and the Public Gateway it is assigned to.
func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*IP, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return nil, errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp IP
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteIP: Delete a flexible IP address from your account. This action is irreversible.
func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.IPID) == "" {
return errors.New("field IPID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IPID) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// RefreshSSHKeys: Refresh the SSH keys of a given Public Gateway, specified by its gateway ID. This adds any new SSH keys in the gateway's Scaleway Project to the gateway itself.
func (s *API) RefreshSSHKeys(req *RefreshSSHKeysRequest, opts ...scw.RequestOption) (*Gateway, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/refresh-ssh-keys",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Gateway
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AddBastionAllowedIPs: Add an IP range (in CIDR notation) to be allowed to connect to the SSH bastion.
func (s *API) AddBastionAllowedIPs(req *AddBastionAllowedIPsRequest, opts ...scw.RequestOption) (*AddBastionAllowedIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/bastion-allowed-ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp AddBastionAllowedIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SetBastionAllowedIPs: Set a definitive list of IP ranges (in CIDR notation) allowed to connect to the SSH bastion.
func (s *API) SetBastionAllowedIPs(req *SetBastionAllowedIPsRequest, opts ...scw.RequestOption) (*SetBastionAllowedIPsResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return nil, errors.New("field GatewayID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PUT",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/bastion-allowed-ips",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp SetBastionAllowedIPsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteBastionAllowedIPs: Delete an IP range (defined in CIDR notation) from SSH bastion, so that it is no longer allowed to connect.
func (s *API) DeleteBastionAllowedIPs(req *DeleteBastionAllowedIPsRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.GatewayID) == "" {
return errors.New("field GatewayID cannot be empty in request")
}
if fmt.Sprint(req.IPRange) == "" {
return errors.New("field IPRange cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/vpc-gw/v2/zones/" + fmt.Sprint(req.Zone) + "/gateways/" + fmt.Sprint(req.GatewayID) + "/bastion-allowed-ips/" + fmt.Sprint(req.IPRange) + "",
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/ 0000775 0000000 0000000 00000000000 14747113137 0025166 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1/ 0000775 0000000 0000000 00000000000 14747113137 0025514 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1/webhosting_sdk.go 0000664 0000000 0000000 00000262044 14747113137 0031065 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package webhosting provides methods and message types of the webhosting v1 API.
package webhosting
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
std "github.com/scaleway/scaleway-sdk-go/api/std"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DNSRecordStatus string
const (
DNSRecordStatusUnknownStatus = DNSRecordStatus("unknown_status")
DNSRecordStatusValid = DNSRecordStatus("valid")
DNSRecordStatusInvalid = DNSRecordStatus("invalid")
)
func (enum DNSRecordStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DNSRecordStatus) Values() []DNSRecordStatus {
return []DNSRecordStatus{
"unknown_status",
"valid",
"invalid",
}
}
func (enum DNSRecordStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordStatus(DNSRecordStatus(tmp).String())
return nil
}
type DNSRecordType string
const (
DNSRecordTypeUnknownType = DNSRecordType("unknown_type")
DNSRecordTypeA = DNSRecordType("a")
DNSRecordTypeCname = DNSRecordType("cname")
DNSRecordTypeMx = DNSRecordType("mx")
DNSRecordTypeTxt = DNSRecordType("txt")
DNSRecordTypeNs = DNSRecordType("ns")
DNSRecordTypeAaaa = DNSRecordType("aaaa")
)
func (enum DNSRecordType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum DNSRecordType) Values() []DNSRecordType {
return []DNSRecordType{
"unknown_type",
"a",
"cname",
"mx",
"txt",
"ns",
"aaaa",
}
}
func (enum DNSRecordType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordType(DNSRecordType(tmp).String())
return nil
}
type DNSRecordsStatus string
const (
DNSRecordsStatusUnknownStatus = DNSRecordsStatus("unknown_status")
DNSRecordsStatusValid = DNSRecordsStatus("valid")
DNSRecordsStatusInvalid = DNSRecordsStatus("invalid")
)
func (enum DNSRecordsStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DNSRecordsStatus) Values() []DNSRecordsStatus {
return []DNSRecordsStatus{
"unknown_status",
"valid",
"invalid",
}
}
func (enum DNSRecordsStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordsStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordsStatus(DNSRecordsStatus(tmp).String())
return nil
}
type HostingStatus string
const (
HostingStatusUnknownStatus = HostingStatus("unknown_status")
HostingStatusDelivering = HostingStatus("delivering")
HostingStatusReady = HostingStatus("ready")
HostingStatusDeleting = HostingStatus("deleting")
HostingStatusError = HostingStatus("error")
HostingStatusLocked = HostingStatus("locked")
HostingStatusMigrating = HostingStatus("migrating")
)
func (enum HostingStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum HostingStatus) Values() []HostingStatus {
return []HostingStatus{
"unknown_status",
"delivering",
"ready",
"deleting",
"error",
"locked",
"migrating",
}
}
func (enum HostingStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HostingStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HostingStatus(HostingStatus(tmp).String())
return nil
}
type HostingSummaryStatus string
const (
HostingSummaryStatusUnknownStatus = HostingSummaryStatus("unknown_status")
HostingSummaryStatusDelivering = HostingSummaryStatus("delivering")
HostingSummaryStatusReady = HostingSummaryStatus("ready")
HostingSummaryStatusDeleting = HostingSummaryStatus("deleting")
HostingSummaryStatusError = HostingSummaryStatus("error")
HostingSummaryStatusLocked = HostingSummaryStatus("locked")
HostingSummaryStatusMigrating = HostingSummaryStatus("migrating")
)
func (enum HostingSummaryStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum HostingSummaryStatus) Values() []HostingSummaryStatus {
return []HostingSummaryStatus{
"unknown_status",
"delivering",
"ready",
"deleting",
"error",
"locked",
"migrating",
}
}
func (enum HostingSummaryStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HostingSummaryStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HostingSummaryStatus(HostingSummaryStatus(tmp).String())
return nil
}
type ListDatabaseUsersRequestOrderBy string
const (
ListDatabaseUsersRequestOrderByUsernameAsc = ListDatabaseUsersRequestOrderBy("username_asc")
ListDatabaseUsersRequestOrderByUsernameDesc = ListDatabaseUsersRequestOrderBy("username_desc")
)
func (enum ListDatabaseUsersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "username_asc"
}
return string(enum)
}
func (enum ListDatabaseUsersRequestOrderBy) Values() []ListDatabaseUsersRequestOrderBy {
return []ListDatabaseUsersRequestOrderBy{
"username_asc",
"username_desc",
}
}
func (enum ListDatabaseUsersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabaseUsersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabaseUsersRequestOrderBy(ListDatabaseUsersRequestOrderBy(tmp).String())
return nil
}
type ListDatabasesRequestOrderBy string
const (
ListDatabasesRequestOrderByDatabaseNameAsc = ListDatabasesRequestOrderBy("database_name_asc")
ListDatabasesRequestOrderByDatabaseNameDesc = ListDatabasesRequestOrderBy("database_name_desc")
)
func (enum ListDatabasesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "database_name_asc"
}
return string(enum)
}
func (enum ListDatabasesRequestOrderBy) Values() []ListDatabasesRequestOrderBy {
return []ListDatabasesRequestOrderBy{
"database_name_asc",
"database_name_desc",
}
}
func (enum ListDatabasesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListDatabasesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListDatabasesRequestOrderBy(ListDatabasesRequestOrderBy(tmp).String())
return nil
}
type ListFtpAccountsRequestOrderBy string
const (
ListFtpAccountsRequestOrderByUsernameAsc = ListFtpAccountsRequestOrderBy("username_asc")
ListFtpAccountsRequestOrderByUsernameDesc = ListFtpAccountsRequestOrderBy("username_desc")
)
func (enum ListFtpAccountsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "username_asc"
}
return string(enum)
}
func (enum ListFtpAccountsRequestOrderBy) Values() []ListFtpAccountsRequestOrderBy {
return []ListFtpAccountsRequestOrderBy{
"username_asc",
"username_desc",
}
}
func (enum ListFtpAccountsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListFtpAccountsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListFtpAccountsRequestOrderBy(ListFtpAccountsRequestOrderBy(tmp).String())
return nil
}
type ListHostingsRequestOrderBy string
const (
ListHostingsRequestOrderByCreatedAtAsc = ListHostingsRequestOrderBy("created_at_asc")
ListHostingsRequestOrderByCreatedAtDesc = ListHostingsRequestOrderBy("created_at_desc")
)
func (enum ListHostingsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListHostingsRequestOrderBy) Values() []ListHostingsRequestOrderBy {
return []ListHostingsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListHostingsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListHostingsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListHostingsRequestOrderBy(ListHostingsRequestOrderBy(tmp).String())
return nil
}
type ListMailAccountsRequestOrderBy string
const (
ListMailAccountsRequestOrderByUsernameAsc = ListMailAccountsRequestOrderBy("username_asc")
ListMailAccountsRequestOrderByUsernameDesc = ListMailAccountsRequestOrderBy("username_desc")
ListMailAccountsRequestOrderByDomainAsc = ListMailAccountsRequestOrderBy("domain_asc")
ListMailAccountsRequestOrderByDomainDesc = ListMailAccountsRequestOrderBy("domain_desc")
)
func (enum ListMailAccountsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "username_asc"
}
return string(enum)
}
func (enum ListMailAccountsRequestOrderBy) Values() []ListMailAccountsRequestOrderBy {
return []ListMailAccountsRequestOrderBy{
"username_asc",
"username_desc",
"domain_asc",
"domain_desc",
}
}
func (enum ListMailAccountsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListMailAccountsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListMailAccountsRequestOrderBy(ListMailAccountsRequestOrderBy(tmp).String())
return nil
}
type ListOffersRequestOrderBy string
const (
ListOffersRequestOrderByPriceAsc = ListOffersRequestOrderBy("price_asc")
)
func (enum ListOffersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "price_asc"
}
return string(enum)
}
func (enum ListOffersRequestOrderBy) Values() []ListOffersRequestOrderBy {
return []ListOffersRequestOrderBy{
"price_asc",
}
}
func (enum ListOffersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListOffersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListOffersRequestOrderBy(ListOffersRequestOrderBy(tmp).String())
return nil
}
type ListWebsitesRequestOrderBy string
const (
ListWebsitesRequestOrderByDomainAsc = ListWebsitesRequestOrderBy("domain_asc")
ListWebsitesRequestOrderByDomainDesc = ListWebsitesRequestOrderBy("domain_desc")
)
func (enum ListWebsitesRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "domain_asc"
}
return string(enum)
}
func (enum ListWebsitesRequestOrderBy) Values() []ListWebsitesRequestOrderBy {
return []ListWebsitesRequestOrderBy{
"domain_asc",
"domain_desc",
}
}
func (enum ListWebsitesRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListWebsitesRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListWebsitesRequestOrderBy(ListWebsitesRequestOrderBy(tmp).String())
return nil
}
type NameserverStatus string
const (
NameserverStatusUnknownStatus = NameserverStatus("unknown_status")
NameserverStatusValid = NameserverStatus("valid")
NameserverStatusInvalid = NameserverStatus("invalid")
)
func (enum NameserverStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum NameserverStatus) Values() []NameserverStatus {
return []NameserverStatus{
"unknown_status",
"valid",
"invalid",
}
}
func (enum NameserverStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NameserverStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NameserverStatus(NameserverStatus(tmp).String())
return nil
}
type OfferOptionName string
const (
OfferOptionNameUnknownName = OfferOptionName("unknown_name")
OfferOptionNameDomainCount = OfferOptionName("domain_count")
OfferOptionNameEmailCount = OfferOptionName("email_count")
OfferOptionNameStorageGb = OfferOptionName("storage_gb")
OfferOptionNameVcpuCount = OfferOptionName("vcpu_count")
OfferOptionNameRAMGb = OfferOptionName("ram_gb")
OfferOptionNameBackup = OfferOptionName("backup")
OfferOptionNameDedicatedIP = OfferOptionName("dedicated_ip")
OfferOptionNameEmailStorageGb = OfferOptionName("email_storage_gb")
OfferOptionNameDatabaseCount = OfferOptionName("database_count")
OfferOptionNameSupport = OfferOptionName("support")
)
func (enum OfferOptionName) String() string {
if enum == "" {
// return default value if empty
return "unknown_name"
}
return string(enum)
}
func (enum OfferOptionName) Values() []OfferOptionName {
return []OfferOptionName{
"unknown_name",
"domain_count",
"email_count",
"storage_gb",
"vcpu_count",
"ram_gb",
"backup",
"dedicated_ip",
"email_storage_gb",
"database_count",
"support",
}
}
func (enum OfferOptionName) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferOptionName) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferOptionName(OfferOptionName(tmp).String())
return nil
}
type OfferOptionWarning string
const (
OfferOptionWarningUnknownWarning = OfferOptionWarning("unknown_warning")
OfferOptionWarningQuotaExceededWarning = OfferOptionWarning("quota_exceeded_warning")
OfferOptionWarningUsageLowWarning = OfferOptionWarning("usage_low_warning")
)
func (enum OfferOptionWarning) String() string {
if enum == "" {
// return default value if empty
return "unknown_warning"
}
return string(enum)
}
func (enum OfferOptionWarning) Values() []OfferOptionWarning {
return []OfferOptionWarning{
"unknown_warning",
"quota_exceeded_warning",
"usage_low_warning",
}
}
func (enum OfferOptionWarning) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferOptionWarning) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferOptionWarning(OfferOptionWarning(tmp).String())
return nil
}
type PlatformPlatformGroup string
const (
PlatformPlatformGroupUnknownGroup = PlatformPlatformGroup("unknown_group")
PlatformPlatformGroupDefault = PlatformPlatformGroup("default")
PlatformPlatformGroupPremium = PlatformPlatformGroup("premium")
)
func (enum PlatformPlatformGroup) String() string {
if enum == "" {
// return default value if empty
return "unknown_group"
}
return string(enum)
}
func (enum PlatformPlatformGroup) Values() []PlatformPlatformGroup {
return []PlatformPlatformGroup{
"unknown_group",
"default",
"premium",
}
}
func (enum PlatformPlatformGroup) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *PlatformPlatformGroup) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = PlatformPlatformGroup(PlatformPlatformGroup(tmp).String())
return nil
}
// PlatformControlPanelURLs: platform control panel ur ls.
type PlatformControlPanelURLs struct {
// Dashboard: URL to connect to the hosting control panel dashboard.
Dashboard string `json:"dashboard"`
// Webmail: URL to connect to the hosting Webmail interface.
Webmail string `json:"webmail"`
}
// OfferOption: offer option.
type OfferOption struct {
// ID: option ID.
ID string `json:"id"`
// Name: name of the option.
// Default value: unknown_name
Name OfferOptionName `json:"name"`
// BillingOperationPath: unique identifier used for billing.
BillingOperationPath string `json:"billing_operation_path"`
// MinValue: minimum value for the option in the offer.
MinValue int32 `json:"min_value"`
// CurrentValue: if a hosting_id was specified in the call, defines the current value of the option in the hosting.
CurrentValue int32 `json:"current_value"`
// MaxValue: maximum value for the option in the offer.
MaxValue int32 `json:"max_value"`
// QuotaWarning: defines a warning if the maximum value for the option has been reached.
// Default value: unknown_warning
QuotaWarning OfferOptionWarning `json:"quota_warning"`
// Price: price of the option for 1 value.
Price *scw.Money `json:"price"`
}
// PlatformControlPanel: platform control panel.
type PlatformControlPanel struct {
// Name: name of the control panel.
Name string `json:"name"`
// URLs: URL to connect to cPanel dashboard and to Webmail interface.
URLs *PlatformControlPanelURLs `json:"urls"`
}
// CreateDatabaseRequestUser: create database request user.
type CreateDatabaseRequestUser struct {
Username string `json:"username"`
Password string `json:"password"`
}
// CreateHostingRequestDomainConfiguration: create hosting request domain configuration.
type CreateHostingRequestDomainConfiguration struct {
UpdateNameservers bool `json:"update_nameservers"`
UpdateWebRecord bool `json:"update_web_record"`
UpdateMailRecord bool `json:"update_mail_record"`
UpdateAllRecords bool `json:"update_all_records"`
}
// OfferOptionRequest: offer option request.
type OfferOptionRequest struct {
// ID: offer option ID.
ID string `json:"id"`
// Quantity: the option requested quantity to set for the Web Hosting plan.
Quantity int64 `json:"quantity"`
}
// SyncDomainDNSRecordsRequestRecord: sync domain dns records request record.
type SyncDomainDNSRecordsRequestRecord struct {
Name string `json:"name"`
// Type: default value: unknown_type
Type DNSRecordType `json:"type"`
}
// DNSRecord: dns record.
type DNSRecord struct {
// Name: record name.
Name string `json:"name"`
// Type: record type.
// Default value: unknown_type
Type DNSRecordType `json:"type"`
// TTL: record time-to-live.
TTL uint32 `json:"ttl"`
// Value: record value.
Value string `json:"value"`
// Priority: record priority level.
Priority *uint32 `json:"priority"`
// Status: record status.
// Default value: unknown_status
Status DNSRecordStatus `json:"status"`
// RawData: record representation as it appears in the zone file or DNS management system.
RawData string `json:"raw_data"`
}
// Nameserver: nameserver.
type Nameserver struct {
// Hostname: hostname of the nameserver.
Hostname string `json:"hostname"`
// Status: status of the nameserver.
// Default value: unknown_status
Status NameserverStatus `json:"status"`
// IsDefault: defines whether the nameserver is the default one.
IsDefault bool `json:"is_default"`
}
// HostingUser: hosting user.
type HostingUser struct {
// Username: main Web Hosting cPanel username.
Username string `json:"username"`
// OneTimePassword: one-time-password used for the first login or reset password, empty after first use.
OneTimePassword *string `json:"one_time_password"`
// ContactEmail: contact email used for the hosting.
ContactEmail string `json:"contact_email"`
}
// Offer: offer.
type Offer struct {
// ID: offer ID.
ID string `json:"id"`
// Name: offer name.
Name string `json:"name"`
// BillingOperationPath: unique identifier used for billing.
BillingOperationPath string `json:"billing_operation_path"`
// Options: options available for the offer.
Options []*OfferOption `json:"options"`
// Price: price of the offer.
Price *scw.Money `json:"price"`
// Available: if a hosting_id was specified in the call, defines whether the offer is available for a specified hosting plan to migrate (update) to.
Available bool `json:"available"`
// ControlPanelName: name of the control panel.
ControlPanelName string `json:"control_panel_name"`
// EndOfLife: indicates if the offer has reached its end of life.
EndOfLife bool `json:"end_of_life"`
// QuotaWarning: defines a warning if the maximum value for an option in the offer is exceeded.
// Default value: unknown_warning
QuotaWarning OfferOptionWarning `json:"quota_warning"`
}
// Platform: platform.
type Platform struct {
// Hostname: hostname of the host platform.
Hostname string `json:"hostname"`
// Number: number of the host platform.
Number int32 `json:"number"`
// GroupName: group name of the hosting's host platform.
// Default value: unknown_group
GroupName PlatformPlatformGroup `json:"group_name"`
// IPv4: iPv4 address of the hosting's host platform.
IPv4 net.IP `json:"ipv4"`
// IPv6: iPv6 address of the hosting's host platform.
IPv6 net.IP `json:"ipv6"`
// ControlPanel: details of the platform control panel.
ControlPanel *PlatformControlPanel `json:"control_panel"`
}
// ControlPanel: control panel.
type ControlPanel struct {
// Name: control panel name.
Name string `json:"name"`
// Available: define if the control panel type is available to order.
Available bool `json:"available"`
// LogoURL: URL of the control panel's logo.
LogoURL string `json:"logo_url"`
// AvailableLanguages: list of available languages for the control panel.
AvailableLanguages []std.LanguageCode `json:"available_languages"`
}
// DatabaseUser: database user.
type DatabaseUser struct {
// Username: name of the database user.
Username string `json:"username"`
// Databases: list of databases accessible by the user.
Databases []string `json:"databases"`
}
// Database: database.
type Database struct {
// DatabaseName: name of the database.
DatabaseName string `json:"database_name"`
// Users: list of users who have access to the database.
Users []string `json:"users"`
}
// FtpAccount: ftp account.
type FtpAccount struct {
// Username: the username of the FTP account.
Username string `json:"username"`
// Path: the path associated with the FTP account.
Path string `json:"path"`
}
// HostingSummary: hosting summary.
type HostingSummary struct {
// ID: ID of the Web Hosting plan.
ID string `json:"id"`
// ProjectID: ID of the Scaleway Project the Web Hosting plan belongs to.
ProjectID string `json:"project_id"`
// CreatedAt: date on which the Web Hosting plan was created.
CreatedAt *time.Time `json:"created_at"`
// UpdatedAt: date on which the Web Hosting plan was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// Status: status of the Web Hosting plan.
// Default value: unknown_status
Status HostingSummaryStatus `json:"status"`
// Domain: main domain associated with the Web Hosting plan.
Domain string `json:"domain"`
// Protected: whether the hosting is protected or not.
Protected bool `json:"protected"`
// DNSStatus: DNS status of the Web Hosting plan.
// Default value: unknown_status
DNSStatus DNSRecordsStatus `json:"dns_status"`
// OfferName: name of the active offer for the Web Hosting plan.
OfferName string `json:"offer_name"`
// Region: region where the Web Hosting plan is hosted.
Region scw.Region `json:"region"`
}
// MailAccount: mail account.
type MailAccount struct {
// Domain: domain part of the mail account address.
Domain string `json:"domain"`
// Username: username part address of the mail account address.
Username string `json:"username"`
}
// Website: website.
type Website struct {
// Domain: the domain of the website.
Domain string `json:"domain"`
// Path: the directory path of the website.
Path string `json:"path"`
// SslStatus: the SSL status of the website.
SslStatus bool `json:"ssl_status"`
}
// CheckUserOwnsDomainResponse: check user owns domain response.
type CheckUserOwnsDomainResponse struct {
// OwnsDomain: indicates whether the specified project owns the domain.
OwnsDomain bool `json:"owns_domain"`
}
// ControlPanelAPIListControlPanelsRequest: control panel api list control panels request.
type ControlPanelAPIListControlPanelsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of control panels to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
}
// DNSAPICheckUserOwnsDomainRequest: dnsapi check user owns domain request.
type DNSAPICheckUserOwnsDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Domain: domain for which ownership is to be verified.
Domain string `json:"-"`
// ProjectID: ID of the project currently in use.
ProjectID string `json:"project_id"`
}
// DNSAPIGetDomainDNSRecordsRequest: dnsapi get domain dns records request.
type DNSAPIGetDomainDNSRecordsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Domain: domain associated with the DNS records.
Domain string `json:"-"`
}
// DNSAPISyncDomainDNSRecordsRequest: dnsapi sync domain dns records request.
type DNSAPISyncDomainDNSRecordsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Domain: domain for which the DNS records will be synchronized.
Domain string `json:"-"`
// UpdateWebRecords: whether or not to synchronize the web records.
UpdateWebRecords bool `json:"update_web_records"`
// UpdateMailRecords: whether or not to synchronize the mail records.
UpdateMailRecords bool `json:"update_mail_records"`
// UpdateAllRecords: whether or not to synchronize all types of records. This one has priority.
UpdateAllRecords bool `json:"update_all_records"`
// CustomRecords: custom records to synchronize.
CustomRecords []*SyncDomainDNSRecordsRequestRecord `json:"custom_records"`
}
// DNSRecords: dns records.
type DNSRecords struct {
// Records: list of DNS records.
Records []*DNSRecord `json:"records"`
// NameServers: list of nameservers.
NameServers []*Nameserver `json:"name_servers"`
// Status: status of the records.
// Default value: unknown_status
Status DNSRecordsStatus `json:"status"`
}
// DatabaseAPIAssignDatabaseUserRequest: database api assign database user request.
type DatabaseAPIAssignDatabaseUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// DatabaseName: name of the database to be assigned.
DatabaseName string `json:"-"`
// Username: name of the user to assign.
Username string `json:"username"`
}
// DatabaseAPIChangeDatabaseUserPasswordRequest: database api change database user password request.
type DatabaseAPIChangeDatabaseUserPasswordRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: name of the user to update.
Username string `json:"-"`
// Password: new password.
Password string `json:"password"`
}
// DatabaseAPICreateDatabaseRequest: database api create database request.
type DatabaseAPICreateDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan where the database will be created.
HostingID string `json:"-"`
// DatabaseName: name of the database to be created.
DatabaseName string `json:"database_name"`
// NewUser: (Optional) Username and password to create a user and link to the database.
// Precisely one of NewUser, ExistingUsername must be set.
NewUser *CreateDatabaseRequestUser `json:"new_user,omitempty"`
// ExistingUsername: (Optional) Username to link an existing user to the database.
// Precisely one of NewUser, ExistingUsername must be set.
ExistingUsername *string `json:"existing_username,omitempty"`
}
// DatabaseAPICreateDatabaseUserRequest: database api create database user request.
type DatabaseAPICreateDatabaseUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: name of the user to create.
Username string `json:"username"`
// Password: password of the user to create.
Password string `json:"password"`
}
// DatabaseAPIDeleteDatabaseRequest: database api delete database request.
type DatabaseAPIDeleteDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// DatabaseName: name of the database to delete.
DatabaseName string `json:"-"`
}
// DatabaseAPIDeleteDatabaseUserRequest: database api delete database user request.
type DatabaseAPIDeleteDatabaseUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: name of the database user to delete.
Username string `json:"-"`
}
// DatabaseAPIGetDatabaseRequest: database api get database request.
type DatabaseAPIGetDatabaseRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// DatabaseName: name of the database.
DatabaseName string `json:"-"`
}
// DatabaseAPIGetDatabaseUserRequest: database api get database user request.
type DatabaseAPIGetDatabaseUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: name of the database user to retrieve details.
Username string `json:"-"`
}
// DatabaseAPIListDatabaseUsersRequest: database api list database users request.
type DatabaseAPIListDatabaseUsersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of database users to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order of database users in the response.
// Default value: username_asc
OrderBy ListDatabaseUsersRequestOrderBy `json:"-"`
}
// DatabaseAPIListDatabasesRequest: database api list databases request.
type DatabaseAPIListDatabasesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of databases to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order of databases in the response.
// Default value: database_name_asc
OrderBy ListDatabasesRequestOrderBy `json:"-"`
}
// DatabaseAPIUnassignDatabaseUserRequest: database api unassign database user request.
type DatabaseAPIUnassignDatabaseUserRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// DatabaseName: name of the database to be unassigned.
DatabaseName string `json:"-"`
// Username: name of the user to unassign.
Username string `json:"username"`
}
// FtpAccountAPIChangeFtpAccountPasswordRequest: ftp account api change ftp account password request.
type FtpAccountAPIChangeFtpAccountPasswordRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: username of the FTP account.
Username string `json:"-"`
// Password: new password for the FTP account.
Password string `json:"password"`
}
// FtpAccountAPICreateFtpAccountRequest: ftp account api create ftp account request.
type FtpAccountAPICreateFtpAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: username for the new FTP account.
Username string `json:"username"`
// Path: path for the new FTP account.
Path string `json:"path"`
// Password: password for the new FTP account.
Password string `json:"password"`
}
// FtpAccountAPIListFtpAccountsRequest: ftp account api list ftp accounts request.
type FtpAccountAPIListFtpAccountsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of FTP accounts to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order of FTP accounts in the response.
// Default value: username_asc
OrderBy ListFtpAccountsRequestOrderBy `json:"-"`
// Domain: domain to filter the FTP accounts.
Domain *string `json:"-"`
}
// FtpAccountAPIRemoveFtpAccountRequest: ftp account api remove ftp account request.
type FtpAccountAPIRemoveFtpAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Username: username of the FTP account to be deleted.
Username string `json:"-"`
}
// Hosting: hosting.
type Hosting struct {
// ID: ID of the Web Hosting plan.
ID string `json:"id"`
// ProjectID: ID of the Scaleway Project the Web Hosting plan belongs to.
ProjectID string `json:"project_id"`
// UpdatedAt: date on which the Web Hosting plan was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: date on which the Web Hosting plan was created.
CreatedAt *time.Time `json:"created_at"`
// Status: status of the Web Hosting plan.
// Default value: unknown_status
Status HostingStatus `json:"status"`
// Domain: main domain associated with the Web Hosting plan.
Domain string `json:"domain"`
// Offer: details of the Web Hosting plan offer and options.
Offer *Offer `json:"offer"`
// Platform: details of the hosting platform.
Platform *Platform `json:"platform"`
// Tags: list of tags associated with the Web Hosting plan.
Tags []string `json:"tags"`
// DNSStatus: DNS status of the Web Hosting plan.
// Default value: unknown_status
DNSStatus DNSRecordsStatus `json:"dns_status"`
// IPv4: current IPv4 address of the hosting.
IPv4 net.IP `json:"ipv4"`
// Protected: whether the hosting is protected or not.
Protected bool `json:"protected"`
// User: details of the hosting user.
User *HostingUser `json:"user"`
// Region: region where the Web Hosting plan is hosted.
Region scw.Region `json:"region"`
}
// HostingAPICreateHostingRequest: hosting api create hosting request.
type HostingAPICreateHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OfferID: ID of the selected offer for the Web Hosting plan.
OfferID string `json:"offer_id"`
// ProjectID: ID of the Scaleway Project in which to create the Web Hosting plan.
ProjectID string `json:"project_id"`
// Email: contact email for the Web Hosting client.
Email string `json:"email"`
// Tags: list of tags for the Web Hosting plan.
Tags []string `json:"tags"`
// Domain: domain name to link to the Web Hosting plan. You must already own this domain name, and have completed the DNS validation process beforehand.
Domain string `json:"domain"`
// OfferOptions: list of the Web Hosting plan options IDs with their quantities.
OfferOptions []*OfferOptionRequest `json:"offer_options"`
// Language: default language for the control panel interface.
// Default value: unknown_language_code
Language std.LanguageCode `json:"language"`
// DomainConfiguration: indicates whether to update hosting domain name servers and DNS records for domains managed by Scaleway Elements.
DomainConfiguration *CreateHostingRequestDomainConfiguration `json:"domain_configuration,omitempty"`
// SkipWelcomeEmail: indicates whether to skip a welcome email to the contact email containing hosting info.
SkipWelcomeEmail *bool `json:"skip_welcome_email,omitempty"`
}
// HostingAPICreateSessionRequest: hosting api create session request.
type HostingAPICreateSessionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// HostingAPIDeleteHostingRequest: hosting api delete hosting request.
type HostingAPIDeleteHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// HostingAPIGetHostingRequest: hosting api get hosting request.
type HostingAPIGetHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// HostingAPIGetResourceSummaryRequest: hosting api get resource summary request.
type HostingAPIGetResourceSummaryRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// HostingAPIListHostingsRequest: hosting api list hostings request.
type HostingAPIListHostingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of Web Hosting plans to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order for Web Hosting plans in the response.
// Default value: created_at_asc
OrderBy ListHostingsRequestOrderBy `json:"-"`
// Tags: tags to filter for, only Web Hosting plans with matching tags will be returned.
Tags []string `json:"-"`
// Statuses: statuses to filter for, only Web Hosting plans with matching statuses will be returned.
Statuses []HostingStatus `json:"-"`
// Domain: domain to filter for, only Web Hosting plans associated with this domain will be returned.
Domain *string `json:"-"`
// ProjectID: project ID to filter for, only Web Hosting plans from this Project will be returned.
ProjectID *string `json:"-"`
// OrganizationID: organization ID to filter for, only Web Hosting plans from this Organization will be returned.
OrganizationID *string `json:"-"`
// ControlPanels: name of the control panel to filter for, only Web Hosting plans from this control panel will be returned.
ControlPanels []string `json:"-"`
}
// HostingAPIResetHostingPasswordRequest: hosting api reset hosting password request.
type HostingAPIResetHostingPasswordRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting.
HostingID string `json:"-"`
}
// HostingAPIUpdateHostingRequest: hosting api update hosting request.
type HostingAPIUpdateHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
// Email: new contact email for the Web Hosting plan.
Email *string `json:"email,omitempty"`
// Tags: new tags for the Web Hosting plan.
Tags *[]string `json:"tags,omitempty"`
// OfferOptions: list of the Web Hosting plan options IDs with their quantities.
OfferOptions []*OfferOptionRequest `json:"offer_options"`
// OfferID: ID of the new offer for the Web Hosting plan.
OfferID *string `json:"offer_id,omitempty"`
// Protected: whether the hosting is protected or not.
Protected *bool `json:"protected,omitempty"`
}
// ListControlPanelsResponse: list control panels response.
type ListControlPanelsResponse struct {
// TotalCount: number of control panels returned.
TotalCount uint64 `json:"total_count"`
// ControlPanels: list of control panels.
ControlPanels []*ControlPanel `json:"control_panels"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListControlPanelsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListControlPanelsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListControlPanelsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ControlPanels = append(r.ControlPanels, results.ControlPanels...)
r.TotalCount += uint64(len(results.ControlPanels))
return uint64(len(results.ControlPanels)), nil
}
// ListDatabaseUsersResponse: list database users response.
type ListDatabaseUsersResponse struct {
// TotalCount: total number of database users.
TotalCount uint64 `json:"total_count"`
// Users: list of database users.
Users []*DatabaseUser `json:"users"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabaseUsersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabaseUsersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDatabaseUsersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Users = append(r.Users, results.Users...)
r.TotalCount += uint64(len(results.Users))
return uint64(len(results.Users)), nil
}
// ListDatabasesResponse: list databases response.
type ListDatabasesResponse struct {
// TotalCount: total number of databases.
TotalCount uint64 `json:"total_count"`
// Databases: list of databases.
Databases []*Database `json:"databases"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListDatabasesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListDatabasesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Databases = append(r.Databases, results.Databases...)
r.TotalCount += uint64(len(results.Databases))
return uint64(len(results.Databases)), nil
}
// ListFtpAccountsResponse: list ftp accounts response.
type ListFtpAccountsResponse struct {
// TotalCount: total number of FTP accounts.
TotalCount uint64 `json:"total_count"`
// FtpAccounts: list of FTP accounts.
FtpAccounts []*FtpAccount `json:"ftp_accounts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListFtpAccountsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListFtpAccountsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListFtpAccountsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.FtpAccounts = append(r.FtpAccounts, results.FtpAccounts...)
r.TotalCount += uint64(len(results.FtpAccounts))
return uint64(len(results.FtpAccounts)), nil
}
// ListHostingsResponse: list hostings response.
type ListHostingsResponse struct {
// TotalCount: number of Web Hosting plans returned.
TotalCount uint64 `json:"total_count"`
// Hostings: list of Web Hosting plans.
Hostings []*HostingSummary `json:"hostings"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListHostingsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListHostingsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListHostingsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Hostings = append(r.Hostings, results.Hostings...)
r.TotalCount += uint64(len(results.Hostings))
return uint64(len(results.Hostings)), nil
}
// ListMailAccountsResponse: list mail accounts response.
type ListMailAccountsResponse struct {
// TotalCount: total number of mail accounts.
TotalCount uint64 `json:"total_count"`
// MailAccounts: list of mail accounts.
MailAccounts []*MailAccount `json:"mail_accounts"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListMailAccountsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListMailAccountsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListMailAccountsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.MailAccounts = append(r.MailAccounts, results.MailAccounts...)
r.TotalCount += uint64(len(results.MailAccounts))
return uint64(len(results.MailAccounts)), nil
}
// ListOffersResponse: list offers response.
type ListOffersResponse struct {
// TotalCount: total number of offers.
TotalCount uint64 `json:"total_count"`
// Offers: list of offers.
Offers []*Offer `json:"offers"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListOffersResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListOffersResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Offers = append(r.Offers, results.Offers...)
r.TotalCount += uint64(len(results.Offers))
return uint64(len(results.Offers)), nil
}
// ListWebsitesResponse: list websites response.
type ListWebsitesResponse struct {
// TotalCount: total number of websites.
TotalCount uint64 `json:"total_count"`
// Websites: list of websites.
Websites []*Website `json:"websites"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListWebsitesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListWebsitesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListWebsitesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Websites = append(r.Websites, results.Websites...)
r.TotalCount += uint64(len(results.Websites))
return uint64(len(results.Websites)), nil
}
// MailAccountAPIChangeMailAccountPasswordRequest: mail account api change mail account password request.
type MailAccountAPIChangeMailAccountPasswordRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Domain: domain part of the mail account address.
Domain string `json:"domain"`
// Username: username part of the mail account address.
Username string `json:"username"`
// Password: new password for the mail account.
Password string `json:"password"`
}
// MailAccountAPICreateMailAccountRequest: mail account api create mail account request.
type MailAccountAPICreateMailAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Domain: domain part of the mail account address.
Domain string `json:"domain"`
// Username: username part address of the mail account address.
Username string `json:"username"`
// Password: password for the new mail account.
Password string `json:"password"`
}
// MailAccountAPIListMailAccountsRequest: mail account api list mail accounts request.
type MailAccountAPIListMailAccountsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of mail accounts to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order of mail accounts in the response.
// Default value: username_asc
OrderBy ListMailAccountsRequestOrderBy `json:"-"`
// Domain: domain to filter the mail accounts.
Domain *string `json:"-"`
}
// MailAccountAPIRemoveMailAccountRequest: mail account api remove mail account request.
type MailAccountAPIRemoveMailAccountRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Domain: domain part of the mail account address.
Domain string `json:"domain"`
// Username: username part of the mail account address.
Username string `json:"username"`
}
// OfferAPIListOffersRequest: offer api list offers request.
type OfferAPIListOffersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of websites to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order for Web Hosting offers in the response.
// Default value: price_asc
OrderBy ListOffersRequestOrderBy `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID *string `json:"-"`
// ControlPanels: name of the control panel(s) to filter for.
ControlPanels []string `json:"-"`
}
// ResetHostingPasswordResponse: reset hosting password response.
type ResetHostingPasswordResponse struct {
// OneTimePassword: new temporary password.
OneTimePassword string `json:"one_time_password"`
}
// ResourceSummary: resource summary.
type ResourceSummary struct {
// DatabasesCount: total number of active databases in the Web Hosting plan.
DatabasesCount uint32 `json:"databases_count"`
// MailAccountsCount: total number of active email accounts in the Web Hosting plan.
MailAccountsCount uint32 `json:"mail_accounts_count"`
// FtpAccountsCount: total number of active FTP accounts in the Web Hosting plan.
FtpAccountsCount uint32 `json:"ftp_accounts_count"`
// WebsitesCount: total number of active domains in the the Web Hosting plan.
WebsitesCount uint32 `json:"websites_count"`
}
// Session: session.
type Session struct {
// URL: logged user's session URL.
URL string `json:"url"`
}
// WebsiteAPIListWebsitesRequest: website api list websites request.
type WebsiteAPIListWebsitesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting plan.
HostingID string `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of websites to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order for Web Hosting websites in the response.
// Default value: domain_asc
OrderBy ListWebsitesRequestOrderBy `json:"-"`
}
// This API allows you to manage your Web Hosting services.
type ControlPanelAPI struct {
client *scw.Client
}
// NewControlPanelAPI returns a ControlPanelAPI object from a Scaleway client.
func NewControlPanelAPI(client *scw.Client) *ControlPanelAPI {
return &ControlPanelAPI{
client: client,
}
}
func (s *ControlPanelAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListControlPanels: "List the control panels type: cpanel or plesk.".
func (s *ControlPanelAPI) ListControlPanels(req *ControlPanelAPIListControlPanelsRequest, opts ...scw.RequestOption) (*ListControlPanelsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/control-panels",
Query: query,
}
var resp ListControlPanelsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your databases and database users for your Web Hosting services.
type DatabaseAPI struct {
client *scw.Client
}
// NewDatabaseAPI returns a DatabaseAPI object from a Scaleway client.
func NewDatabaseAPI(client *scw.Client) *DatabaseAPI {
return &DatabaseAPI{
client: client,
}
}
func (s *DatabaseAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateDatabase: "Create a new database within your hosting plan".
func (s *DatabaseAPI) CreateDatabase(req *DatabaseAPICreateDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDatabases: "List all databases within your hosting plan".
func (s *DatabaseAPI) ListDatabases(req *DatabaseAPIListDatabasesRequest, opts ...scw.RequestOption) (*ListDatabasesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases",
Query: query,
}
var resp ListDatabasesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDatabase: "Get details of a database within your hosting plan".
func (s *DatabaseAPI) GetDatabase(req *DatabaseAPIGetDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.DatabaseName) == "" {
return nil, errors.New("field DatabaseName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases/" + fmt.Sprint(req.DatabaseName) + "",
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabase: "Delete a database within your hosting plan".
func (s *DatabaseAPI) DeleteDatabase(req *DatabaseAPIDeleteDatabaseRequest, opts ...scw.RequestOption) (*Database, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.DatabaseName) == "" {
return nil, errors.New("field DatabaseName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases/" + fmt.Sprint(req.DatabaseName) + "",
}
var resp Database
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateDatabaseUser: "Create a new database user".
func (s *DatabaseAPI) CreateDatabaseUser(req *DatabaseAPICreateDatabaseUserRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases-users",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListDatabaseUsers: "List all database users".
func (s *DatabaseAPI) ListDatabaseUsers(req *DatabaseAPIListDatabaseUsersRequest, opts ...scw.RequestOption) (*ListDatabaseUsersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/database-users",
Query: query,
}
var resp ListDatabaseUsersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDatabaseUser: "Get details of a database user".
func (s *DatabaseAPI) GetDatabaseUser(req *DatabaseAPIGetDatabaseUserRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.Username) == "" {
return nil, errors.New("field Username cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases-users/" + fmt.Sprint(req.Username) + "",
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteDatabaseUser: "Delete a database user".
func (s *DatabaseAPI) DeleteDatabaseUser(req *DatabaseAPIDeleteDatabaseUserRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.Username) == "" {
return nil, errors.New("field Username cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/database-users/" + fmt.Sprint(req.Username) + "",
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ChangeDatabaseUserPassword: "Change the password of a database user".
func (s *DatabaseAPI) ChangeDatabaseUserPassword(req *DatabaseAPIChangeDatabaseUserPasswordRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.Username) == "" {
return nil, errors.New("field Username cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases-users/" + fmt.Sprint(req.Username) + "/change-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// AssignDatabaseUser: "Assign a database user to a database".
func (s *DatabaseAPI) AssignDatabaseUser(req *DatabaseAPIAssignDatabaseUserRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.DatabaseName) == "" {
return nil, errors.New("field DatabaseName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases/" + fmt.Sprint(req.DatabaseName) + "/assign-user",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UnassignDatabaseUser: "Unassign a database user from a database".
func (s *DatabaseAPI) UnassignDatabaseUser(req *DatabaseAPIUnassignDatabaseUserRequest, opts ...scw.RequestOption) (*DatabaseUser, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.DatabaseName) == "" {
return nil, errors.New("field DatabaseName cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/databases/" + fmt.Sprint(req.DatabaseName) + "/unassign-user",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DatabaseUser
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your Web Hosting services.
type DnsAPI struct {
client *scw.Client
}
// NewDnsAPI returns a DnsAPI object from a Scaleway client.
func NewDnsAPI(client *scw.Client) *DnsAPI {
return &DnsAPI{
client: client,
}
}
func (s *DnsAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// GetDomainDNSRecords: Get the set of DNS records of a specified domain associated with a Web Hosting plan's domain.
func (s *DnsAPI) GetDomainDNSRecords(req *DNSAPIGetDomainDNSRecordsRequest, opts ...scw.RequestOption) (*DNSRecords, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.Domain) + "/dns-records",
}
var resp DNSRecords
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckUserOwnsDomain: "Check whether you own this domain or not.".
func (s *DnsAPI) CheckUserOwnsDomain(req *DNSAPICheckUserOwnsDomainRequest, opts ...scw.RequestOption) (*CheckUserOwnsDomainResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.Domain) + "/check-ownership",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckUserOwnsDomainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// SyncDomainDNSRecords: "Synchronize your DNS records on the Elements Console and on cPanel.".
func (s *DnsAPI) SyncDomainDNSRecords(req *DNSAPISyncDomainDNSRecordsRequest, opts ...scw.RequestOption) (*DNSRecords, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.Domain) + "/sync-domain-dns-records",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp DNSRecords
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your offer for your Web Hosting services.
type OfferAPI struct {
client *scw.Client
}
// NewOfferAPI returns a OfferAPI object from a Scaleway client.
func NewOfferAPI(client *scw.Client) *OfferAPI {
return &OfferAPI{
client: client,
}
}
func (s *OfferAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListOffers: List all available hosting offers along with their specific options.
func (s *OfferAPI) ListOffers(req *OfferAPIListOffersRequest, opts ...scw.RequestOption) (*ListOffersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "hosting_id", req.HostingID)
parameter.AddToQuery(query, "control_panels", req.ControlPanels)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/offers",
Query: query,
}
var resp ListOffersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your Web Hosting services.
type HostingAPI struct {
client *scw.Client
}
// NewHostingAPI returns a HostingAPI object from a Scaleway client.
func NewHostingAPI(client *scw.Client) *HostingAPI {
return &HostingAPI{
client: client,
}
}
func (s *HostingAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateHosting: Order a Web Hosting plan, specifying the offer type required via the `offer_id` parameter.
func (s *HostingAPI) CreateHosting(req *HostingAPICreateHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListHostings: List all of your existing Web Hosting plans. Various filters are available to limit the results, including filtering by domain, status, tag and Project ID.
func (s *HostingAPI) ListHostings(req *HostingAPIListHostingsRequest, opts ...scw.RequestOption) (*ListHostingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "statuses", req.Statuses)
parameter.AddToQuery(query, "domain", req.Domain)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "control_panels", req.ControlPanels)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings",
Query: query,
}
var resp ListHostingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetHosting: Get the details of one of your existing Web Hosting plans, specified by its `hosting_id`.
func (s *HostingAPI) GetHosting(req *HostingAPIGetHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHosting: Update the details of one of your existing Web Hosting plans, specified by its `hosting_id`. You can update parameters including the contact email address, tags, options and offer.
func (s *HostingAPI) UpdateHosting(req *HostingAPIUpdateHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteHosting: Delete a Web Hosting plan, specified by its `hosting_id`. Note that deletion is not immediate: it will take place at the end of the calendar month, after which time your Web Hosting plan and all its data (files and emails) will be irreversibly lost.
func (s *HostingAPI) DeleteHosting(req *HostingAPIDeleteHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSession: Create a user session.
func (s *HostingAPI) CreateSession(req *HostingAPICreateSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/sessions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ResetHostingPassword: Reset a Web Hosting plan password.
func (s *HostingAPI) ResetHostingPassword(req *HostingAPIResetHostingPasswordRequest, opts ...scw.RequestOption) (*ResetHostingPasswordResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/reset-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ResetHostingPasswordResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetResourceSummary: Get the total counts of websites, databases, email accounts, and FTP accounts of a Web Hosting plan.
func (s *HostingAPI) GetResourceSummary(req *HostingAPIGetResourceSummaryRequest, opts ...scw.RequestOption) (*ResourceSummary, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/resource-summary",
}
var resp ResourceSummary
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your FTP accounts for your Web Hosting services.
type FtpAccountAPI struct {
client *scw.Client
}
// NewFtpAccountAPI returns a FtpAccountAPI object from a Scaleway client.
func NewFtpAccountAPI(client *scw.Client) *FtpAccountAPI {
return &FtpAccountAPI{
client: client,
}
}
func (s *FtpAccountAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateFtpAccount: Create a new FTP account within your hosting plan.
func (s *FtpAccountAPI) CreateFtpAccount(req *FtpAccountAPICreateFtpAccountRequest, opts ...scw.RequestOption) (*FtpAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/ftp-accounts",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FtpAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListFtpAccounts: List all FTP accounts within your hosting plan.
func (s *FtpAccountAPI) ListFtpAccounts(req *FtpAccountAPIListFtpAccountsRequest, opts ...scw.RequestOption) (*ListFtpAccountsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "domain", req.Domain)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/ftp-accounts",
Query: query,
}
var resp ListFtpAccountsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RemoveFtpAccount: Delete a specific FTP account within your hosting plan.
func (s *FtpAccountAPI) RemoveFtpAccount(req *FtpAccountAPIRemoveFtpAccountRequest, opts ...scw.RequestOption) (*FtpAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.Username) == "" {
return nil, errors.New("field Username cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/ftp-accounts/" + fmt.Sprint(req.Username) + "",
}
var resp FtpAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ChangeFtpAccountPassword:
func (s *FtpAccountAPI) ChangeFtpAccountPassword(req *FtpAccountAPIChangeFtpAccountPasswordRequest, opts ...scw.RequestOption) (*FtpAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
if fmt.Sprint(req.Username) == "" {
return nil, errors.New("field Username cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/ftp-accounts/" + fmt.Sprint(req.Username) + "/change-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp FtpAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your mail accounts for your Web Hosting services.
type MailAccountAPI struct {
client *scw.Client
}
// NewMailAccountAPI returns a MailAccountAPI object from a Scaleway client.
func NewMailAccountAPI(client *scw.Client) *MailAccountAPI {
return &MailAccountAPI{
client: client,
}
}
func (s *MailAccountAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateMailAccount: Create a new mail account within your hosting plan.
func (s *MailAccountAPI) CreateMailAccount(req *MailAccountAPICreateMailAccountRequest, opts ...scw.RequestOption) (*MailAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/mail-accounts",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp MailAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListMailAccounts: List all mail accounts within your hosting plan.
func (s *MailAccountAPI) ListMailAccounts(req *MailAccountAPIListMailAccountsRequest, opts ...scw.RequestOption) (*ListMailAccountsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "domain", req.Domain)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/mail-accounts",
Query: query,
}
var resp ListMailAccountsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RemoveMailAccount: Delete a mail account within your hosting plan.
func (s *MailAccountAPI) RemoveMailAccount(req *MailAccountAPIRemoveMailAccountRequest, opts ...scw.RequestOption) (*MailAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/remove-mail-account",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp MailAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ChangeMailAccountPassword: Update the password of a mail account within your hosting plan.
func (s *MailAccountAPI) ChangeMailAccountPassword(req *MailAccountAPIChangeMailAccountPasswordRequest, opts ...scw.RequestOption) (*MailAccount, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/change-mail-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp MailAccount
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your websites for your Web Hosting services.
type WebsiteAPI struct {
client *scw.Client
}
// NewWebsiteAPI returns a WebsiteAPI object from a Scaleway client.
func NewWebsiteAPI(client *scw.Client) *WebsiteAPI {
return &WebsiteAPI{
client: client,
}
}
func (s *WebsiteAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// ListWebsites: List all websites for a specific hosting.
func (s *WebsiteAPI) ListWebsites(req *WebsiteAPIListWebsitesRequest, opts ...scw.RequestOption) (*ListWebsitesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/websites",
Query: query,
}
var resp ListWebsitesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1alpha1/ 0000775 0000000 0000000 00000000000 14747113137 0026603 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1alpha1/sweepers/ 0000775 0000000 0000000 00000000000 14747113137 0030440 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1alpha1/sweepers/sweepers.go 0000664 0000000 0000000 00000001752 14747113137 0032631 0 ustar 00root root 0000000 0000000 package sweepers
import (
"fmt"
webhostingSDK "github.com/scaleway/scaleway-sdk-go/api/webhosting/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
func SweepWebHosting(scwClient *scw.Client, region scw.Region) error {
webHostingAPI := webhostingSDK.NewAPI(scwClient)
listHostings, err := webHostingAPI.ListHostings(&webhostingSDK.ListHostingsRequest{Region: region}, scw.WithAllPages())
if err != nil {
return fmt.Errorf("error listing hostings in (%s) in sweeper: %s", region, err)
}
for _, hosting := range listHostings.Hostings {
_, err := webHostingAPI.DeleteHosting(&webhostingSDK.DeleteHostingRequest{
HostingID: hosting.ID,
Region: region,
})
if err != nil {
return fmt.Errorf("error deleting hosting in sweeper: %s", err)
}
}
return nil
}
func SweepAllLocalities(scwClient *scw.Client) error {
for _, region := range (&webhostingSDK.API{}).Regions() {
err := SweepWebHosting(scwClient, region)
if err != nil {
return err
}
}
return nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1alpha1/webhosting_sdk.go 0000664 0000000 0000000 00000133331 14747113137 0032150 0 ustar 00root root 0000000 0000000 // This file was automatically generated. DO NOT EDIT.
// If you have any remark or suggestion do not hesitate to open an issue.
// Package webhosting provides methods and message types of the webhosting v1alpha1 API.
package webhosting
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
std "github.com/scaleway/scaleway-sdk-go/api/std"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/marshaler"
"github.com/scaleway/scaleway-sdk-go/namegenerator"
"github.com/scaleway/scaleway-sdk-go/parameter"
"github.com/scaleway/scaleway-sdk-go/scw"
)
// always import dependencies
var (
_ fmt.Stringer
_ json.Unmarshaler
_ url.URL
_ net.IP
_ http.Header
_ bytes.Reader
_ time.Time
_ = strings.Join
_ scw.ScalewayRequest
_ marshaler.Duration
_ scw.File
_ = parameter.AddToQuery
_ = namegenerator.GetRandomName
)
type DNSRecordStatus string
const (
DNSRecordStatusUnknownStatus = DNSRecordStatus("unknown_status")
DNSRecordStatusValid = DNSRecordStatus("valid")
DNSRecordStatusInvalid = DNSRecordStatus("invalid")
)
func (enum DNSRecordStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum DNSRecordStatus) Values() []DNSRecordStatus {
return []DNSRecordStatus{
"unknown_status",
"valid",
"invalid",
}
}
func (enum DNSRecordStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordStatus(DNSRecordStatus(tmp).String())
return nil
}
type DNSRecordType string
const (
DNSRecordTypeUnknownType = DNSRecordType("unknown_type")
DNSRecordTypeA = DNSRecordType("a")
DNSRecordTypeCname = DNSRecordType("cname")
DNSRecordTypeMx = DNSRecordType("mx")
DNSRecordTypeTxt = DNSRecordType("txt")
DNSRecordTypeNs = DNSRecordType("ns")
DNSRecordTypeAaaa = DNSRecordType("aaaa")
)
func (enum DNSRecordType) String() string {
if enum == "" {
// return default value if empty
return "unknown_type"
}
return string(enum)
}
func (enum DNSRecordType) Values() []DNSRecordType {
return []DNSRecordType{
"unknown_type",
"a",
"cname",
"mx",
"txt",
"ns",
"aaaa",
}
}
func (enum DNSRecordType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordType) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordType(DNSRecordType(tmp).String())
return nil
}
type DNSRecordsStatus string
const (
DNSRecordsStatusUnknown = DNSRecordsStatus("unknown")
DNSRecordsStatusValid = DNSRecordsStatus("valid")
DNSRecordsStatusInvalid = DNSRecordsStatus("invalid")
)
func (enum DNSRecordsStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown"
}
return string(enum)
}
func (enum DNSRecordsStatus) Values() []DNSRecordsStatus {
return []DNSRecordsStatus{
"unknown",
"valid",
"invalid",
}
}
func (enum DNSRecordsStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *DNSRecordsStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = DNSRecordsStatus(DNSRecordsStatus(tmp).String())
return nil
}
type HostingDNSStatus string
const (
HostingDNSStatusUnknownDNSStatus = HostingDNSStatus("unknown_dns_status")
HostingDNSStatusValid = HostingDNSStatus("valid")
HostingDNSStatusInvalid = HostingDNSStatus("invalid")
)
func (enum HostingDNSStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_dns_status"
}
return string(enum)
}
func (enum HostingDNSStatus) Values() []HostingDNSStatus {
return []HostingDNSStatus{
"unknown_dns_status",
"valid",
"invalid",
}
}
func (enum HostingDNSStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HostingDNSStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HostingDNSStatus(HostingDNSStatus(tmp).String())
return nil
}
type HostingStatus string
const (
HostingStatusUnknownStatus = HostingStatus("unknown_status")
HostingStatusDelivering = HostingStatus("delivering")
HostingStatusReady = HostingStatus("ready")
HostingStatusDeleting = HostingStatus("deleting")
HostingStatusError = HostingStatus("error")
HostingStatusLocked = HostingStatus("locked")
HostingStatusMigrating = HostingStatus("migrating")
)
func (enum HostingStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum HostingStatus) Values() []HostingStatus {
return []HostingStatus{
"unknown_status",
"delivering",
"ready",
"deleting",
"error",
"locked",
"migrating",
}
}
func (enum HostingStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *HostingStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = HostingStatus(HostingStatus(tmp).String())
return nil
}
type ListHostingsRequestOrderBy string
const (
ListHostingsRequestOrderByCreatedAtAsc = ListHostingsRequestOrderBy("created_at_asc")
ListHostingsRequestOrderByCreatedAtDesc = ListHostingsRequestOrderBy("created_at_desc")
)
func (enum ListHostingsRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "created_at_asc"
}
return string(enum)
}
func (enum ListHostingsRequestOrderBy) Values() []ListHostingsRequestOrderBy {
return []ListHostingsRequestOrderBy{
"created_at_asc",
"created_at_desc",
}
}
func (enum ListHostingsRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListHostingsRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListHostingsRequestOrderBy(ListHostingsRequestOrderBy(tmp).String())
return nil
}
type ListOffersRequestOrderBy string
const (
ListOffersRequestOrderByPriceAsc = ListOffersRequestOrderBy("price_asc")
)
func (enum ListOffersRequestOrderBy) String() string {
if enum == "" {
// return default value if empty
return "price_asc"
}
return string(enum)
}
func (enum ListOffersRequestOrderBy) Values() []ListOffersRequestOrderBy {
return []ListOffersRequestOrderBy{
"price_asc",
}
}
func (enum ListOffersRequestOrderBy) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *ListOffersRequestOrderBy) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = ListOffersRequestOrderBy(ListOffersRequestOrderBy(tmp).String())
return nil
}
type NameserverStatus string
const (
NameserverStatusUnknownStatus = NameserverStatus("unknown_status")
NameserverStatusValid = NameserverStatus("valid")
NameserverStatusInvalid = NameserverStatus("invalid")
)
func (enum NameserverStatus) String() string {
if enum == "" {
// return default value if empty
return "unknown_status"
}
return string(enum)
}
func (enum NameserverStatus) Values() []NameserverStatus {
return []NameserverStatus{
"unknown_status",
"valid",
"invalid",
}
}
func (enum NameserverStatus) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *NameserverStatus) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = NameserverStatus(NameserverStatus(tmp).String())
return nil
}
type OfferQuotaWarning string
const (
OfferQuotaWarningUnknownQuotaWarning = OfferQuotaWarning("unknown_quota_warning")
OfferQuotaWarningEmailCountExceeded = OfferQuotaWarning("email_count_exceeded")
OfferQuotaWarningDatabaseCountExceeded = OfferQuotaWarning("database_count_exceeded")
OfferQuotaWarningDiskUsageExceeded = OfferQuotaWarning("disk_usage_exceeded")
OfferQuotaWarningAddonDomainCountExceeded = OfferQuotaWarning("addon_domain_count_exceeded")
)
func (enum OfferQuotaWarning) String() string {
if enum == "" {
// return default value if empty
return "unknown_quota_warning"
}
return string(enum)
}
func (enum OfferQuotaWarning) Values() []OfferQuotaWarning {
return []OfferQuotaWarning{
"unknown_quota_warning",
"email_count_exceeded",
"database_count_exceeded",
"disk_usage_exceeded",
"addon_domain_count_exceeded",
}
}
func (enum OfferQuotaWarning) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum)), nil
}
func (enum *OfferQuotaWarning) UnmarshalJSON(data []byte) error {
tmp := ""
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*enum = OfferQuotaWarning(OfferQuotaWarning(tmp).String())
return nil
}
// HostingCpanelURLs: hosting cpanel ur ls.
type HostingCpanelURLs struct {
Dashboard string `json:"dashboard"`
Webmail string `json:"webmail"`
}
// HostingOption: hosting option.
type HostingOption struct {
// ID: option ID.
ID string `json:"id"`
// Name: option name.
Name string `json:"name"`
}
// EmailAddress: email address.
type EmailAddress struct {
// Domain: domain part of the mailbox address.
Domain string `json:"domain"`
// Login: username part address of the mailbox address.
Login string `json:"login"`
}
// OfferProduct: offer product.
type OfferProduct struct {
// Name: product name.
Name string `json:"name"`
// Option: product option.
Option bool `json:"option"`
// EmailAccountsQuota: limit number of email accounts.
EmailAccountsQuota int32 `json:"email_accounts_quota"`
// EmailStorageQuota: limit quantity of email storage in gigabytes.
EmailStorageQuota int32 `json:"email_storage_quota"`
// DatabasesQuota: limit number of databases.
DatabasesQuota int32 `json:"databases_quota"`
// HostingStorageQuota: limit quantity of hosting storage in gigabytes.
HostingStorageQuota uint32 `json:"hosting_storage_quota"`
// SupportIncluded: whether or not support is included.
SupportIncluded bool `json:"support_included"`
// VCPU: limit number of virtual CPU.
VCPU uint32 `json:"v_cpu"`
// RAM: limit quantity of memory in gigabytes.
RAM uint32 `json:"ram"`
// MaxAddonDomains: limit number of add-on domains.
MaxAddonDomains int32 `json:"max_addon_domains"`
}
// CreateHostingRequestDomainConfiguration: create hosting request domain configuration.
type CreateHostingRequestDomainConfiguration struct {
UpdateNameservers bool `json:"update_nameservers"`
UpdateWebRecord bool `json:"update_web_record"`
UpdateMailRecord bool `json:"update_mail_record"`
UpdateAllRecords bool `json:"update_all_records"`
}
// DNSRecord: dns record.
type DNSRecord struct {
// Name: record name.
Name string `json:"name"`
// Type: record type.
// Default value: unknown_type
Type DNSRecordType `json:"type"`
// TTL: record time-to-live.
TTL uint32 `json:"ttl"`
// Value: record value.
Value string `json:"value"`
// Priority: record priority level.
Priority *uint32 `json:"priority"`
// Status: record status.
// Default value: unknown_status
Status DNSRecordStatus `json:"status"`
}
// Nameserver: nameserver.
type Nameserver struct {
// Hostname: hostname of the nameserver.
Hostname string `json:"hostname"`
// Status: status of the nameserver.
// Default value: unknown_status
Status NameserverStatus `json:"status"`
// IsDefault: defines whether the nameserver is the default one.
IsDefault bool `json:"is_default"`
}
// ControlPanel: control panel.
type ControlPanel struct {
// Name: control panel name.
Name string `json:"name"`
// Available: define if the control panel type is available to order.
Available bool `json:"available"`
// LogoURL: URL of this control panel's logo.
LogoURL string `json:"logo_url"`
// AvailableLanguages: list of available languages for the control panel.
AvailableLanguages []std.LanguageCode `json:"available_languages"`
}
// Hosting: hosting.
type Hosting struct {
// ID: ID of the Web Hosting plan.
ID string `json:"id"`
// OrganizationID: ID of the Scaleway Organization the Web Hosting plan belongs to.
OrganizationID string `json:"organization_id"`
// ProjectID: ID of the Scaleway Project the Web Hosting plan belongs to.
ProjectID string `json:"project_id"`
// UpdatedAt: date on which the Web Hosting plan was last updated.
UpdatedAt *time.Time `json:"updated_at"`
// CreatedAt: date on which the Web Hosting plan was created.
CreatedAt *time.Time `json:"created_at"`
// Status: status of the Web Hosting plan.
// Default value: unknown_status
Status HostingStatus `json:"status"`
// PlatformHostname: hostname of the host platform.
PlatformHostname string `json:"platform_hostname"`
// PlatformNumber: number of the host platform.
PlatformNumber *int32 `json:"platform_number"`
// OfferID: ID of the active offer for the Web Hosting plan.
OfferID string `json:"offer_id"`
// OfferName: name of the active offer for the Web Hosting plan.
OfferName string `json:"offer_name"`
// Domain: main domain associated with the Web Hosting plan.
Domain string `json:"domain"`
// Tags: list of tags associated with the Web Hosting plan.
Tags []string `json:"tags"`
// Options: array of any options activated for the Web Hosting plan.
Options []*HostingOption `json:"options"`
// DNSStatus: DNS status of the Web Hosting plan.
// Default value: unknown_dns_status
DNSStatus HostingDNSStatus `json:"dns_status"`
// CpanelURLs: URL to connect to cPanel dashboard and to Webmail interface.
CpanelURLs *HostingCpanelURLs `json:"cpanel_urls"`
// Username: main Web Hosting cPanel username.
Username string `json:"username"`
// OfferEndOfLife: indicates if the hosting offer has reached its end of life.
OfferEndOfLife bool `json:"offer_end_of_life"`
// ControlPanelName: name of the control panel.
ControlPanelName string `json:"control_panel_name"`
// PlatformGroup: group of the hosting's host server/platform.
PlatformGroup string `json:"platform_group"`
// IPv4: iPv4 address of the hosting's host server.
IPv4 string `json:"ipv4"`
// IPv6: iPv6 address of the hosting's host server.
IPv6 string `json:"ipv6"`
// Protected: whether the hosting is protected or not.
Protected bool `json:"protected"`
// OneTimePassword: one-time-password used for the first login or reset password, empty after first use.
OneTimePassword string `json:"one_time_password"`
// Region: region where the Web Hosting plan is hosted.
Region scw.Region `json:"region"`
}
// Mailbox: mailbox.
type Mailbox struct {
// MailboxID: the ID of the mailbox.
MailboxID uint32 `json:"mailbox_id"`
// Email: the email address of the mailbox.
Email *EmailAddress `json:"email"`
}
// Offer: offer.
type Offer struct {
// ID: offer ID.
ID string `json:"id"`
// BillingOperationPath: unique identifier used for billing.
BillingOperationPath string `json:"billing_operation_path"`
// Product: product constituting this offer.
Product *OfferProduct `json:"product"`
// Price: price of this offer.
Price *scw.Money `json:"price"`
// Available: if a hosting_id was specified in the call, defines whether this offer is available for that Web Hosting plan to migrate (update) to.
Available bool `json:"available"`
// QuotaWarnings: quota warnings, if the offer is not available for the specified hosting_id.
QuotaWarnings []OfferQuotaWarning `json:"quota_warnings"`
// EndOfLife: indicates if the offer has reached its end of life.
EndOfLife bool `json:"end_of_life"`
// ControlPanelName: name of the control panel.
ControlPanelName string `json:"control_panel_name"`
}
// CheckUserOwnsDomainRequest: check user owns domain request.
type CheckUserOwnsDomainRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Domain: domain for which ownership is to be verified.
Domain string `json:"-"`
// ProjectID: ID of the project currently in use.
ProjectID string `json:"project_id"`
}
// CheckUserOwnsDomainResponse: check user owns domain response.
type CheckUserOwnsDomainResponse struct {
// OwnsDomain: indicates whether the specified project owns the domain.
OwnsDomain bool `json:"owns_domain"`
}
// ClassicMailAPICreateMailboxRequest: classic mail api create mailbox request.
type ClassicMailAPICreateMailboxRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OnlineID: the Online hosting ID.
OnlineID uint32 `json:"-"`
// Email: the email address of the mailbox.
Email *EmailAddress `json:"email,omitempty"`
// Password: password for the new mailbox.
Password string `json:"password"`
}
// ClassicMailAPIDeleteMailboxRequest: classic mail api delete mailbox request.
type ClassicMailAPIDeleteMailboxRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OnlineID: the Online hosting ID.
OnlineID uint32 `json:"-"`
// MailboxID: the ID of the mailbox to delete.
MailboxID uint32 `json:"-"`
}
// ClassicMailAPIGetMailboxRequest: classic mail api get mailbox request.
type ClassicMailAPIGetMailboxRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OnlineID: the Online hosting ID.
OnlineID uint32 `json:"-"`
// MailboxID: the ID of the mailbox to get.
MailboxID uint32 `json:"-"`
}
// ClassicMailAPIListMailboxesRequest: classic mail api list mailboxes request.
type ClassicMailAPIListMailboxesRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OnlineID: the Online hosting ID.
OnlineID uint32 `json:"-"`
// Page: page number (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of mailboxes to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// Domain: domain to filter the mailboxes.
Domain *string `json:"-"`
}
// ClassicMailAPIUpdateMailboxRequest: classic mail api update mailbox request.
type ClassicMailAPIUpdateMailboxRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OnlineID: the Online hosting ID.
OnlineID uint32 `json:"-"`
// MailboxID: the ID of the mailbox to update.
MailboxID uint32 `json:"-"`
// Password: new password for the mailbox.
Password *string `json:"password,omitempty"`
}
// CreateHostingRequest: create hosting request.
type CreateHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OfferID: ID of the selected offer for the Web Hosting plan.
OfferID string `json:"offer_id"`
// ProjectID: ID of the Scaleway Project in which to create the Web Hosting plan.
ProjectID string `json:"project_id"`
// Email: contact email for the Web Hosting client.
Email *string `json:"email,omitempty"`
// Tags: list of tags for the Web Hosting plan.
Tags []string `json:"tags"`
// Domain: domain name to link to the Web Hosting plan. You must already own this domain name, and have completed the DNS validation process beforehand.
Domain string `json:"domain"`
// OptionIDs: iDs of any selected additional options for the Web Hosting plan.
OptionIDs []string `json:"option_ids"`
// Language: default language for the control panel interface.
// Default value: unknown_language_code
Language std.LanguageCode `json:"language"`
// DomainConfiguration: indicates whether to update hosting domain name servers and DNS records for domains managed by Scaleway Elements.
DomainConfiguration *CreateHostingRequestDomainConfiguration `json:"domain_configuration,omitempty"`
}
// CreateSessionRequest: create session request.
type CreateSessionRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// DNSRecords: dns records.
type DNSRecords struct {
// Records: list of DNS records.
Records []*DNSRecord `json:"records"`
// NameServers: list of nameservers.
NameServers []*Nameserver `json:"name_servers"`
// Status: status of the records.
// Default value: unknown
Status DNSRecordsStatus `json:"status"`
}
// DeleteHostingRequest: delete hosting request.
type DeleteHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// GetDomainDNSRecordsRequest: get domain dns records request.
type GetDomainDNSRecordsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Domain: domain associated with the DNS records.
Domain string `json:"-"`
}
// GetHostingRequest: get hosting request.
type GetHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// ListControlPanelsRequest: list control panels request.
type ListControlPanelsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of control panels to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
}
// ListControlPanelsResponse: list control panels response.
type ListControlPanelsResponse struct {
// TotalCount: number of control panels returned.
TotalCount uint64 `json:"total_count"`
// ControlPanels: list of control panels.
ControlPanels []*ControlPanel `json:"control_panels"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListControlPanelsResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListControlPanelsResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListControlPanelsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.ControlPanels = append(r.ControlPanels, results.ControlPanels...)
r.TotalCount += uint64(len(results.ControlPanels))
return uint64(len(results.ControlPanels)), nil
}
// ListHostingsRequest: list hostings request.
type ListHostingsRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// Page: page number to return, from the paginated results (must be a positive integer).
Page *int32 `json:"-"`
// PageSize: number of Web Hosting plans to return (must be a positive integer lower or equal to 100).
PageSize *uint32 `json:"-"`
// OrderBy: sort order for Web Hosting plans in the response.
// Default value: created_at_asc
OrderBy ListHostingsRequestOrderBy `json:"-"`
// Tags: tags to filter for, only Web Hosting plans with matching tags will be returned.
Tags []string `json:"-"`
// Statuses: statuses to filter for, only Web Hosting plans with matching statuses will be returned.
Statuses []HostingStatus `json:"-"`
// Domain: domain to filter for, only Web Hosting plans associated with this domain will be returned.
Domain *string `json:"-"`
// ProjectID: project ID to filter for, only Web Hosting plans from this Project will be returned.
ProjectID *string `json:"-"`
// OrganizationID: organization ID to filter for, only Web Hosting plans from this Organization will be returned.
OrganizationID *string `json:"-"`
// ControlPanels: name of the control panel to filter for, only Web Hosting plans from this control panel will be returned.
ControlPanels []string `json:"-"`
}
// ListHostingsResponse: list hostings response.
type ListHostingsResponse struct {
// TotalCount: number of Web Hosting plans returned.
TotalCount uint32 `json:"total_count"`
// Hostings: list of Web Hosting plans.
Hostings []*Hosting `json:"hostings"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListHostingsResponse) UnsafeGetTotalCount() uint32 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListHostingsResponse) UnsafeAppend(res interface{}) (uint32, error) {
results, ok := res.(*ListHostingsResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Hostings = append(r.Hostings, results.Hostings...)
r.TotalCount += uint32(len(results.Hostings))
return uint32(len(results.Hostings)), nil
}
// ListMailboxesResponse: list mailboxes response.
type ListMailboxesResponse struct {
// TotalCount: total number of mailboxes.
TotalCount uint64 `json:"total_count"`
// Mailboxes: list of mailboxes.
Mailboxes []*Mailbox `json:"mailboxes"`
}
// UnsafeGetTotalCount should not be used
// Internal usage only
func (r *ListMailboxesResponse) UnsafeGetTotalCount() uint64 {
return r.TotalCount
}
// UnsafeAppend should not be used
// Internal usage only
func (r *ListMailboxesResponse) UnsafeAppend(res interface{}) (uint64, error) {
results, ok := res.(*ListMailboxesResponse)
if !ok {
return 0, errors.New("%T type cannot be appended to type %T", res, r)
}
r.Mailboxes = append(r.Mailboxes, results.Mailboxes...)
r.TotalCount += uint64(len(results.Mailboxes))
return uint64(len(results.Mailboxes)), nil
}
// ListOffersRequest: list offers request.
type ListOffersRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// OrderBy: sort order of offers in the response.
// Default value: price_asc
OrderBy ListOffersRequestOrderBy `json:"-"`
// WithoutOptions: defines whether the response should consist of offers only, without options.
WithoutOptions bool `json:"-"`
// OnlyOptions: defines whether the response should consist of options only, without offers.
OnlyOptions bool `json:"-"`
// HostingID: ID of a Web Hosting plan, to check compatibility with returned offers (in case of wanting to update the plan).
HostingID *string `json:"-"`
// ControlPanels: name of the control panel to filter for.
ControlPanels []string `json:"-"`
}
// ListOffersResponse: list offers response.
type ListOffersResponse struct {
// Offers: list of offers.
Offers []*Offer `json:"offers"`
}
// ResetHostingPasswordRequest: reset hosting password request.
type ResetHostingPasswordRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: UUID of the hosting.
HostingID string `json:"-"`
}
// ResetHostingPasswordResponse: reset hosting password response.
type ResetHostingPasswordResponse struct {
// Password: new password.
Password string `json:"password"`
}
// RestoreHostingRequest: restore hosting request.
type RestoreHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
}
// Session: session.
type Session struct {
// URL: logged user's session URL.
URL string `json:"url"`
}
// UpdateHostingRequest: update hosting request.
type UpdateHostingRequest struct {
// Region: region to target. If none is passed will use default region from the config.
Region scw.Region `json:"-"`
// HostingID: hosting ID.
HostingID string `json:"-"`
// Email: new contact email for the Web Hosting plan.
Email *string `json:"email,omitempty"`
// Tags: new tags for the Web Hosting plan.
Tags *[]string `json:"tags,omitempty"`
// OptionIDs: iDs of the new options for the Web Hosting plan.
OptionIDs *[]string `json:"option_ids,omitempty"`
// OfferID: ID of the new offer for the Web Hosting plan.
OfferID *string `json:"offer_id,omitempty"`
// Protected: whether the hosting is protected or not.
Protected *bool `json:"protected,omitempty"`
}
// This API allows you to manage your Web Hosting services.
type API struct {
client *scw.Client
}
// NewAPI returns a API object from a Scaleway client.
func NewAPI(client *scw.Client) *API {
return &API{
client: client,
}
}
func (s *API) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms}
}
// CreateHosting: Order a Web Hosting plan, specifying the offer type required via the `offer_id` parameter.
func (s *API) CreateHosting(req *CreateHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListHostings: List all of your existing Web Hosting plans. Various filters are available to limit the results, including filtering by domain, status, tag and Project ID.
func (s *API) ListHostings(req *ListHostingsRequest, opts ...scw.RequestOption) (*ListHostingsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "tags", req.Tags)
parameter.AddToQuery(query, "statuses", req.Statuses)
parameter.AddToQuery(query, "domain", req.Domain)
parameter.AddToQuery(query, "project_id", req.ProjectID)
parameter.AddToQuery(query, "organization_id", req.OrganizationID)
parameter.AddToQuery(query, "control_panels", req.ControlPanels)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings",
Query: query,
}
var resp ListHostingsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetHosting: Get the details of one of your existing Web Hosting plans, specified by its `hosting_id`.
func (s *API) GetHosting(req *GetHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateHosting: Update the details of one of your existing Web Hosting plans, specified by its `hosting_id`. You can update parameters including the contact email address, tags, options and offer.
func (s *API) UpdateHosting(req *UpdateHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteHosting: Delete a Web Hosting plan, specified by its `hosting_id`. Note that deletion is not immediate: it will take place at the end of the calendar month, after which time your Web Hosting plan and all its data (files and emails) will be irreversibly lost.
func (s *API) DeleteHosting(req *DeleteHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "",
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// RestoreHosting: When you [delete a Web Hosting plan](#path-hostings-delete-a-hosting), definitive deletion does not take place until the end of the calendar month. In the time between initiating the deletion, and definitive deletion at the end of the month, you can choose to **restore** the Web Hosting plan, using this endpoint and specifying its `hosting_id`.
func (s *API) RestoreHosting(req *RestoreHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/restore",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Hosting
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetDomainDNSRecords: Get the set of DNS records of a specified domain associated with a Web Hosting plan.
func (s *API) GetDomainDNSRecords(req *GetDomainDNSRecordsRequest, opts ...scw.RequestOption) (*DNSRecords, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.Domain) + "/dns-records",
}
var resp DNSRecords
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CheckUserOwnsDomain: "Check whether you own this domain or not.".
func (s *API) CheckUserOwnsDomain(req *CheckUserOwnsDomainRequest, opts ...scw.RequestOption) (*CheckUserOwnsDomainResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if req.ProjectID == "" {
defaultProjectID, _ := s.client.GetDefaultProjectID()
req.ProjectID = defaultProjectID
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.Domain) == "" {
return nil, errors.New("field Domain cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1/regions/" + fmt.Sprint(req.Region) + "/domains/" + fmt.Sprint(req.Domain) + "/check-ownership",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp CheckUserOwnsDomainResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListOffers: List the different Web Hosting offers, and their options, available to order from Scaleway.
func (s *API) ListOffers(req *ListOffersRequest, opts ...scw.RequestOption) (*ListOffersResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
query := url.Values{}
parameter.AddToQuery(query, "order_by", req.OrderBy)
parameter.AddToQuery(query, "without_options", req.WithoutOptions)
parameter.AddToQuery(query, "only_options", req.OnlyOptions)
parameter.AddToQuery(query, "hosting_id", req.HostingID)
parameter.AddToQuery(query, "control_panels", req.ControlPanels)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/offers",
Query: query,
}
var resp ListOffersResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListControlPanels: "List the control panels type: cpanel or plesk.".
func (s *API) ListControlPanels(req *ListControlPanelsRequest, opts ...scw.RequestOption) (*ListControlPanelsResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/control-panels",
Query: query,
}
var resp ListControlPanelsResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// CreateSession: Create a user session.
func (s *API) CreateSession(req *CreateSessionRequest, opts ...scw.RequestOption) (*Session, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/sessions",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Session
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ResetHostingPassword:
func (s *API) ResetHostingPassword(req *ResetHostingPasswordRequest, opts ...scw.RequestOption) (*ResetHostingPasswordResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.HostingID) == "" {
return nil, errors.New("field HostingID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/hostings/" + fmt.Sprint(req.HostingID) + "/reset-password",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp ResetHostingPasswordResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// This API allows you to manage your mailboxes for your Web Hosting services.
type ClassicMailAPI struct {
client *scw.Client
}
// NewClassicMailAPI returns a ClassicMailAPI object from a Scaleway client.
func NewClassicMailAPI(client *scw.Client) *ClassicMailAPI {
return &ClassicMailAPI{
client: client,
}
}
func (s *ClassicMailAPI) Regions() []scw.Region {
return []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}
}
// CreateMailbox: Create a new mailbox within your hosting plan.
func (s *ClassicMailAPI) CreateMailbox(req *ClassicMailAPICreateMailboxRequest, opts ...scw.RequestOption) (*Mailbox, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.OnlineID) == "" {
return nil, errors.New("field OnlineID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "POST",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/classic-hostings/" + fmt.Sprint(req.OnlineID) + "/mailboxes",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Mailbox
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// GetMailbox: Get a mailbox by id within your hosting plan.
func (s *ClassicMailAPI) GetMailbox(req *ClassicMailAPIGetMailboxRequest, opts ...scw.RequestOption) (*Mailbox, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.OnlineID) == "" {
return nil, errors.New("field OnlineID cannot be empty in request")
}
if fmt.Sprint(req.MailboxID) == "" {
return nil, errors.New("field MailboxID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/classic-hostings/" + fmt.Sprint(req.OnlineID) + "/mailboxes/" + fmt.Sprint(req.MailboxID) + "",
}
var resp Mailbox
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// ListMailboxes: List all mailboxes within your hosting plan.
func (s *ClassicMailAPI) ListMailboxes(req *ClassicMailAPIListMailboxesRequest, opts ...scw.RequestOption) (*ListMailboxesResponse, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
defaultPageSize, exist := s.client.GetDefaultPageSize()
if (req.PageSize == nil || *req.PageSize == 0) && exist {
req.PageSize = &defaultPageSize
}
query := url.Values{}
parameter.AddToQuery(query, "page", req.Page)
parameter.AddToQuery(query, "page_size", req.PageSize)
parameter.AddToQuery(query, "domain", req.Domain)
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.OnlineID) == "" {
return nil, errors.New("field OnlineID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/classic-hostings/" + fmt.Sprint(req.OnlineID) + "/mailboxes",
Query: query,
}
var resp ListMailboxesResponse
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// DeleteMailbox:
func (s *ClassicMailAPI) DeleteMailbox(req *ClassicMailAPIDeleteMailboxRequest, opts ...scw.RequestOption) (*Mailbox, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.OnlineID) == "" {
return nil, errors.New("field OnlineID cannot be empty in request")
}
if fmt.Sprint(req.MailboxID) == "" {
return nil, errors.New("field MailboxID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "DELETE",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/classic-hostings/" + fmt.Sprint(req.OnlineID) + "/mailboxes/" + fmt.Sprint(req.MailboxID) + "",
}
var resp Mailbox
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
// UpdateMailbox: Update the mailbox within your hosting plan.
func (s *ClassicMailAPI) UpdateMailbox(req *ClassicMailAPIUpdateMailboxRequest, opts ...scw.RequestOption) (*Mailbox, error) {
var err error
if req.Region == "" {
defaultRegion, _ := s.client.GetDefaultRegion()
req.Region = defaultRegion
}
if fmt.Sprint(req.Region) == "" {
return nil, errors.New("field Region cannot be empty in request")
}
if fmt.Sprint(req.OnlineID) == "" {
return nil, errors.New("field OnlineID cannot be empty in request")
}
if fmt.Sprint(req.MailboxID) == "" {
return nil, errors.New("field MailboxID cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/webhosting/v1alpha1/regions/" + fmt.Sprint(req.Region) + "/classic-hostings/" + fmt.Sprint(req.OnlineID) + "/mailboxes/" + fmt.Sprint(req.MailboxID) + "",
}
err = scwReq.SetBody(req)
if err != nil {
return nil, err
}
var resp Mailbox
err = s.client.Do(scwReq, &resp, opts...)
if err != nil {
return nil, err
}
return &resp, nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/api/webhosting/v1alpha1/webhosting_utils.go 0000664 0000000 0000000 00000003121 14747113137 0032520 0 ustar 00root root 0000000 0000000 package webhosting
import (
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 5 * time.Second
defaultTimeout = 5 * time.Minute
)
// WaitForHostingRequest is used by WaitForHosting method.
type WaitForHostingRequest struct {
HostingID string
Region scw.Region
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForHosting wait for a hosting to be in a "terminal state" before returning.
func (s *API) WaitForHosting(req *WaitForHostingRequest, opts ...scw.RequestOption) (*Hosting, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[HostingStatus]struct{}{
HostingStatusReady: {},
HostingStatusError: {},
HostingStatusUnknownStatus: {},
HostingStatusLocked: {},
}
res, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
hosting, err := s.GetHosting(&GetHostingRequest{
HostingID: req.HostingID,
Region: req.Region,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[hosting.Status]
return hosting, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for hosting failed")
}
return res.(*Hosting), nil
}
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/doc.go 0000664 0000000 0000000 00000000566 14747113137 0023347 0 ustar 00root root 0000000 0000000 // Package scalewaysdkgo is the Scaleway API SDK for Go.
//
// In order to use the available APIs, create a `Client`. Once created, it can be used to instantiate an API.
// To use the `instance` API, for example, instantiate it (with the client object) `instance.NewApi(client)`.
// On this instance API, all the available API functions can be called.
package scalewaysdkgo
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/docs/ 0000775 0000000 0000000 00000000000 14747113137 0023174 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/docs/CONTINUOUS_CODE_DEPLOYMENT.md 0000664 0000000 0000000 00000001643 14747113137 0027562 0 ustar 00root root 0000000 0000000 # Continuous code deployment
Part of this repo is automatically generated from our [protocol buffer](https://en.wikipedia.org/wiki/Protocol_Buffers) monorepo.
This enables us to keep Scaleway toolings up to date with the latest version of our APIs ([developer website](https://www.scaleway.com/en/developers/), soon-to-be CLI, ...).
## Generated files
Generated files and folders are located in [scaleway-sdk-go/api](../api).
They always start with the following line:
```c
// This file was automatically generated. DO NOT EDIT.
```
## Continuous deployment process
TODO: explains the continuous deployment process.
## Synchronization frequency
The continuous code deployment process can occur at anytime of the day, sometime many times a day.
Expect it to happen regularly.
## Any question?
If you have any question or request about the continuous code deployment process feel free to [reach us](../README.md#reach-us).
golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/docs/static_files/ 0000775 0000000 0000000 00000000000 14747113137 0025645 5 ustar 00root root 0000000 0000000 golang-github-scaleway-scaleway-sdk-go-1.0.0~beta32/docs/static_files/sdk-artwork.png 0000664 0000000 0000000 00000304701 14747113137 0030630 0 ustar 00root root 0000000 0000000 PNG
IHDR ) ō Ūä2 gAMA ąüa cHRM z&