diff --git a/.terraform.tfstate.lock.info b/.terraform.tfstate.lock.info deleted file mode 100644 index f69078b..0000000 --- a/.terraform.tfstate.lock.info +++ /dev/null @@ -1 +0,0 @@ -{"ID":"ce8a6c85-724a-2103-76d4-17478b531b03","Operation":"OperationTypeApply","Info":"","Who":"duy@duy-ThinkPad-T460","Version":"1.3.5","Created":"2023-02-08T09:12:08.869515269Z","Path":"terraform.tfstate"} \ No newline at end of file diff --git a/build.sh b/build.sh index 646bda0..048bee5 100755 --- a/build.sh +++ b/build.sh @@ -1,16 +1,17 @@ #bin/bash #export TF_LOG=debug rm -rf .terraform -rm -r .terraform.lock.hcl +rm -rf .terraform.* +#rm -rf terraform.* go build -o terraform-provider-vngcloud #OS_ARCH="$(go env GOHOSTOS)_$(go env GOHOSTARCH)" -OS_ARCH="linux_amd64" +OS_ARCH="darwin_amd64" echo $OS_ARCH #rm -rf ~/.terraform.d/plugins/vngcloud.vn/terraform/vngcloud/0.2 #mkdir -p ~/.terraform.d/plugins/vngcloud.vn/terraform/vngcloud/0.2/$OS_ARCH #mv terraform-provider-vngcloud ~/.terraform.d/plugins/vngcloud.vn/terraform/vngcloud/0.2/$OS_ARCH -rm -rf ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/0.2 -mkdir -p ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/0.2/$OS_ARCH -mv terraform-provider-vngcloud ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/0.2/$OS_ARCH -#terraform init +rm -rf ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/1.0.0 +mkdir -p ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/1.0.0/$OS_ARCH +mv terraform-provider-vngcloud ~/.terraform.d/plugins/registry.terraform.tunm4/vngcloud/vngcloud/1.0.0/$OS_ARCH +terraform init #terraform apply \ No newline at end of file diff --git a/client/client.go b/client/client.go index 4ce5af0..4ddc8d8 100644 --- a/client/client.go +++ b/client/client.go @@ -3,6 +3,7 @@ package client import ( "github.com/vngcloud/terraform-provider-vngcloud/client/authen" "github.com/vngcloud/terraform-provider-vngcloud/client/vdb" + "github.com/vngcloud/terraform-provider-vngcloud/client/vks" "github.com/vngcloud/terraform-provider-vngcloud/client/vloadbalancing" "github.com/vngcloud/terraform-provider-vngcloud/client/vserver" ) @@ -12,6 +13,7 @@ type Client struct { VserverClient *vserver.APIClient VdbClient *vdb.APIClient VlbClient *vloadbalancing.APIClient + VksClient *vks.APIClient ProjectId string } @@ -43,7 +45,7 @@ func NewClient(vdbBaseURL string, vserverBaseURL string, vlbBaseURL string, proj return client, nil } -func NewClientV2(vserverBaseURL string, vlbBaseURL string, ClientID string, ClientSecret string, TokenURL string) (*Client, error) { +func NewClientV2(vserverBaseURL string, vlbBaseURL string, vksBaseURL string, ClientID string, ClientSecret string, TokenURL string) (*Client, error) { authenConfig := authen.NewConfiguration(ClientID, ClientSecret, TokenURL) authenClient, err := authen.NewAuthenClient(authenConfig) if err != nil { @@ -56,10 +58,14 @@ func NewClientV2(vserverBaseURL string, vlbBaseURL string, ClientID string, Clie vlbConfig := vloadbalancing.NewConfiguration(vlbBaseURL, authenClient.Client) vlbClient := vloadbalancing.NewAPIClient(vlbConfig) + vksConfig := vks.NewConfiguration(vksBaseURL, authenClient.Client) + vksClient := vks.NewAPIClient(vksConfig) + client := &Client{ AuthenClient: authenClient, VserverClient: vserverClient, VdbClient: nil, + VksClient: vksClient, VlbClient: vlbClient, ProjectId: "projectId", } diff --git a/client/vks/README.md b/client/vks/README.md new file mode 100644 index 0000000..fdcb2fc --- /dev/null +++ b/client/vks/README.md @@ -0,0 +1,68 @@ +# Go API client for swagger + +No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: 1.0-SNAPSHOT +- Package version: 1.0.0 +- Build package: io.swagger.codegen.v3.generators.go.GoClientCodegen + +## Installation +Put the package under your project folder and add the following in import: +```golang +import "./swagger" +``` + +## Documentation for API Endpoints + +All URIs are relative to */* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*V1ClusterControllerApi* | [**V1ClustersClusterIdDelete**](docs/V1ClusterControllerApi.md#v1clustersclusteriddelete) | **Delete** /v1/clusters/{clusterId} | +*V1ClusterControllerApi* | [**V1ClustersClusterIdGet**](docs/V1ClusterControllerApi.md#v1clustersclusteridget) | **Get** /v1/clusters/{clusterId} | +*V1ClusterControllerApi* | [**V1ClustersClusterIdKubeconfigGet**](docs/V1ClusterControllerApi.md#v1clustersclusteridkubeconfigget) | **Get** /v1/clusters/{clusterId}/kubeconfig | +*V1ClusterControllerApi* | [**V1ClustersClusterIdPut**](docs/V1ClusterControllerApi.md#v1clustersclusteridput) | **Put** /v1/clusters/{clusterId} | +*V1ClusterControllerApi* | [**V1ClustersGet**](docs/V1ClusterControllerApi.md#v1clustersget) | **Get** /v1/clusters | +*V1ClusterControllerApi* | [**V1ClustersPost**](docs/V1ClusterControllerApi.md#v1clusterspost) | **Post** /v1/clusters | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsGet**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupsget) | **Get** /v1/clusters/{clusterId}/node-groups | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsNodeGroupIdDelete**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupsnodegroupiddelete) | **Delete** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsNodeGroupIdGet**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupsnodegroupidget) | **Get** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupsnodegroupidnodesget) | **Get** /v1/clusters/{clusterId}/node-groups/{nodeGroupId}/nodes | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsNodeGroupIdPut**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupsnodegroupidput) | **Put** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +*V1NodeGroupControllerApi* | [**V1ClustersClusterIdNodeGroupsPost**](docs/V1NodeGroupControllerApi.md#v1clustersclusteridnodegroupspost) | **Post** /v1/clusters/{clusterId}/node-groups | +*V1NodeGroupImageControllerApi* | [**V1NodeGroupImagesGet**](docs/V1NodeGroupImageControllerApi.md#v1nodegroupimagesget) | **Get** /v1/node-group-images | +*V1WorkspaceControllerApi* | [**V1WorkspaceGet**](docs/V1WorkspaceControllerApi.md#v1workspaceget) | **Get** /v1/workspace | +*V1WorkspaceControllerApi* | [**V1WorkspacePost**](docs/V1WorkspaceControllerApi.md#v1workspacepost) | **Post** /v1/workspace | +*V1WorkspaceControllerApi* | [**V1WorkspaceResetServiceAccountPost**](docs/V1WorkspaceControllerApi.md#v1workspaceresetserviceaccountpost) | **Post** /v1/workspace/reset-service-account | + +## Documentation For Models + + - [ClusterDetailDto](docs/ClusterDetailDto.md) + - [ClusterDto](docs/ClusterDto.md) + - [CreateClusterComboDto](docs/CreateClusterComboDto.md) + - [CreateNodeGroupDto](docs/CreateNodeGroupDto.md) + - [NetworkType](docs/NetworkType.md) + - [NodeDto](docs/NodeDto.md) + - [NodeGroupAutoScaleConfigDto](docs/NodeGroupAutoScaleConfigDto.md) + - [NodeGroupDetailDto](docs/NodeGroupDetailDto.md) + - [NodeGroupDto](docs/NodeGroupDto.md) + - [NodeGroupImageDto](docs/NodeGroupImageDto.md) + - [NodeGroupTaintDto](docs/NodeGroupTaintDto.md) + - [NodeGroupUpgradeConfigDto](docs/NodeGroupUpgradeConfigDto.md) + - [PagingResultDtoClusterDto](docs/PagingResultDtoClusterDto.md) + - [PagingResultDtoNodeDto](docs/PagingResultDtoNodeDto.md) + - [PagingResultDtoNodeGroupDto](docs/PagingResultDtoNodeGroupDto.md) + - [UpdateClusterDto](docs/UpdateClusterDto.md) + - [UpdateNodeGroupDto](docs/UpdateNodeGroupDto.md) + - [WorkspaceDto](docs/WorkspaceDto.md) + +## Documentation For Authorization + Endpoints do not require authorization. + + +## Author + + diff --git a/client/vks/api/swagger.yaml b/client/vks/api/swagger.yaml new file mode 100644 index 0000000..71f857d --- /dev/null +++ b/client/vks/api/swagger.yaml @@ -0,0 +1,1083 @@ +openapi: 3.0.3 +info: + title: vks-api API + version: 1.0-SNAPSHOT +servers: +- url: / +paths: + /v1/clusters: + get: + tags: + - V 1 Cluster Controller + parameters: + - name: filter + in: query + required: false + style: form + explode: true + schema: + type: string + default: "{}" + - name: page + in: query + required: false + style: form + explode: true + schema: + minimum: 0 + type: integer + format: int32 + default: 0 + - name: pageSize + in: query + required: false + style: form + explode: true + schema: + minimum: 1 + type: integer + format: int32 + default: 10 + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PagingResultDtoClusterDto' + post: + tags: + - V 1 Cluster Controller + parameters: + - name: poc + in: query + required: false + style: form + explode: true + schema: + type: boolean + default: false + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateClusterComboDto' + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ClusterDto' + /v1/clusters/{clusterId}: + get: + tags: + - V 1 Cluster Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ClusterDetailDto' + put: + tags: + - V 1 Cluster Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateClusterDto' + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ClusterDto' + delete: + tags: + - V 1 Cluster Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ClusterDto' + /v1/clusters/{clusterId}/kubeconfig: + get: + tags: + - V 1 Cluster Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + text/plain: + schema: + type: string + x-content-type: text/plain + /v1/clusters/{clusterId}/node-groups: + get: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: page + in: query + required: false + style: form + explode: true + schema: + minimum: 0 + type: integer + format: int32 + default: 0 + - name: pageSize + in: query + required: false + style: form + explode: true + schema: + minimum: 1 + type: integer + format: int32 + default: 10 + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PagingResultDtoNodeGroupDto' + post: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateNodeGroupDto' + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/NodeGroupDto' + /v1/clusters/{clusterId}/node-groups/{nodeGroupId}: + get: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: nodeGroupId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/NodeGroupDetailDto' + put: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: nodeGroupId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateNodeGroupDto' + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/NodeGroupDto' + delete: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: nodeGroupId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/NodeGroupDto' + /v1/clusters/{clusterId}/node-groups/{nodeGroupId}/nodes: + get: + tags: + - V 1 Node Group Controller + parameters: + - name: clusterId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: nodeGroupId + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: page + in: query + required: false + style: form + explode: true + schema: + minimum: 0 + type: integer + format: int32 + default: 0 + - name: pageSize + in: query + required: false + style: form + explode: true + schema: + minimum: 1 + type: integer + format: int32 + default: 10 + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PagingResultDtoNodeDto' + /v1/node-group-images: + get: + tags: + - V 1 Node Group Image Controller + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NodeGroupImageDto' + x-content-type: application/json + /v1/workspace: + get: + tags: + - V 1 Workspace Controller + parameters: + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/WorkspaceDto' + post: + tags: + - V 1 Workspace Controller + parameters: + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/WorkspaceDto' + /v1/workspace/reset-service-account: + post: + tags: + - V 1 Workspace Controller + parameters: + - name: portal-user-id + in: header + required: false + style: simple + explode: false + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/WorkspaceDto' +components: + schemas: + ClusterDetailDto: + type: object + properties: + id: + type: string + name: + type: string + description: + type: string + status: + type: string + version: + type: string + numNodes: + type: integer + format: int64 + createdAt: + $ref: '#/components/schemas/Date' + updatedAt: + $ref: '#/components/schemas/Date' + enablePrivateCluster: + type: boolean + networkType: + $ref: '#/components/schemas/NetworkType' + vpcId: + type: string + subnetId: + type: string + cidr: + type: string + enabledLoadBalancerPlugin: + type: boolean + enabledBlockStoreCsiPlugin: + type: boolean + whitelistNodeCIDRs: + type: array + items: + type: string + example: + subnetId: subnetId + enabledBlockStoreCsiPlugin: true + enabledLoadBalancerPlugin: true + whitelistNodeCIDRs: + - whitelistNodeCIDRs + - whitelistNodeCIDRs + description: description + version: version + createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + vpcId: vpcId + name: name + cidr: cidr + id: id + networkType: CALICO + enablePrivateCluster: true + status: status + updatedAt: null + ClusterDto: + type: object + properties: + id: + type: string + name: + type: string + description: + type: string + status: + type: string + version: + type: string + numNodes: + type: integer + format: int64 + createdAt: + $ref: '#/components/schemas/Date' + updatedAt: + $ref: '#/components/schemas/Date' + example: + createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + name: name + description: description + id: id + version: version + status: status + updatedAt: null + CreateClusterComboDto: + required: + - cidr + - enablePrivateCluster + - name + - networkType + - nodeGroups + - subnetId + - version + - vpcId + type: object + properties: + name: + pattern: "^[a-zA-Z0-9_\\-.]{5,50}$" + type: string + description: + pattern: "^[a-zA-Z0-9_\\-. @]{0,255}$" + type: string + version: + pattern: "^v[0-9]+.[0-9]+.[0-9]+$" + type: string + enablePrivateCluster: + type: boolean + networkType: + pattern: ^CALICO$ + type: string + vpcId: + maxLength: 50 + minLength: 1 + type: string + subnetId: + maxLength: 50 + minLength: 1 + type: string + cidr: + pattern: "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,2}$" + type: string + enabledLoadBalancerPlugin: + type: boolean + enabledBlockStoreCsiPlugin: + type: boolean + nodeGroups: + maxItems: 100 + minItems: 1 + type: array + items: + $ref: '#/components/schemas/CreateNodeGroupDto' + CreateNodeGroupDto: + required: + - diskSize + - diskType + - enablePrivateNodes + - flavorId + - imageId + - name + - numNodes + - securityGroups + - sshKeyId + - upgradeConfig + type: object + properties: + name: + maxLength: 50 + minLength: 5 + pattern: "^[a-zA-Z0-9_\\-.]+$" + type: string + numNodes: + maximum: 100 + minimum: 1 + type: integer + format: int32 + autoScaleConfig: + $ref: '#/components/schemas/NodeGroupAutoScaleConfigDto' + upgradeConfig: + $ref: '#/components/schemas/NodeGroupUpgradeConfigDto' + imageId: + maxLength: 50 + minLength: 1 + type: string + flavorId: + maxLength: 50 + minLength: 1 + type: string + diskSize: + maximum: 5000 + minimum: 20 + type: integer + format: int32 + diskType: + maxLength: 50 + minLength: 1 + type: string + enablePrivateNodes: + type: boolean + securityGroups: + type: array + items: + type: string + sshKeyId: + maxLength: 50 + minLength: 1 + type: string + labels: + type: object + additionalProperties: + type: string + taints: + maxItems: 50 + type: array + items: + $ref: '#/components/schemas/NodeGroupTaintDto' + Date: + type: string + format: date + example: 2022-03-10 + NetworkType: + type: string + enum: + - CALICO + - CILIUM + NodeDto: + type: object + properties: + id: + type: string + name: + type: string + status: + type: string + floatingIp: + type: string + fixedIp: + type: string + ready: + type: boolean + example: + floatingIp: floatingIp + ready: true + name: name + fixedIp: fixedIp + id: id + status: status + NodeGroupAutoScaleConfigDto: + required: + - maxSize + - minSize + type: object + properties: + minSize: + maximum: 100 + minimum: 1 + type: integer + format: int32 + maxSize: + maximum: 100 + minimum: 1 + type: integer + format: int32 + example: + minSize: 15 + maxSize: 60 + NodeGroupDetailDto: + type: object + properties: + id: + type: string + clusterId: + type: string + name: + type: string + status: + type: string + numNodes: + type: integer + format: int64 + imageId: + type: string + createdAt: + $ref: '#/components/schemas/Date' + updatedAt: + $ref: '#/components/schemas/Date' + flavorId: + type: string + diskSize: + type: integer + format: int32 + diskType: + type: string + enablePrivateNodes: + type: boolean + sshKeyId: + type: string + securityGroups: + type: array + items: + type: string + autoScaleConfig: + $ref: '#/components/schemas/NodeGroupAutoScaleConfigDto' + upgradeConfig: + $ref: '#/components/schemas/NodeGroupUpgradeConfigDto' + labels: + type: object + additionalProperties: + type: string + taints: + type: array + items: + $ref: '#/components/schemas/NodeGroupTaintDto' + example: + imageId: imageId + enablePrivateNodes: true + autoScaleConfig: + minSize: 15 + maxSize: 60 + flavorId: flavorId + clusterId: clusterId + taints: + - effect: effect + value: value + key: key + - effect: effect + value: value + key: key + sshKeyId: sshKeyId + upgradeConfig: + maxSurge: 56 + maxUnavailable: 23 + strategy: strategy + labels: + key: labels + createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + diskSize: 6 + name: name + securityGroups: + - securityGroups + - securityGroups + id: id + diskType: diskType + status: status + updatedAt: null + NodeGroupDto: + type: object + properties: + id: + type: string + clusterId: + type: string + name: + type: string + status: + type: string + numNodes: + type: integer + format: int64 + imageId: + type: string + createdAt: + $ref: '#/components/schemas/Date' + updatedAt: + $ref: '#/components/schemas/Date' + example: + createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + imageId: imageId + name: name + id: id + clusterId: clusterId + status: status + updatedAt: null + NodeGroupImageDto: + type: object + properties: + id: + type: string + os: + type: string + kubernetesVersion: + type: string + enable: + type: boolean + example: + os: os + enable: true + id: id + kubernetesVersion: kubernetesVersion + NodeGroupTaintDto: + required: + - effect + - key + - value + type: object + properties: + key: + pattern: "^([a-zA-Z0-9]([a-zA-Z0-9._\\-/][a-zA-Z0-9])?){1,63}$" + type: string + value: + pattern: "^[a-zA-Z0-9._\\-/]{1,63}$" + type: string + effect: + pattern: ^NoSchedule|PreferNoSchedule|NoExecute$ + type: string + example: + effect: effect + value: value + key: key + NodeGroupUpgradeConfigDto: + required: + - strategy + type: object + properties: + strategy: + pattern: ^SURGE$ + type: string + maxSurge: + maximum: 100 + minimum: 1 + type: integer + format: int32 + maxUnavailable: + maximum: 100 + minimum: 0 + type: integer + format: int32 + example: + maxSurge: 56 + maxUnavailable: 23 + strategy: strategy + PagingResultDtoClusterDto: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/ClusterDto' + total: + type: integer + format: int64 + page: + type: integer + format: int32 + pageSize: + type: integer + format: int32 + example: + total: 6 + pageSize: 5 + page: 1 + items: + - createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + name: name + description: description + id: id + version: version + status: status + updatedAt: null + - createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + name: name + description: description + id: id + version: version + status: status + updatedAt: null + PagingResultDtoNodeDto: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/NodeDto' + total: + type: integer + format: int64 + page: + type: integer + format: int32 + pageSize: + type: integer + format: int32 + example: + total: 0 + pageSize: 1 + page: 6 + items: + - floatingIp: floatingIp + ready: true + name: name + fixedIp: fixedIp + id: id + status: status + - floatingIp: floatingIp + ready: true + name: name + fixedIp: fixedIp + id: id + status: status + PagingResultDtoNodeGroupDto: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/NodeGroupDto' + total: + type: integer + format: int64 + page: + type: integer + format: int32 + pageSize: + type: integer + format: int32 + example: + total: 6 + pageSize: 5 + page: 1 + items: + - createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + imageId: imageId + name: name + id: id + clusterId: clusterId + status: status + updatedAt: null + - createdAt: 2022-03-10T00:00:00.000+00:00 + numNodes: 0 + imageId: imageId + name: name + id: id + clusterId: clusterId + status: status + updatedAt: null + UpdateClusterDto: + required: + - version + - whitelistNodeCIDRs + type: object + properties: + version: + type: string + whitelistNodeCIDRs: + maxItems: 10 + minItems: 1 + type: array + items: + type: string + UpdateNodeGroupDto: + required: + - imageId + - securityGroups + - upgradeConfig + type: object + properties: + autoScaleConfig: + $ref: '#/components/schemas/NodeGroupAutoScaleConfigDto' + numNodes: + maximum: 100 + minimum: 1 + type: integer + format: int64 + upgradeConfig: + $ref: '#/components/schemas/NodeGroupUpgradeConfigDto' + securityGroups: + type: array + items: + type: string + imageId: + maxLength: 50 + minLength: 1 + type: string + WorkspaceDto: + type: object + properties: + projectId: + type: string + serviceAccountId: + type: string + status: + type: string + example: + serviceAccountId: serviceAccountId + projectId: projectId + status: status diff --git a/client/vks/api_v1_cluster_controller.go b/client/vks/api_v1_cluster_controller.go new file mode 100644 index 0000000..3d84832 --- /dev/null +++ b/client/vks/api_v1_cluster_controller.go @@ -0,0 +1,629 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "bytes" + "context" + "fmt" + "github.com/antihax/optional" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type V1ClusterControllerApiService service + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1ClusterControllerApiV1ClustersClusterIdDeleteOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return ClusterDto +*/ + +type V1ClusterControllerApiV1ClustersClusterIdDeleteOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1ClusterControllerApiService) V1ClustersClusterIdDelete(ctx context.Context, clusterId string, localVarOptionals *V1ClusterControllerApiV1ClustersClusterIdDeleteOpts) (ClusterDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Delete") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ClusterDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v ClusterDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1ClusterControllerApiV1ClustersClusterIdGetOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return ClusterDetailDto +*/ + +type V1ClusterControllerApiV1ClustersClusterIdGetOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1ClusterControllerApiService) V1ClustersClusterIdGet(ctx context.Context, clusterId string, localVarOptionals *V1ClusterControllerApiV1ClustersClusterIdGetOpts) (ClusterDetailDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ClusterDetailDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v ClusterDetailDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1ClusterControllerApiV1ClustersClusterIdKubeconfigGetOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return string +*/ + +type V1ClusterControllerApiV1ClustersClusterIdKubeconfigGetOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1ClusterControllerApiService) V1ClustersClusterIdKubeconfigGet(ctx context.Context, clusterId string, localVarOptionals *V1ClusterControllerApiV1ClustersClusterIdKubeconfigGetOpts) (string, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue string + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/kubeconfig" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"text/plain"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v string + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return string(localVarBody), localVarHttpResponse, nil +} + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1ClusterControllerApiV1ClustersClusterIdPutOpts - Optional Parameters: + * @param "Body" (optional.Interface of UpdateClusterDto) - + * @param "PortalUserId" (optional.Int64) - +@return ClusterDto +*/ + +type V1ClusterControllerApiV1ClustersClusterIdPutOpts struct { + Body optional.Interface + PortalUserId optional.Int64 +} + +func (a *V1ClusterControllerApiService) V1ClustersClusterIdPut(ctx context.Context, clusterId string, localVarOptionals *V1ClusterControllerApiV1ClustersClusterIdPutOpts) (ClusterDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Put") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ClusterDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + // body params + if localVarOptionals != nil && localVarOptionals.Body.IsSet() { + + localVarOptionalBody := localVarOptionals.Body.Value() + localVarPostBody = &localVarOptionalBody + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v ClusterDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param optional nil or *V1ClusterControllerApiV1ClustersGetOpts - Optional Parameters: + * @param "Filter" (optional.String) - + * @param "Page" (optional.Int32) - + * @param "PageSize" (optional.Int32) - + * @param "PortalUserId" (optional.Int64) - +@return PagingResultDtoClusterDto +*/ + +type V1ClusterControllerApiV1ClustersGetOpts struct { + Filter optional.String + Page optional.Int32 + PageSize optional.Int32 + PortalUserId optional.Int64 +} + +func (a *V1ClusterControllerApiService) V1ClustersGet(ctx context.Context, localVarOptionals *V1ClusterControllerApiV1ClustersGetOpts) (PagingResultDtoClusterDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue PagingResultDtoClusterDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if localVarOptionals != nil && localVarOptionals.Filter.IsSet() { + localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), "")) + } + if localVarOptionals != nil && localVarOptionals.Page.IsSet() { + localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) + } + if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() { + localVarQueryParams.Add("pageSize", parameterToString(localVarOptionals.PageSize.Value(), "")) + } + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v PagingResultDtoClusterDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1ClusterControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param optional nil or *V1ClusterControllerApiV1ClustersPostOpts - Optional Parameters: + * @param "Body" (optional.Interface of CreateClusterComboDto) - + * @param "PortalUserId" (optional.Int64) - + * @param "Poc" (optional.Bool) - +@return ClusterDto +*/ + +type V1ClusterControllerApiV1ClustersPostOpts struct { + Body optional.Interface + PortalUserId optional.Int64 + Poc optional.Bool +} + +func (a *V1ClusterControllerApiService) V1ClustersPost(ctx context.Context, localVarOptionals *V1ClusterControllerApiV1ClustersPostOpts) (ClusterDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue ClusterDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if localVarOptionals != nil && localVarOptionals.Poc.IsSet() { + localVarQueryParams.Add("poc", parameterToString(localVarOptionals.Poc.Value(), "")) + } + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + // body params + if localVarOptionals != nil && localVarOptionals.Body.IsSet() { + + localVarOptionalBody := localVarOptionals.Body.Value() + localVarPostBody = &localVarOptionalBody + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v ClusterDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/client/vks/api_v1_node_group_controller.go b/client/vks/api_v1_node_group_controller.go new file mode 100644 index 0000000..dc5fe34 --- /dev/null +++ b/client/vks/api_v1_node_group_controller.go @@ -0,0 +1,641 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "bytes" + "context" + "fmt" + "github.com/antihax/optional" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type V1NodeGroupControllerApiService service + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsGetOpts - Optional Parameters: + * @param "Page" (optional.Int32) - + * @param "PageSize" (optional.Int32) - + * @param "PortalUserId" (optional.Int64) - +@return PagingResultDtoNodeGroupDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsGetOpts struct { + Page optional.Int32 + PageSize optional.Int32 + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsGet(ctx context.Context, clusterId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsGetOpts) (PagingResultDtoNodeGroupDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue PagingResultDtoNodeGroupDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if localVarOptionals != nil && localVarOptionals.Page.IsSet() { + localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) + } + if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() { + localVarQueryParams.Add("pageSize", parameterToString(localVarOptionals.PageSize.Value(), "")) + } + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v PagingResultDtoNodeGroupDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param nodeGroupId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdDeleteOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return NodeGroupDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdDeleteOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsNodeGroupIdDelete(ctx context.Context, clusterId string, nodeGroupId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdDeleteOpts) (NodeGroupDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Delete") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue NodeGroupDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups/{nodeGroupId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + localVarPath = strings.Replace(localVarPath, "{"+"nodeGroupId"+"}", fmt.Sprintf("%v", nodeGroupId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v NodeGroupDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param nodeGroupId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdGetOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return NodeGroupDetailDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdGetOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsNodeGroupIdGet(ctx context.Context, clusterId string, nodeGroupId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdGetOpts) (NodeGroupDetailDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue NodeGroupDetailDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups/{nodeGroupId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + localVarPath = strings.Replace(localVarPath, "{"+"nodeGroupId"+"}", fmt.Sprintf("%v", nodeGroupId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v NodeGroupDetailDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param nodeGroupId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdNodesGetOpts - Optional Parameters: + * @param "Page" (optional.Int32) - + * @param "PageSize" (optional.Int32) - + * @param "PortalUserId" (optional.Int64) - +@return PagingResultDtoNodeDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdNodesGetOpts struct { + Page optional.Int32 + PageSize optional.Int32 + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet(ctx context.Context, clusterId string, nodeGroupId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdNodesGetOpts) (PagingResultDtoNodeDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue PagingResultDtoNodeDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups/{nodeGroupId}/nodes" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + localVarPath = strings.Replace(localVarPath, "{"+"nodeGroupId"+"}", fmt.Sprintf("%v", nodeGroupId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if localVarOptionals != nil && localVarOptionals.Page.IsSet() { + localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) + } + if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() { + localVarQueryParams.Add("pageSize", parameterToString(localVarOptionals.PageSize.Value(), "")) + } + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v PagingResultDtoNodeDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param nodeGroupId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts - Optional Parameters: + * @param "Body" (optional.Interface of UpdateNodeGroupDto) - + * @param "PortalUserId" (optional.Int64) - +@return NodeGroupDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts struct { + Body optional.Interface + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsNodeGroupIdPut(ctx context.Context, clusterId string, nodeGroupId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts) (NodeGroupDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Put") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue NodeGroupDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups/{nodeGroupId}" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + localVarPath = strings.Replace(localVarPath, "{"+"nodeGroupId"+"}", fmt.Sprintf("%v", nodeGroupId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + // body params + if localVarOptionals != nil && localVarOptionals.Body.IsSet() { + + localVarOptionalBody := localVarOptionals.Body.Value() + localVarPostBody = &localVarOptionalBody + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v NodeGroupDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1NodeGroupControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param clusterId + * @param optional nil or *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts - Optional Parameters: + * @param "Body" (optional.Interface of CreateNodeGroupDto) - + * @param "PortalUserId" (optional.Int64) - +@return NodeGroupDto +*/ + +type V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts struct { + Body optional.Interface + PortalUserId optional.Int64 +} + +func (a *V1NodeGroupControllerApiService) V1ClustersClusterIdNodeGroupsPost(ctx context.Context, clusterId string, localVarOptionals *V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts) (NodeGroupDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue NodeGroupDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/clusters/{clusterId}/node-groups" + localVarPath = strings.Replace(localVarPath, "{"+"clusterId"+"}", fmt.Sprintf("%v", clusterId), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + // body params + if localVarOptionals != nil && localVarOptionals.Body.IsSet() { + + localVarOptionalBody := localVarOptionals.Body.Value() + localVarPostBody = &localVarOptionalBody + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v NodeGroupDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/client/vks/api_v1_node_group_image_controller.go b/client/vks/api_v1_node_group_image_controller.go new file mode 100644 index 0000000..9decd0a --- /dev/null +++ b/client/vks/api_v1_node_group_image_controller.go @@ -0,0 +1,110 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "bytes" + "context" + _ "fmt" + _ "github.com/antihax/optional" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type V1NodeGroupImageControllerApiService service + +/* +V1NodeGroupImageControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return []NodeGroupImageDto +*/ +func (a *V1NodeGroupImageControllerApiService) V1NodeGroupImagesGet(ctx context.Context) ([]NodeGroupImageDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue []NodeGroupImageDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/node-group-images" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v []NodeGroupImageDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/client/vks/api_v1_workspace_controller.go b/client/vks/api_v1_workspace_controller.go new file mode 100644 index 0000000..8dca774 --- /dev/null +++ b/client/vks/api_v1_workspace_controller.go @@ -0,0 +1,306 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "bytes" + "context" + _ "fmt" + "github.com/antihax/optional" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type V1WorkspaceControllerApiService service + +/* +V1WorkspaceControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param optional nil or *V1WorkspaceControllerApiV1WorkspaceGetOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return WorkspaceDto +*/ + +type V1WorkspaceControllerApiV1WorkspaceGetOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1WorkspaceControllerApiService) V1WorkspaceGet(ctx context.Context, localVarOptionals *V1WorkspaceControllerApiV1WorkspaceGetOpts) (WorkspaceDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue WorkspaceDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/workspace" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v WorkspaceDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1WorkspaceControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param optional nil or *V1WorkspaceControllerApiV1WorkspacePostOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return WorkspaceDto +*/ + +type V1WorkspaceControllerApiV1WorkspacePostOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1WorkspaceControllerApiService) V1WorkspacePost(ctx context.Context, localVarOptionals *V1WorkspaceControllerApiV1WorkspacePostOpts) (WorkspaceDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue WorkspaceDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/workspace" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v WorkspaceDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +V1WorkspaceControllerApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param optional nil or *V1WorkspaceControllerApiV1WorkspaceResetServiceAccountPostOpts - Optional Parameters: + * @param "PortalUserId" (optional.Int64) - +@return WorkspaceDto +*/ + +type V1WorkspaceControllerApiV1WorkspaceResetServiceAccountPostOpts struct { + PortalUserId optional.Int64 +} + +func (a *V1WorkspaceControllerApiService) V1WorkspaceResetServiceAccountPost(ctx context.Context, localVarOptionals *V1WorkspaceControllerApiV1WorkspaceResetServiceAccountPostOpts) (WorkspaceDto, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue WorkspaceDto + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/v1/workspace/reset-service-account" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + if localVarOptionals != nil && localVarOptionals.PortalUserId.IsSet() { + localVarHeaderParams["portal-user-id"] = parameterToString(localVarOptionals.PortalUserId.Value(), "") + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, _ := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err == nil { + return localVarReturnValue, localVarHttpResponse, err + } + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + if localVarHttpResponse.StatusCode == 200 { + var v WorkspaceDto + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/client/vks/client.go b/client/vks/client.go new file mode 100644 index 0000000..ef7ded7 --- /dev/null +++ b/client/vks/client.go @@ -0,0 +1,482 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") +) + +// APIClient manages communication with the vks-api API API v1.0-SNAPSHOT +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + V1ClusterControllerApi *V1ClusterControllerApiService + + V1NodeGroupControllerApi *V1NodeGroupControllerApiService + + V1NodeGroupImageControllerApi *V1NodeGroupImageControllerApiService + + V1WorkspaceControllerApi *V1WorkspaceControllerApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.V1ClusterControllerApi = (*V1ClusterControllerApiService)(&c.common) + c.V1NodeGroupControllerApi = (*V1NodeGroupControllerApiService)(&c.common) + c.V1NodeGroupImageControllerApi = (*V1NodeGroupImageControllerApiService)(&c.common) + c.V1WorkspaceControllerApi = (*V1WorkspaceControllerApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath(path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Override request host, if applicable + if c.cfg.Host != "" { + localVarRequest.Host = c.cfg.Host + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if strings.Contains(contentType, "application/xml") { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } else if strings.Contains(contentType, "application/json") { + if err = json.Unmarshal(b, v); err != nil { + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericSwaggerError Provides access to the body, error and model on returned errors. +type GenericSwaggerError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericSwaggerError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericSwaggerError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericSwaggerError) Model() interface{} { + return e.model +} diff --git a/client/vks/configuration.go b/client/vks/configuration.go new file mode 100644 index 0000000..8063145 --- /dev/null +++ b/client/vks/configuration.go @@ -0,0 +1,72 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "net/http" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKey takes an APIKey as authentication for the request + ContextAPIKey = contextKey("apikey") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +type Configuration struct { + BasePath string `json:"basePath,omitempty"` + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + HTTPClient *http.Client +} + +func NewConfiguration(BasePath string, HTTPClient *http.Client) *Configuration { + cfg := &Configuration{ + BasePath: BasePath, + DefaultHeader: make(map[string]string), + HTTPClient: HTTPClient, + UserAgent: "terraform", + } + return cfg +} + +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} diff --git a/client/vks/docs/ClusterDetailDto.md b/client/vks/docs/ClusterDetailDto.md new file mode 100644 index 0000000..71423b6 --- /dev/null +++ b/client/vks/docs/ClusterDetailDto.md @@ -0,0 +1,24 @@ +# ClusterDetailDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] +**Description** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] +**Version** | **string** | | [optional] [default to null] +**NumNodes** | **int64** | | [optional] [default to null] +**CreatedAt** | **string** | | [optional] [default to null] +**UpdatedAt** | **string** | | [optional] [default to null] +**EnablePrivateCluster** | **bool** | | [optional] [default to null] +**NetworkType** | [***NetworkType**](NetworkType.md) | | [optional] [default to null] +**VpcId** | **string** | | [optional] [default to null] +**SubnetId** | **string** | | [optional] [default to null] +**Cidr** | **string** | | [optional] [default to null] +**EnabledLoadBalancerPlugin** | **bool** | | [optional] [default to null] +**EnabledBlockStoreCsiPlugin** | **bool** | | [optional] [default to null] +**WhitelistNodeCIDRs** | **[]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/ClusterDto.md b/client/vks/docs/ClusterDto.md new file mode 100644 index 0000000..43cb02b --- /dev/null +++ b/client/vks/docs/ClusterDto.md @@ -0,0 +1,16 @@ +# ClusterDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] +**Description** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] +**Version** | **string** | | [optional] [default to null] +**NumNodes** | **int64** | | [optional] [default to null] +**CreatedAt** | **string** | | [optional] [default to null] +**UpdatedAt** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/CreateClusterComboDto.md b/client/vks/docs/CreateClusterComboDto.md new file mode 100644 index 0000000..2e10ddd --- /dev/null +++ b/client/vks/docs/CreateClusterComboDto.md @@ -0,0 +1,19 @@ +# CreateClusterComboDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [default to null] +**Description** | **string** | | [optional] [default to null] +**Version** | **string** | | [default to null] +**EnablePrivateCluster** | **bool** | | [default to null] +**NetworkType** | **string** | | [default to null] +**VpcId** | **string** | | [default to null] +**SubnetId** | **string** | | [default to null] +**Cidr** | **string** | | [default to null] +**EnabledLoadBalancerPlugin** | **bool** | | [optional] [default to null] +**EnabledBlockStoreCsiPlugin** | **bool** | | [optional] [default to null] +**NodeGroups** | [**[]CreateNodeGroupDto**](CreateNodeGroupDto.md) | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/CreateNodeGroupDto.md b/client/vks/docs/CreateNodeGroupDto.md new file mode 100644 index 0000000..a683c1e --- /dev/null +++ b/client/vks/docs/CreateNodeGroupDto.md @@ -0,0 +1,21 @@ +# CreateNodeGroupDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [default to null] +**NumNodes** | **int32** | | [default to null] +**AutoScaleConfig** | [***NodeGroupAutoScaleConfigDto**](NodeGroupAutoScaleConfigDto.md) | | [optional] [default to null] +**UpgradeConfig** | [***NodeGroupUpgradeConfigDto**](NodeGroupUpgradeConfigDto.md) | | [default to null] +**ImageId** | **string** | | [default to null] +**FlavorId** | **string** | | [default to null] +**DiskSize** | **int32** | | [default to null] +**DiskType** | **string** | | [default to null] +**EnablePrivateNodes** | **bool** | | [default to null] +**SecurityGroups** | **[]string** | | [default to null] +**SshKeyId** | **string** | | [default to null] +**Labels** | **map[string]string** | | [optional] [default to null] +**Taints** | [**[]NodeGroupTaintDto**](NodeGroupTaintDto.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NetworkType.md b/client/vks/docs/NetworkType.md new file mode 100644 index 0000000..80bd442 --- /dev/null +++ b/client/vks/docs/NetworkType.md @@ -0,0 +1,8 @@ +# NetworkType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeDto.md b/client/vks/docs/NodeDto.md new file mode 100644 index 0000000..37c654e --- /dev/null +++ b/client/vks/docs/NodeDto.md @@ -0,0 +1,14 @@ +# NodeDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] +**FloatingIp** | **string** | | [optional] [default to null] +**FixedIp** | **string** | | [optional] [default to null] +**Ready** | **bool** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupAutoScaleConfigDto.md b/client/vks/docs/NodeGroupAutoScaleConfigDto.md new file mode 100644 index 0000000..2c8b1db --- /dev/null +++ b/client/vks/docs/NodeGroupAutoScaleConfigDto.md @@ -0,0 +1,10 @@ +# NodeGroupAutoScaleConfigDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MinSize** | **int32** | | [default to null] +**MaxSize** | **int32** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupDetailDto.md b/client/vks/docs/NodeGroupDetailDto.md new file mode 100644 index 0000000..221ff41 --- /dev/null +++ b/client/vks/docs/NodeGroupDetailDto.md @@ -0,0 +1,26 @@ +# NodeGroupDetailDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**ClusterId** | **string** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] +**NumNodes** | **int64** | | [optional] [default to null] +**ImageId** | **string** | | [optional] [default to null] +**CreatedAt** | **string** | | [optional] [default to null] +**UpdatedAt** | **string** | | [optional] [default to null] +**FlavorId** | **string** | | [optional] [default to null] +**DiskSize** | **int32** | | [optional] [default to null] +**DiskType** | **string** | | [optional] [default to null] +**EnablePrivateNodes** | **bool** | | [optional] [default to null] +**SshKeyId** | **string** | | [optional] [default to null] +**SecurityGroups** | **[]string** | | [optional] [default to null] +**AutoScaleConfig** | [***NodeGroupAutoScaleConfigDto**](NodeGroupAutoScaleConfigDto.md) | | [optional] [default to null] +**UpgradeConfig** | [***NodeGroupUpgradeConfigDto**](NodeGroupUpgradeConfigDto.md) | | [optional] [default to null] +**Labels** | **map[string]string** | | [optional] [default to null] +**Taints** | [**[]NodeGroupTaintDto**](NodeGroupTaintDto.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupDto.md b/client/vks/docs/NodeGroupDto.md new file mode 100644 index 0000000..e672005 --- /dev/null +++ b/client/vks/docs/NodeGroupDto.md @@ -0,0 +1,16 @@ +# NodeGroupDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**ClusterId** | **string** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] +**NumNodes** | **int64** | | [optional] [default to null] +**ImageId** | **string** | | [optional] [default to null] +**CreatedAt** | **string** | | [optional] [default to null] +**UpdatedAt** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupImageDto.md b/client/vks/docs/NodeGroupImageDto.md new file mode 100644 index 0000000..06e67e8 --- /dev/null +++ b/client/vks/docs/NodeGroupImageDto.md @@ -0,0 +1,12 @@ +# NodeGroupImageDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] +**Os** | **string** | | [optional] [default to null] +**KubernetesVersion** | **string** | | [optional] [default to null] +**Enable** | **bool** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupTaintDto.md b/client/vks/docs/NodeGroupTaintDto.md new file mode 100644 index 0000000..73bfc68 --- /dev/null +++ b/client/vks/docs/NodeGroupTaintDto.md @@ -0,0 +1,11 @@ +# NodeGroupTaintDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Key** | **string** | | [default to null] +**Value** | **string** | | [default to null] +**Effect** | **string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/NodeGroupUpgradeConfigDto.md b/client/vks/docs/NodeGroupUpgradeConfigDto.md new file mode 100644 index 0000000..a719b21 --- /dev/null +++ b/client/vks/docs/NodeGroupUpgradeConfigDto.md @@ -0,0 +1,11 @@ +# NodeGroupUpgradeConfigDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Strategy** | **string** | | [default to null] +**MaxSurge** | **int32** | | [optional] [default to null] +**MaxUnavailable** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/PagingResultDtoClusterDto.md b/client/vks/docs/PagingResultDtoClusterDto.md new file mode 100644 index 0000000..ac85681 --- /dev/null +++ b/client/vks/docs/PagingResultDtoClusterDto.md @@ -0,0 +1,12 @@ +# PagingResultDtoClusterDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Items** | [**[]ClusterDto**](ClusterDto.md) | | [optional] [default to null] +**Total** | **int64** | | [optional] [default to null] +**Page** | **int32** | | [optional] [default to null] +**PageSize** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/PagingResultDtoNodeDto.md b/client/vks/docs/PagingResultDtoNodeDto.md new file mode 100644 index 0000000..30c8ceb --- /dev/null +++ b/client/vks/docs/PagingResultDtoNodeDto.md @@ -0,0 +1,12 @@ +# PagingResultDtoNodeDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Items** | [**[]NodeDto**](NodeDto.md) | | [optional] [default to null] +**Total** | **int64** | | [optional] [default to null] +**Page** | **int32** | | [optional] [default to null] +**PageSize** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/PagingResultDtoNodeGroupDto.md b/client/vks/docs/PagingResultDtoNodeGroupDto.md new file mode 100644 index 0000000..59dc749 --- /dev/null +++ b/client/vks/docs/PagingResultDtoNodeGroupDto.md @@ -0,0 +1,12 @@ +# PagingResultDtoNodeGroupDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Items** | [**[]NodeGroupDto**](NodeGroupDto.md) | | [optional] [default to null] +**Total** | **int64** | | [optional] [default to null] +**Page** | **int32** | | [optional] [default to null] +**PageSize** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/UpdateClusterDto.md b/client/vks/docs/UpdateClusterDto.md new file mode 100644 index 0000000..b497c4e --- /dev/null +++ b/client/vks/docs/UpdateClusterDto.md @@ -0,0 +1,10 @@ +# UpdateClusterDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Version** | **string** | | [default to null] +**WhitelistNodeCIDRs** | **[]string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/UpdateNodeGroupDto.md b/client/vks/docs/UpdateNodeGroupDto.md new file mode 100644 index 0000000..2f84f33 --- /dev/null +++ b/client/vks/docs/UpdateNodeGroupDto.md @@ -0,0 +1,13 @@ +# UpdateNodeGroupDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**AutoScaleConfig** | [***NodeGroupAutoScaleConfigDto**](NodeGroupAutoScaleConfigDto.md) | | [optional] [default to null] +**NumNodes** | **int64** | | [optional] [default to null] +**UpgradeConfig** | [***NodeGroupUpgradeConfigDto**](NodeGroupUpgradeConfigDto.md) | | [default to null] +**SecurityGroups** | **[]string** | | [default to null] +**ImageId** | **string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/docs/V1ClusterControllerApi.md b/client/vks/docs/V1ClusterControllerApi.md new file mode 100644 index 0000000..0636480 --- /dev/null +++ b/client/vks/docs/V1ClusterControllerApi.md @@ -0,0 +1,219 @@ +# {{classname}} + +All URIs are relative to */* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**V1ClustersClusterIdDelete**](V1ClusterControllerApi.md#V1ClustersClusterIdDelete) | **Delete** /v1/clusters/{clusterId} | +[**V1ClustersClusterIdGet**](V1ClusterControllerApi.md#V1ClustersClusterIdGet) | **Get** /v1/clusters/{clusterId} | +[**V1ClustersClusterIdKubeconfigGet**](V1ClusterControllerApi.md#V1ClustersClusterIdKubeconfigGet) | **Get** /v1/clusters/{clusterId}/kubeconfig | +[**V1ClustersClusterIdPut**](V1ClusterControllerApi.md#V1ClustersClusterIdPut) | **Put** /v1/clusters/{clusterId} | +[**V1ClustersGet**](V1ClusterControllerApi.md#V1ClustersGet) | **Get** /v1/clusters | +[**V1ClustersPost**](V1ClusterControllerApi.md#V1ClustersPost) | **Post** /v1/clusters | + +# **V1ClustersClusterIdDelete** +> ClusterDto V1ClustersClusterIdDelete(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1ClusterControllerApiV1ClustersClusterIdDeleteOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersClusterIdDeleteOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **portalUserId** | **optional.Int64**| | + +### Return type + +[**ClusterDto**](ClusterDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdGet** +> ClusterDetailDto V1ClustersClusterIdGet(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1ClusterControllerApiV1ClustersClusterIdGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersClusterIdGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **portalUserId** | **optional.Int64**| | + +### Return type + +[**ClusterDetailDto**](ClusterDetailDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdKubeconfigGet** +> string V1ClustersClusterIdKubeconfigGet(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1ClusterControllerApiV1ClustersClusterIdKubeconfigGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersClusterIdKubeconfigGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **portalUserId** | **optional.Int64**| | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdPut** +> ClusterDto V1ClustersClusterIdPut(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1ClusterControllerApiV1ClustersClusterIdPutOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersClusterIdPutOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **body** | [**optional.Interface of UpdateClusterDto**](UpdateClusterDto.md)| | + **portalUserId** | **optional.**| | + +### Return type + +[**ClusterDto**](ClusterDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersGet** +> PagingResultDtoClusterDto V1ClustersGet(ctx, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **optional** | ***V1ClusterControllerApiV1ClustersGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **filter** | **optional.String**| | [default to {}] + **page** | **optional.Int32**| | [default to 0] + **pageSize** | **optional.Int32**| | [default to 10] + **portalUserId** | **optional.Int64**| | + +### Return type + +[**PagingResultDtoClusterDto**](PagingResultDtoClusterDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersPost** +> ClusterDto V1ClustersPost(ctx, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **optional** | ***V1ClusterControllerApiV1ClustersPostOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1ClusterControllerApiV1ClustersPostOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**optional.Interface of CreateClusterComboDto**](CreateClusterComboDto.md)| | + **poc** | **optional.**| | [default to false] + **portalUserId** | **optional.**| | + +### Return type + +[**ClusterDto**](ClusterDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/client/vks/docs/V1NodeGroupControllerApi.md b/client/vks/docs/V1NodeGroupControllerApi.md new file mode 100644 index 0000000..e844903 --- /dev/null +++ b/client/vks/docs/V1NodeGroupControllerApi.md @@ -0,0 +1,231 @@ +# {{classname}} + +All URIs are relative to */* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**V1ClustersClusterIdNodeGroupsGet**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsGet) | **Get** /v1/clusters/{clusterId}/node-groups | +[**V1ClustersClusterIdNodeGroupsNodeGroupIdDelete**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsNodeGroupIdDelete) | **Delete** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +[**V1ClustersClusterIdNodeGroupsNodeGroupIdGet**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsNodeGroupIdGet) | **Get** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +[**V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet) | **Get** /v1/clusters/{clusterId}/node-groups/{nodeGroupId}/nodes | +[**V1ClustersClusterIdNodeGroupsNodeGroupIdPut**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsNodeGroupIdPut) | **Put** /v1/clusters/{clusterId}/node-groups/{nodeGroupId} | +[**V1ClustersClusterIdNodeGroupsPost**](V1NodeGroupControllerApi.md#V1ClustersClusterIdNodeGroupsPost) | **Post** /v1/clusters/{clusterId}/node-groups | + +# **V1ClustersClusterIdNodeGroupsGet** +> PagingResultDtoNodeGroupDto V1ClustersClusterIdNodeGroupsGet(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **page** | **optional.Int32**| | [default to 0] + **pageSize** | **optional.Int32**| | [default to 10] + **portalUserId** | **optional.Int64**| | + +### Return type + +[**PagingResultDtoNodeGroupDto**](PagingResultDtoNodeGroupDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdNodeGroupsNodeGroupIdDelete** +> NodeGroupDto V1ClustersClusterIdNodeGroupsNodeGroupIdDelete(ctx, clusterId, nodeGroupId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **nodeGroupId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdDeleteOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdDeleteOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + + **portalUserId** | **optional.Int64**| | + +### Return type + +[**NodeGroupDto**](NodeGroupDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdNodeGroupsNodeGroupIdGet** +> NodeGroupDetailDto V1ClustersClusterIdNodeGroupsNodeGroupIdGet(ctx, clusterId, nodeGroupId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **nodeGroupId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + + **portalUserId** | **optional.Int64**| | + +### Return type + +[**NodeGroupDetailDto**](NodeGroupDetailDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet** +> PagingResultDtoNodeDto V1ClustersClusterIdNodeGroupsNodeGroupIdNodesGet(ctx, clusterId, nodeGroupId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **nodeGroupId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdNodesGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdNodesGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + + **page** | **optional.Int32**| | [default to 0] + **pageSize** | **optional.Int32**| | [default to 10] + **portalUserId** | **optional.Int64**| | + +### Return type + +[**PagingResultDtoNodeDto**](PagingResultDtoNodeDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdNodeGroupsNodeGroupIdPut** +> NodeGroupDto V1ClustersClusterIdNodeGroupsNodeGroupIdPut(ctx, clusterId, nodeGroupId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **nodeGroupId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + + **body** | [**optional.Interface of UpdateNodeGroupDto**](UpdateNodeGroupDto.md)| | + **portalUserId** | **optional.**| | + +### Return type + +[**NodeGroupDto**](NodeGroupDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1ClustersClusterIdNodeGroupsPost** +> NodeGroupDto V1ClustersClusterIdNodeGroupsPost(ctx, clusterId, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **clusterId** | **string**| | + **optional** | ***V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + + **body** | [**optional.Interface of CreateNodeGroupDto**](CreateNodeGroupDto.md)| | + **portalUserId** | **optional.**| | + +### Return type + +[**NodeGroupDto**](NodeGroupDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/client/vks/docs/V1NodeGroupImageControllerApi.md b/client/vks/docs/V1NodeGroupImageControllerApi.md new file mode 100644 index 0000000..6994b1b --- /dev/null +++ b/client/vks/docs/V1NodeGroupImageControllerApi.md @@ -0,0 +1,30 @@ +# {{classname}} + +All URIs are relative to */* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**V1NodeGroupImagesGet**](V1NodeGroupImageControllerApi.md#V1NodeGroupImagesGet) | **Get** /v1/node-group-images | + +# **V1NodeGroupImagesGet** +> []NodeGroupImageDto V1NodeGroupImagesGet(ctx, ) + + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + +[**[]NodeGroupImageDto**](NodeGroupImageDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/client/vks/docs/V1WorkspaceControllerApi.md b/client/vks/docs/V1WorkspaceControllerApi.md new file mode 100644 index 0000000..aa1fed4 --- /dev/null +++ b/client/vks/docs/V1WorkspaceControllerApi.md @@ -0,0 +1,106 @@ +# {{classname}} + +All URIs are relative to */* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**V1WorkspaceGet**](V1WorkspaceControllerApi.md#V1WorkspaceGet) | **Get** /v1/workspace | +[**V1WorkspacePost**](V1WorkspaceControllerApi.md#V1WorkspacePost) | **Post** /v1/workspace | +[**V1WorkspaceResetServiceAccountPost**](V1WorkspaceControllerApi.md#V1WorkspaceResetServiceAccountPost) | **Post** /v1/workspace/reset-service-account | + +# **V1WorkspaceGet** +> WorkspaceDto V1WorkspaceGet(ctx, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **optional** | ***V1WorkspaceControllerApiV1WorkspaceGetOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1WorkspaceControllerApiV1WorkspaceGetOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **portalUserId** | **optional.Int64**| | + +### Return type + +[**WorkspaceDto**](WorkspaceDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1WorkspacePost** +> WorkspaceDto V1WorkspacePost(ctx, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **optional** | ***V1WorkspaceControllerApiV1WorkspacePostOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1WorkspaceControllerApiV1WorkspacePostOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **portalUserId** | **optional.Int64**| | + +### Return type + +[**WorkspaceDto**](WorkspaceDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **V1WorkspaceResetServiceAccountPost** +> WorkspaceDto V1WorkspaceResetServiceAccountPost(ctx, optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **optional** | ***V1WorkspaceControllerApiV1WorkspaceResetServiceAccountPostOpts** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a pointer to a V1WorkspaceControllerApiV1WorkspaceResetServiceAccountPostOpts struct +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **portalUserId** | **optional.Int64**| | + +### Return type + +[**WorkspaceDto**](WorkspaceDto.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/client/vks/docs/WorkspaceDto.md b/client/vks/docs/WorkspaceDto.md new file mode 100644 index 0000000..9b06751 --- /dev/null +++ b/client/vks/docs/WorkspaceDto.md @@ -0,0 +1,11 @@ +# WorkspaceDto + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ProjectId** | **string** | | [optional] [default to null] +**ServiceAccountId** | **string** | | [optional] [default to null] +**Status** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/client/vks/model_cluster_detail_dto.go b/client/vks/model_cluster_detail_dto.go new file mode 100644 index 0000000..1904714 --- /dev/null +++ b/client/vks/model_cluster_detail_dto.go @@ -0,0 +1,28 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type ClusterDetailDto struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Status string `json:"status,omitempty"` + Version string `json:"version,omitempty"` + NumNodes int64 `json:"numNodes,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + UpdatedAt string `json:"updatedAt,omitempty"` + EnablePrivateCluster bool `json:"enablePrivateCluster,omitempty"` + NetworkType *NetworkType `json:"networkType,omitempty"` + VpcId string `json:"vpcId,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + Cidr string `json:"cidr,omitempty"` + EnabledLoadBalancerPlugin bool `json:"enabledLoadBalancerPlugin,omitempty"` + EnabledBlockStoreCsiPlugin bool `json:"enabledBlockStoreCsiPlugin,omitempty"` + WhitelistNodeCIDRs []string `json:"whitelistNodeCIDRs,omitempty"` +} diff --git a/client/vks/model_cluster_dto.go b/client/vks/model_cluster_dto.go new file mode 100644 index 0000000..bf21819 --- /dev/null +++ b/client/vks/model_cluster_dto.go @@ -0,0 +1,20 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type ClusterDto struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Status string `json:"status,omitempty"` + Version string `json:"version,omitempty"` + NumNodes int64 `json:"numNodes,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + UpdatedAt string `json:"updatedAt,omitempty"` +} diff --git a/client/vks/model_create_cluster_combo_dto.go b/client/vks/model_create_cluster_combo_dto.go new file mode 100644 index 0000000..98c0e92 --- /dev/null +++ b/client/vks/model_create_cluster_combo_dto.go @@ -0,0 +1,23 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type CreateClusterComboDto struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Version string `json:"version"` + EnablePrivateCluster bool `json:"enablePrivateCluster"` + NetworkType string `json:"networkType"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Cidr string `json:"cidr"` + EnabledLoadBalancerPlugin bool `json:"enabledLoadBalancerPlugin"` + EnabledBlockStoreCsiPlugin bool `json:"enabledBlockStoreCsiPlugin"` + NodeGroups []CreateNodeGroupDto `json:"nodeGroups"` +} diff --git a/client/vks/model_create_node_group_dto.go b/client/vks/model_create_node_group_dto.go new file mode 100644 index 0000000..5c636cf --- /dev/null +++ b/client/vks/model_create_node_group_dto.go @@ -0,0 +1,25 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type CreateNodeGroupDto struct { + Name string `json:"name"` + NumNodes int32 `json:"numNodes"` + AutoScaleConfig *NodeGroupAutoScaleConfigDto `json:"autoScaleConfig,omitempty"` + UpgradeConfig NodeGroupUpgradeConfigDto `json:"upgradeConfig,omitempty"` + ImageId string `json:"imageId"` + FlavorId string `json:"flavorId"` + DiskSize int32 `json:"diskSize"` + DiskType string `json:"diskType"` + EnablePrivateNodes bool `json:"enablePrivateNodes"` + SecurityGroups []string `json:"securityGroups"` + SshKeyId string `json:"sshKeyId"` + Labels map[string]string `json:"labels,omitempty"` + Taints []NodeGroupTaintDto `json:"taints,omitempty"` +} diff --git a/client/vks/model_network_type.go b/client/vks/model_network_type.go new file mode 100644 index 0000000..0693921 --- /dev/null +++ b/client/vks/model_network_type.go @@ -0,0 +1,17 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NetworkType string + +// List of NetworkType +const ( + CALICO_NetworkType NetworkType = "CALICO" + CILIUM_NetworkType NetworkType = "CILIUM" +) diff --git a/client/vks/model_node_dto.go b/client/vks/model_node_dto.go new file mode 100644 index 0000000..e5f9aa1 --- /dev/null +++ b/client/vks/model_node_dto.go @@ -0,0 +1,18 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeDto struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Status string `json:"status,omitempty"` + FloatingIp string `json:"floatingIp,omitempty"` + FixedIp string `json:"fixedIp,omitempty"` + Ready bool `json:"ready,omitempty"` +} diff --git a/client/vks/model_node_group_auto_scale_config_dto.go b/client/vks/model_node_group_auto_scale_config_dto.go new file mode 100644 index 0000000..cc82757 --- /dev/null +++ b/client/vks/model_node_group_auto_scale_config_dto.go @@ -0,0 +1,14 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupAutoScaleConfigDto struct { + MinSize int32 `json:"minSize"` + MaxSize int32 `json:"maxSize"` +} diff --git a/client/vks/model_node_group_detail_dto.go b/client/vks/model_node_group_detail_dto.go new file mode 100644 index 0000000..e5086a6 --- /dev/null +++ b/client/vks/model_node_group_detail_dto.go @@ -0,0 +1,30 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupDetailDto struct { + Id string `json:"id,omitempty"` + ClusterId string `json:"clusterId,omitempty"` + Name string `json:"name,omitempty"` + Status string `json:"status,omitempty"` + NumNodes int64 `json:"numNodes,omitempty"` + ImageId string `json:"imageId,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + UpdatedAt string `json:"updatedAt,omitempty"` + FlavorId string `json:"flavorId,omitempty"` + DiskSize int32 `json:"diskSize,omitempty"` + DiskType string `json:"diskType,omitempty"` + EnablePrivateNodes bool `json:"enablePrivateNodes,omitempty"` + SshKeyId string `json:"sshKeyId,omitempty"` + SecurityGroups []string `json:"securityGroups,omitempty"` + AutoScaleConfig *NodeGroupAutoScaleConfigDto `json:"autoScaleConfig,omitempty"` + UpgradeConfig *NodeGroupUpgradeConfigDto `json:"upgradeConfig,omitempty"` + Labels map[string]string `json:"labels,omitempty"` + Taints []NodeGroupTaintDto `json:"taints,omitempty"` +} diff --git a/client/vks/model_node_group_dto.go b/client/vks/model_node_group_dto.go new file mode 100644 index 0000000..5dbb6b7 --- /dev/null +++ b/client/vks/model_node_group_dto.go @@ -0,0 +1,20 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupDto struct { + Id string `json:"id,omitempty"` + ClusterId string `json:"clusterId,omitempty"` + Name string `json:"name,omitempty"` + Status string `json:"status,omitempty"` + NumNodes int64 `json:"numNodes,omitempty"` + ImageId string `json:"imageId,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + UpdatedAt string `json:"updatedAt,omitempty"` +} diff --git a/client/vks/model_node_group_image_dto.go b/client/vks/model_node_group_image_dto.go new file mode 100644 index 0000000..5ab1b27 --- /dev/null +++ b/client/vks/model_node_group_image_dto.go @@ -0,0 +1,16 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupImageDto struct { + Id string `json:"id,omitempty"` + Os string `json:"os,omitempty"` + KubernetesVersion string `json:"kubernetesVersion,omitempty"` + Enable bool `json:"enable,omitempty"` +} diff --git a/client/vks/model_node_group_taint_dto.go b/client/vks/model_node_group_taint_dto.go new file mode 100644 index 0000000..ff66f30 --- /dev/null +++ b/client/vks/model_node_group_taint_dto.go @@ -0,0 +1,15 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupTaintDto struct { + Key string `json:"key"` + Value string `json:"value"` + Effect string `json:"effect"` +} diff --git a/client/vks/model_node_group_upgrade_config_dto.go b/client/vks/model_node_group_upgrade_config_dto.go new file mode 100644 index 0000000..69e4203 --- /dev/null +++ b/client/vks/model_node_group_upgrade_config_dto.go @@ -0,0 +1,15 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type NodeGroupUpgradeConfigDto struct { + Strategy string `json:"strategy"` + MaxSurge int32 `json:"maxSurge"` + MaxUnavailable int32 `json:"maxUnavailable"` +} diff --git a/client/vks/model_paging_result_dto_cluster_dto.go b/client/vks/model_paging_result_dto_cluster_dto.go new file mode 100644 index 0000000..6b90e2b --- /dev/null +++ b/client/vks/model_paging_result_dto_cluster_dto.go @@ -0,0 +1,16 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type PagingResultDtoClusterDto struct { + Items []ClusterDto `json:"items,omitempty"` + Total int64 `json:"total,omitempty"` + Page int32 `json:"page,omitempty"` + PageSize int32 `json:"pageSize,omitempty"` +} diff --git a/client/vks/model_paging_result_dto_node_dto.go b/client/vks/model_paging_result_dto_node_dto.go new file mode 100644 index 0000000..11a84ba --- /dev/null +++ b/client/vks/model_paging_result_dto_node_dto.go @@ -0,0 +1,16 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type PagingResultDtoNodeDto struct { + Items []NodeDto `json:"items,omitempty"` + Total int64 `json:"total,omitempty"` + Page int32 `json:"page,omitempty"` + PageSize int32 `json:"pageSize,omitempty"` +} diff --git a/client/vks/model_paging_result_dto_node_group_dto.go b/client/vks/model_paging_result_dto_node_group_dto.go new file mode 100644 index 0000000..20c2b3c --- /dev/null +++ b/client/vks/model_paging_result_dto_node_group_dto.go @@ -0,0 +1,16 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type PagingResultDtoNodeGroupDto struct { + Items []NodeGroupDto `json:"items,omitempty"` + Total int64 `json:"total,omitempty"` + Page int32 `json:"page,omitempty"` + PageSize int32 `json:"pageSize,omitempty"` +} diff --git a/client/vks/model_update_cluster_dto.go b/client/vks/model_update_cluster_dto.go new file mode 100644 index 0000000..bcf8f8d --- /dev/null +++ b/client/vks/model_update_cluster_dto.go @@ -0,0 +1,14 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type UpdateClusterDto struct { + Version string `json:"version"` + WhitelistNodeCIDRs []string `json:"whitelistNodeCIDRs"` +} diff --git a/client/vks/model_update_node_group_dto.go b/client/vks/model_update_node_group_dto.go new file mode 100644 index 0000000..b49dbf2 --- /dev/null +++ b/client/vks/model_update_node_group_dto.go @@ -0,0 +1,17 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type UpdateNodeGroupDto struct { + AutoScaleConfig *NodeGroupAutoScaleConfigDto `json:"autoScaleConfig,omitempty"` + NumNodes *int32 `json:"numNodes"` + UpgradeConfig *NodeGroupUpgradeConfigDto `json:"upgradeConfig"` + SecurityGroups []string `json:"securityGroups"` + ImageId string `json:"imageId"` +} diff --git a/client/vks/model_workspace_dto.go b/client/vks/model_workspace_dto.go new file mode 100644 index 0000000..790dc76 --- /dev/null +++ b/client/vks/model_workspace_dto.go @@ -0,0 +1,15 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +type WorkspaceDto struct { + ProjectId string `json:"projectId,omitempty"` + ServiceAccountId string `json:"serviceAccountId,omitempty"` + Status string `json:"status,omitempty"` +} diff --git a/client/vks/response.go b/client/vks/response.go new file mode 100644 index 0000000..3cf4000 --- /dev/null +++ b/client/vks/response.go @@ -0,0 +1,42 @@ +/* + * vks-api API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0-SNAPSHOT + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package vks + +import ( + "net/http" +) + +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/docs/resources/vks_cluster.md b/docs/resources/vks_cluster.md new file mode 100644 index 0000000..484aecb --- /dev/null +++ b/docs/resources/vks_cluster.md @@ -0,0 +1,70 @@ +--- +subcategory: "Kubernetes Service" +description: |- + Creates a Cluster on VNGCloud Kubernetes Service (VKS). +--- + +# vngcloud_vks_cluster + +Manages a VNGCloud Kubernetes Engine (VKS) cluster. + +To get more information about VKS clusters, see: + +* How-to guides + * [VKS overview](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/vks-la-gi) + * [Getting Start with VKS](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/bat-dau-voi-vks) +* Terraform guidance + * [Using VKS with Terraform](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/su-dung-vks-voi-terraform) + +--- +## Example Usage - with a separately managed node group (recommended) + +```hcl +resource "vngcloud_vks_cluster" "primary" { + name = "my-vks-cluster" + cidr = "172.16.0.0/16" + vpc_id = "net-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + subnet_id = "sub-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" +} + +resource "vngcloud_vks_cluster_node_group" "primary" { + name= "my-vks-node-group" + ssh_key_id= "ssh-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + cluster_id= vngcloud_vks_cluster.primary.id +} +``` + +**Important Note**: We are recommend you to create and manage node groups as separate resources, like in this example. This allows you to add or remove node groups without needing to recreate the entire cluster. +If you define node groups directly within the vngcloud_vks_cluster resource, you cannot remove them without recreating the cluster itself. + +## Example Usage - with the default node group + +```hcl +resource "vngcloud_vks_cluster" "primary" { + name = "my-vks-cluster" + cidr = "172.16.0.0/16" + vpc_id = "net-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + subnet_id = "sub-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + node_group { + name= "my-vks-node-group" + ssh_key_id= "ssh-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + } +} +``` +--- +## Argument Reference + +* `name` - (Required) The name of the cluster. Only letters (a-z, 0-9, '-') are allowed. Your input data length must be between 5 and 20. +* `config` - (Computed) The configuration of the Cluster. You don't need input to this field anything when you create a Cluster. +* `description` - (Optional) Description of the cluster. Only letters (a-z, A-Z, 0-9, '@', '.' , '_' , '-' , ' '). Your input data length must be between 0 and 255. +* `version` - (Optional) The version you want to use for you Cluster. You can see all of the Kubernetes's version in [here](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/tham-khao-them/phien-ban-ho-tro-kubernetes). +* `white_list_node_cidr` - (Optional) The IP Address range can connect to the control plane. The feature only works on Private Node Group mode. +* `enable_private_cluster` (Optional) - Enables the private cluster feature, + creating a private endpoint on the cluster. The VKS public clusters refer to a type of Kubernetes cluster configuration where the Kubernetes API server endpoint is publicly accessible over the internet. In an VKS public cluster, the API server endpoint is not restricted to private access within a VPC (Virtual Private Cloud) and can be accessed over the public internet. The VKS private clusters are configured to have private access to the Kubernetes API server endpoint. This means that the API server endpoint is only accessible from within a specific Virtual Private Cloud (VPC) and is not exposed to the public internet. Private clusters provide enhanced security by restricting access to the Kubernetes API to resources within the VPC. At this time, the default value of this field is false and we only offer Public Cluster mode. +* `network_type` - (Optional) The type of network for the cluster. Defaults to "CALICO". +* `vpc_id` (Required) The VPC ID for the cluster. You need create a VPC on vServer and put the VPC's ID on this field. +* `subnet_id` (Required) The subnet ID for the cluster. You need create a Subnet on vServer and put the Subnet's ID on this field. +* `cidr` (Required) The CIDR block for the cluster. You can enter CIDR as private IP and can select from the following options (10.0.0.0 - 10.255.0.0 / 172.16.0.0 - 172.24.0.0 / 192.168.0.0). +* `enabled_load_balancer_plugin` (Optional) Automatically deploy and manage the BlockStore Persistent Disk CSI Driver via Kubernetes YAML. +* `enabled_block_store_csi_plugin` (Optional) Allow attaching load balancers (network and application) via the Kubernetes YAML. + diff --git a/docs/resources/vks_cluster_node_group.md b/docs/resources/vks_cluster_node_group.md new file mode 100644 index 0000000..7e9f0b7 --- /dev/null +++ b/docs/resources/vks_cluster_node_group.md @@ -0,0 +1,91 @@ +--- +subcategory: "Kubernetes Service" +description: |- + Manages a VKS NodeGroup resource. +--- + +# vngcloud_vks_cluster_node_group + +Manages a VNGCloud Kubernetes Engine (VKS) Node Group. + +To get more information about VKS Node Group, see: + +* How-to guides + * [VKS overview](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/vks-la-gi) + * [Getting Start with VKS](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/bat-dau-voi-vks) +* Terraform guidance + * [Using VKS with Terraform](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/su-dung-vks-voi-terraform) + +Manages a node group in a VNGCloud Kubernetes Service (VKS) cluster separately from +the cluster control plane. For more information see [Node Group](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/node-groups). + +--- + +# vngcloud_vks_cluster_node_group + +## Example Usage - using a separately managed node group (recommended) + +```hcl +resource "vngcloud_vks_cluster" "primary" { + name = "my-vks-cluster" + cidr = "172.16.0.0/16" + vpc_id = "net-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + subnet_id = "sub-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" +} + +resource "vngcloud_vks_cluster_node_group" "primary" { + name= "my-vks-node-group" + ssh_key_id= "ssh-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + cluster_id= vngcloud_vks_cluster.primary.id +} +``` + +## Example Usage - 2 node pools, 1 separately managed + the default node group + +```hcl +resource "vngcloud_vks_cluster" "primary" { + name = "my-vks-cluster" + cidr = "172.16.0.0/16" + vpc_id = "net-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + subnet_id = "sub-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + node_group { + name= "my-vks-default" + ssh_key_id= "ssh-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + } +} + +resource "vngcloud_vks_cluster_node_group" "primary" { + name= "my-vks-node-group" + ssh_key_id= "ssh-xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx" + cluster_id= vngcloud_vks_cluster.primary.id +} +``` + +## Argument Reference + +* `cluster_id` - (Required) The Cluster ID which you want to create one or more node group into. +* `name` - (Required) The name of the node group. Only letters (a-z, 0-9, '-') are allowed. Your input data length must be between 5 and 15. +* `num_nodes` - (Optional) The desired number of nodes that the group should launch with initially. The number of nodes are between 1 and 10 nodes. If `auto_scale_config` is set, `num_nodes` must be -1. If `auto_scale_config` is not set, `num_nodes` must not be -1 +* `auto_scale_config` - (Optional) Configuration required by cluster autoscaler to adjust the size of the node group to the current cluster usage. + * `min_size` - (Optional) Minimum number of nodes in the Node Group. Must be >=0 and <= 10 and <= max_size. + * `max_size` - (Optional) Maximum number of nodes in the Node Group. Must be >=0 and <= 10 and >= min_size. +* `upgrade_config` - (Optional) Specify node upgrade settings to change how VKS upgrades nodes. The maximum number of nodes upgraded simultaneously is limited to 20. + * `strategy` - (Optional) Strategy used for node group update. Strategy can only be SURGE. + * `max_surge` - (Optional) The number of additional nodes that can be added to the node pool during + an upgrade. Increasing `max_surge` raises the number of nodes that can be upgraded simultaneously. + Can be set to 0 or greater. By default, an extra temporary node is generated during each node upgrade. To minimize expenses (although with a higher risk of disruption), consider configuring Max Surge to 1 and Max Unavailable to 0. + * `max_unvailable` - (Optional) The number of nodes that can be simultaneously unavailable during + an upgrade. Increasing `max_unavailable` raises the number of nodes that can be upgraded in + parallel. Can be set to 0 or greater. To mitigate risk for workloads that are sensitive to disruptions, this approach involves creating a fresh node pool while retaining the old nodes temporarily. It offers flexible upgrade pacing through batch requests and straightforward rollbacks. However, it comes with a higher cost compared to surge upgrades. +* `image_id` - (Optional) The image that you want to use for your node group. You can get the Image's ID on VKS Portal or [here](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/tham-khao-them/danh-sach-system-image-dang-ho-tro) and input to this field. +* `flavor_id` - (Optional) The flavor that you want to use for your node on your node group. You can get the Flavor's ID in [here](https://docs.vngcloud.vn/vng-cloud-document/v/vn/vks/tham-khao-them/danh-sach-flavor-dang-ho-tro) and input to this field. +* `disk_size` - (Optional) The Size of Data Disk will be used when new nodes are created using this node group. Disk size must be greater than or equal 20 GB and the largest is 5000 GB. +* `disk_type` - (Optional) The Type of Data Disk will be used when new nodes are created using this node group. At that time, we only provide one type SSD Disk. +* `enable_private_nodes` - (Optional) You can choose the mode that you want your node group works. The VKS public node groups include worker nodes deployed in public subnets within a VPC. These worker nodes have public IP addresses and CAN communicate directly with the public internet. The private node groups configuration involves deploying worker nodes within subnets of a VPC, ensuring they cannot directly access the public internet. All outbound traffic from these nodes is routed exclusively through a NAT gateway service. +* `security_groups` - (Optional) The Security Group that you want to use to your Cluster. A Security Group acts as a virtual firewall, controlling the traffic that is allowed to enter and leave the resources associated with it. For example, after you associate a security group with any server, it controls the Inbound and Outbound traffic for that Server. You can get the Security Group ID on vServer Portal and input to this field. +* `ssh_key_id` - (Required) The SSH Key that you want to set of secure credentials that you use to prove your identity when connecting to our Server. You can import a key and get the SSH Key ID on vServer Portal and input to this field. +* `labels` - (Optional) Labels are key/value pairs that are attached to objects such as Pods. Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users, but do not directly imply semantics to the core system. +* `taint` - (Optional) A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect. + * `key`- (Required) The Key for taint. The string must be 63 characters or less and consist only of letters (a-z, A-Z), numbers (0-9), hyphens (-), underscores (_), and periods (.). It must also begin and end with a letter, number, or underscore. + * `value` - (Required) The Value for taint. The string must be 63 characters or less and consist only of letters (a-z, A-Z), numbers (0-9), hyphens (-), underscores (_), and periods (.). It must also begin and end with a letter, number, or underscore. + * `effect` - (Optional) The Effect for taint. Accepted values are `NoSchedule`, `PreferNoSchedule`, and `NoExecute`. \ No newline at end of file diff --git a/provider/provider.go b/provider/provider.go index 619f655..916842c 100644 --- a/provider/provider.go +++ b/provider/provider.go @@ -1,6 +1,7 @@ package provider import ( + "github.com/vngcloud/terraform-provider-vngcloud/resource/vks" "log" "github.com/vngcloud/terraform-provider-vngcloud/resource/vdb" @@ -60,6 +61,8 @@ func Provider() *schema.Provider { "vngcloud_vserver_network_interface": vserver.ResourceNetworkInterface(), "vngcloud_vserver_external_interface_attach": vserver.ResourceAttachExternalInterface(), "vngcloud_vserver_internal_interface_attach": vserver.ResourceAttachInternalInterface(), + "vngcloud_vks_cluster": vks.ResourceCluster(), + "vngcloud_vks_cluster_node_group": vks.ResourceClusterNodeGroup(), }, Schema: map[string]*schema.Schema{ "token_url": { @@ -92,6 +95,12 @@ func Provider() *schema.Provider { DefaultFunc: schema.EnvDefaultFunc("VLB_BASE_URL", ""), Description: "endpoint to connection with provider resource", }, + "vks_base_url": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("VKS_BASE_URL", ""), + Description: "endpoint to connection with provider resource", + }, }, ConfigureFunc: providerConfigure, } @@ -115,5 +124,11 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { } clientID := d.Get("client_id").(string) clientSecret := d.Get("client_secret").(string) - return client.NewClientV2(vserverBaseURL, vlbBaseURL, clientID, clientSecret, tokenURL) + + vksBaseURL := "https://vks.api.vngcloud.vn" + _, hasVksBaseUrl := d.GetOk("vks_base_url") + if hasVksBaseUrl { + vksBaseURL = d.Get("vks_base_url").(string) + } + return client.NewClientV2(vserverBaseURL, vlbBaseURL, vksBaseURL, clientID, clientSecret, tokenURL) } diff --git a/resource/vks/config.go b/resource/vks/config.go new file mode 100644 index 0000000..0558914 --- /dev/null +++ b/resource/vks/config.go @@ -0,0 +1,10 @@ +package vks + +var ( + CREATING = []string{"CREATING", "DEGRADED"} + ERROR = []string{"ERROR"} + DELETING = []string{"DELETING"} + ACTIVE = []string{"ACTIVE"} + UPDATING = []string{"UPDATING", "DEGRADED"} + DELETED = []string{"DELETED"} +) diff --git a/resource/vks/resource_cluster.go b/resource/vks/resource_cluster.go new file mode 100644 index 0000000..c37b2ea --- /dev/null +++ b/resource/vks/resource_cluster.go @@ -0,0 +1,599 @@ +package vks + +import ( + "context" + "encoding/json" + "fmt" + "github.com/antihax/optional" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/vngcloud/terraform-provider-vngcloud/client" + "github.com/vngcloud/terraform-provider-vngcloud/client/vks" + "log" + "net/http" + "time" +) + +func ResourceCluster() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 0, + //MigrateState: resourceClusterMigrateState, + //StateUpgraders: []schema.StateUpgrader{ + // { + // Type: resourceContainerClusterResourceV1().CoreConfigSchema().ImpliedType(), + // Upgrade: ResourceContainerClusterUpgradeV1, + // Version: 0, + // }, + //}, + + Create: resourceClusterCreate, + Read: resourceClusterRead, + Update: resourceClusterUpdate, + Delete: resourceClusterDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + cli := m.(*client.Client) + _, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdGet(context.TODO(), d.Id(), nil) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return nil, errResponse + } + resourceClusterRead(d, m) + return []*schema.ResourceData{d}, nil + }, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "config": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "version": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: func() (interface{}, error) { + return fetchByKey("k8s_version") + }, + }, + "white_list_node_cidr": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "enable_private_cluster": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + DefaultFunc: func() (interface{}, error) { + return false, nil + }, + }, + "network_type": { + Type: schema.TypeString, + Optional: true, + Default: "CALICO", + ForceNew: true, + }, + "vpc_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "subnet_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "cidr": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "enabled_load_balancer_plugin": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: true, + }, + "enabled_block_store_csi_plugin": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Default: true, + }, + "node_group": { + Type: schema.TypeList, + Optional: true, + Computed: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: MergeSchemas( + schemaNodeGroup, + map[string]*schema.Schema{ + "node_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }), + }, + }, + }, + } +} +func resourceClusterStateRefreshFunc(cli *client.Client, clusterID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdGet(context.TODO(), clusterID, nil) + if httpResponse.StatusCode != http.StatusOK { + return nil, "", fmt.Errorf("Error : %s", GetResponseBody(httpResponse)) + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + cluster := resp + return cluster, cluster.Status, nil + } +} +func resourceClusterCreate(d *schema.ResourceData, m interface{}) error { + createNodeGroupRequests := expandNodeGroupForCreating(d.Get("node_group").([]interface{})) + createClusterRequest := vks.CreateClusterComboDto{ + Name: d.Get("name").(string), + Description: d.Get("description").(string), + Version: d.Get("version").(string), + EnablePrivateCluster: d.Get("enable_private_cluster").(bool), + NetworkType: d.Get("network_type").(string), + VpcId: d.Get("vpc_id").(string), + SubnetId: d.Get("subnet_id").(string), + Cidr: d.Get("cidr").(string), + EnabledLoadBalancerPlugin: d.Get("enabled_load_balancer_plugin").(bool), + EnabledBlockStoreCsiPlugin: d.Get("enabled_block_store_csi_plugin").(bool), + NodeGroups: createNodeGroupRequests, + } + cli := m.(*client.Client) + request := vks.V1ClusterControllerApiV1ClustersPostOpts{ + Body: optional.NewInterface(createClusterRequest), + } + resp, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersPost(context.TODO(), &request) + + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return errResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + + stateConf := &resource.StateChangeConf{ + Pending: CREATING, + Target: ACTIVE, + Refresh: resourceClusterStateRefreshFunc(cli, resp.Id), + Timeout: 180 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err := stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for create cluster (%s) %s", resp.Id, err) + } + if len(createNodeGroupRequests) > 0 { + stateConf = &resource.StateChangeConf{ + Pending: CREATING, + Target: ACTIVE, + Refresh: resourceNodeGroupForClusterStateRefreshFunc(cli, resp.Id), + Timeout: 180 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + log.Printf("Node group size >0.................") + _, err := stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for create cluster (%s) %s", resp.Id, err) + } + updateNodeGroupData(cli, d, resp.Id) + } + d.SetId(resp.Id) + + return resourceClusterRead(d, m) +} + +func updateNodeGroupData(cli *client.Client, d *schema.ResourceData, clusterId string) error { + nodeGroups := d.Get("node_group").([]interface{}) + updatedNodeGroups := make([]interface{}, len(nodeGroups)) + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsGet(context.TODO(), clusterId, nil) + if httpResponse.StatusCode != http.StatusOK { + return fmt.Errorf("Error : %s", GetResponseBody(httpResponse)) + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + clusterNodeGroups := resp.Items + for i, ng := range nodeGroups { + nodeGroup := ng.(map[string]interface{}) + clusterNodeGroup := clusterNodeGroups[len(clusterNodeGroups)-i-1] + // Set the value for a specific field + upgradeConfig := nodeGroup["upgrade_config"].([]interface{}) + if len(upgradeConfig) == 0 { + clusterNodeGroupDetail, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterId, clusterNodeGroup.Id, nil) + if httpResponse.StatusCode != http.StatusOK { + return fmt.Errorf("Error : %s", GetResponseBody(httpResponse)) + } + upgradeConfig := []interface{}{ + map[string]interface{}{ + "strategy": clusterNodeGroupDetail.UpgradeConfig.Strategy, + "max_surge": clusterNodeGroupDetail.UpgradeConfig.MaxSurge, + "max_unavailable": clusterNodeGroupDetail.UpgradeConfig.MaxUnavailable, + }, + } + nodeGroup["upgrade_config"] = upgradeConfig + nodeGroup["node_group_id"] = clusterNodeGroupDetail.Id + } + if nodeGroup["num_nodes"] != nil && int32(nodeGroup["num_nodes"].(int)) != -1 { + log.Printf("num_nodes !=nil\n") + } else { + nodeGroup["num_nodes"] = clusterNodeGroup.NumNodes + } + updatedNodeGroups[i] = nodeGroup + } + + // Update the node_group field with the modified values + if err := d.Set("node_group", updatedNodeGroups); err != nil { + return fmt.Errorf("error setting node_group: %s", err) + } + + return nil +} + +func expandNodeGroupForCreating(node_group []interface{}) []vks.CreateNodeGroupDto { + if len(node_group) == 0 { + log.Printf("node_group 0\n") + return []vks.CreateNodeGroupDto{} + } else if node_group[0] == nil { + log.Printf("node_group nil\n") + return []vks.CreateNodeGroupDto{} + } + nodeGroupsJson, _ := json.Marshal(node_group) + log.Printf("aaaaa-------------------------------------\n") + log.Printf("%s\n", string(nodeGroupsJson)) + createNodeGroupRequests := make([]vks.CreateNodeGroupDto, len(node_group)) + for i, ng := range node_group { + nodeGroup, ok := ng.(map[string]interface{}) + if !ok { + log.Fatalf("Element at index %d is not a map", i) + } + createNodeGroupRequest := getCreateNodeGroupRequestForCluster(nodeGroup) + createNodeGroupRequests[i] = createNodeGroupRequest + } + return createNodeGroupRequests +} + +func resourceClusterRead(d *schema.ResourceData, m interface{}) error { + clusterID := d.Id() + cli := m.(*client.Client) + resp, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdGet(context.TODO(), clusterID, nil) + if httpResponse.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + return errorResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + cluster := resp + d.Set("version", cluster.Version) + whiteListNodeCIDRRequest := d.Get("white_list_node_cidr").([]interface{}) + var whiteListNodeCIDR []string + for _, s := range whiteListNodeCIDRRequest { + whiteListNodeCIDR = append(whiteListNodeCIDR, s.(string)) + } + var whiteListCIDRCluster []string + for _, whiteList := range cluster.WhitelistNodeCIDRs { + whiteListCIDRCluster = append(whiteListCIDRCluster, whiteList) + } + if !CheckListStringEqual(whiteListNodeCIDR, whiteListCIDRCluster) { + d.Set("white_list_node_cidr", whiteListCIDRCluster) + } + d.Set("cidr", cluster.Cidr) + d.Set("vpc_id", cluster.VpcId) + d.Set("subnet_id", cluster.SubnetId) + d.Set("network_type", cluster.NetworkType) + d.Set("name", cluster.Name) + d.Set("enabled_load_balancer_plugin", cluster.EnabledLoadBalancerPlugin) + d.Set("enabled_block_store_csi_plugin", cluster.EnabledBlockStoreCsiPlugin) + d.Set("enable_private_cluster", cluster.EnablePrivateCluster) + log.Printf("GetConfig\n") + configResp, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdKubeconfigGet(context.TODO(), clusterID, nil) + if !CheckErrorResponse(httpResponse) { + log.Printf("SetConfig\n") + d.Set("config", configResp) + } + return nil +} + +func resourceClusterUpdate(d *schema.ResourceData, m interface{}) error { + if d.HasChange("node_group") { + err := checkRequestNodeGroup(d) + if err != nil { + return err + } + } + if d.HasChange("white_list_node_cidr") || d.HasChange("version") { + err := changeWhiteListNodeOrVersion(d, m) + if err != nil { + return err + } + } + if d.HasChange("node_group") { + err := changeNodeGroup(d, m) + if err != nil { + return err + } + } + return resourceClusterRead(d, m) +} + +func checkRequestNodeGroup(d *schema.ResourceData) error { + nodeGroups := d.Get("node_group").([]interface{}) + for _, ng := range nodeGroups { + nodeGroup := ng.(map[string]interface{}) + autoScaleConfig := getAutoScaleConfig(nodeGroup["auto_scale_config"].([]interface{})) + var numNodes *int32 + if value, ok := nodeGroup["num_nodes"]; ok { + if value != nil { + num := int32(value.(int)) + if num != -1 { + numNodes = &num + } + } + } + var err error + if autoScaleConfig != nil && numNodes != nil { + err = fmt.Errorf("If auto_scale_config is set then num_nodes must be -1\n") + } + if autoScaleConfig == nil && numNodes == nil { + err = fmt.Errorf("If auto_scale_config is not set then num_nodes must be different from -1\n") + } + if err != nil { + oldNodeGroup, _ := d.GetChange("node_group") + d.Set("node_group", oldNodeGroup) + return err + } + } + return nil +} + +func changeWhiteListNodeOrVersion(d *schema.ResourceData, m interface{}) error { + whiteListCIDRsInterface := d.Get("white_list_node_cidr").([]interface{}) + var whiteListCIDR []string + for _, s := range whiteListCIDRsInterface { + whiteListCIDR = append(whiteListCIDR, s.(string)) + } + if len(whiteListCIDR) == 0 { + return fmt.Errorf(`The argument "white_list_node_cidr" must not be empty.`) + } + updateCluster := vks.UpdateClusterDto{ + Version: d.Get("version").(string), + WhitelistNodeCIDRs: whiteListCIDR, + } + cli := m.(*client.Client) + request := vks.V1ClusterControllerApiV1ClustersClusterIdPutOpts{ + Body: optional.NewInterface(updateCluster), + } + resp, httpResponse, err := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdPut(context.TODO(), d.Id(), &request) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + oldVersion, _ := d.GetChange("version") + oldWhiteListNodeCIDR, _ := d.GetChange("white_list_node_cidr") + d.Set("version", oldVersion) + d.Set("white_list_node_cidr", oldWhiteListNodeCIDR) + return errorResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + stateConf := &resource.StateChangeConf{ + Pending: UPDATING, + Target: ACTIVE, + Refresh: resourceClusterStateRefreshFunc(cli, d.Id()), + Timeout: d.Timeout(schema.TimeoutUpdate), + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for instance (%s) to be created: %s", d.Id(), err) + } + return resourceClusterRead(d, m) +} + +func changeNodeGroup(d *schema.ResourceData, m interface{}) error { + cli := m.(*client.Client) + nodeGroups := d.Get("node_group").([]interface{}) + for _, ng := range nodeGroups { + nodeGroup := ng.(map[string]interface{}) + + securityGroupsRequest := nodeGroup["security_groups"].([]interface{}) + var securityGroups []string + for _, s := range securityGroupsRequest { + securityGroups = append(securityGroups, s.(string)) + } + if securityGroups == nil { + securityGroups = make([]string, 0) + } + autoScaleConfig := getAutoScaleConfig(nodeGroup["auto_scale_config"].([]interface{})) + upgradeConfig := getUpgradeConfig(nodeGroup["upgrade_config"].([]interface{})) + var numNodes *int32 + if value, ok := nodeGroup["num_nodes"]; ok { + num := int32(value.(int)) + if num != -1 { + numNodes = &num + } + } + imageId := nodeGroup["image_id"].(string) + updateNodeGroupRequest := vks.UpdateNodeGroupDto{ + AutoScaleConfig: autoScaleConfig, + NumNodes: numNodes, + UpgradeConfig: &upgradeConfig, + SecurityGroups: securityGroups, + ImageId: imageId, + } + requestPutOpts := vks.V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts{ + Body: optional.NewInterface(updateNodeGroupRequest), + } + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdPut(context.TODO(), d.Id(), nodeGroup["node_group_id"].(string), &requestPutOpts) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return errResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + + stateConf := &resource.StateChangeConf{ + Pending: UPDATING, + Target: ACTIVE, + Refresh: resourceClusterNodeGroupStateRefreshFunc(cli, d.Id(), nodeGroup["node_group_id"].(string)), + Timeout: 180 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err := stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for update cluster node group (%s) %s", resp.Id, err) + } + } + return resourceClusterRead(d, m) +} + +func resourceClusterDelete(d *schema.ResourceData, m interface{}) error { + cli := m.(*client.Client) + resp, httpResponse, err := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdDelete(context.TODO(), d.Id(), nil) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + return errorResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + stateConf := &resource.StateChangeConf{ + Pending: DELETING, + Target: DELETED, + Refresh: resourceClusterDeleteStateRefreshFunc(cli, d.Id()), + Timeout: d.Timeout(schema.TimeoutCreate), + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for instance (%s) to be created: %s", d.Id(), err) + } + d.SetId("") + return nil +} + +func resourceClusterDeleteStateRefreshFunc(cli *client.Client, clusterId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, httpResponse, _ := cli.VksClient.V1ClusterControllerApi.V1ClustersClusterIdGet(context.TODO(), clusterId, nil) + if httpResponse.StatusCode != http.StatusOK { + if httpResponse.StatusCode == http.StatusNotFound { + return vks.ClusterDto{Status: "DELETED"}, "DELETED", nil + } else { + return nil, "", fmt.Errorf("Error describing instance: %s", GetResponseBody(httpResponse)) + } + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + return resp, resp.Status, nil + } +} + +func resourceClusterMigrateState( + v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { + if is.Empty() { + log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") + return is, nil + } + switch v { + case 1: + log.Println("[INFO] Found Cluster State v1 in legacy migration function; returning as non-op") + return is, nil + default: + return is, fmt.Errorf("Unexpected schema version: %d", v) + } +} + +func resourceNodeGroupForClusterStateRefreshFunc(cli *client.Client, clusterID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsGet(context.TODO(), clusterID, nil) + if httpResponse.StatusCode != http.StatusOK { + return nil, "", fmt.Errorf("Error : %s", GetResponseBody(httpResponse)) + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + clusterNodeGroups := resp.Items + var status string + for _, clusterNodeGroup := range clusterNodeGroups { + status = clusterNodeGroup.Status + if clusterNodeGroup.Status != "ACTIVE" { + break + } + } + return clusterNodeGroups, status, nil + } +} + +func getCreateNodeGroupRequestForCluster(nodeGroup map[string]interface{}) vks.CreateNodeGroupDto { + taintsInput, ok := nodeGroup["taint"].([]interface{}) + var tains []vks.NodeGroupTaintDto + if ok { + tains = getTaints(taintsInput) + } else { + tains = nil + } + return vks.CreateNodeGroupDto{ + Name: nodeGroup["name"].(string), + NumNodes: int32(nodeGroup["num_nodes"].(int)), + ImageId: nodeGroup["image_id"].(string), + FlavorId: nodeGroup["flavor_id"].(string), + DiskSize: int32(nodeGroup["disk_size"].(int)), + DiskType: nodeGroup["disk_type"].(string), + EnablePrivateNodes: nodeGroup["enable_private_nodes"].(bool), + SshKeyId: nodeGroup["ssh_key_id"].(string), + Labels: getLabels(nodeGroup["labels"].(map[string]interface{})), + Taints: tains, + SecurityGroups: getSecurityGroups(nodeGroup["security_groups"].([]interface{})), + UpgradeConfig: getUpgradeConfig(nodeGroup["upgrade_config"].([]interface{})), + AutoScaleConfig: getAutoScaleConfig(nodeGroup["auto_scale_config"].([]interface{})), + } +} diff --git a/resource/vks/resrouce_cluster_node_group.go b/resource/vks/resrouce_cluster_node_group.go new file mode 100644 index 0000000..efd41bd --- /dev/null +++ b/resource/vks/resrouce_cluster_node_group.go @@ -0,0 +1,630 @@ +package vks + +import ( + "context" + "encoding/json" + "fmt" + "github.com/antihax/optional" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/vngcloud/terraform-provider-vngcloud/client" + "github.com/vngcloud/terraform-provider-vngcloud/client/vks" + "log" + "net/http" + "strings" + "time" +) + +func ResourceClusterNodeGroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 0, + //MigrateState: resourceClusterNodeGroupMigrateState, + //StateUpgraders: []schema.StateUpgrader{ + // { + // Type: resourceContainerClusterResourceV1().CoreConfigSchema().ImpliedType(), + // Upgrade: ResourceContainerClusterUpgradeV1, + // Version: 1, + // }, + //}, + + Create: resourceClusterNodeGroupCreate, + Read: resourceClusterNodeGroupRead, + Update: resourceClusterNodeGroupUpdate, + Delete: resourceClusterNodeGroupDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + idParts := strings.Split(d.Id(), ":") + if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected ClusterID:NodeGroupId", d.Id()) + } + clusterID := idParts[0] + nodeGroupID := idParts[1] + cli := m.(*client.Client) + _, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterID, nodeGroupID, nil) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return nil, errResponse + } + d.SetId(nodeGroupID) + d.Set("cluster_id", clusterID) + resourceClusterNodeGroupRead(d, m) + return []*schema.ResourceData{d}, nil + }, + }, + Schema: MergeSchemas( + schemaNodeGroup, + map[string]*schema.Schema{ + "cluster_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + ), + } +} + +var schemaNodeGroup = map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "num_nodes": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + ValidateFunc: validation.IntAtLeast(-1), + }, + //"initial_node_count": { + // Type: schema.TypeInt, + // Optional: true, + // ForceNew: true, + // Default: 1, + //}, + "auto_scale_config": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "min_size": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + }, + "max_size": { + Type: schema.TypeInt, + Optional: true, + Default: 10, + }, + }, + }, + }, + "upgrade_config": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "strategy": { + Type: schema.TypeString, + Optional: true, + Default: "SURGE", + }, + "max_surge": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + }, + "max_unavailable": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + }, + }, + DefaultFunc: func() (interface{}, error) { + return []interface{}{ + map[string]interface{}{ + "strategy": "SURGE", + "max_surge": 1, + "max_unavailable": 0, + }, + }, nil + }, + }, + "image_id": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: func() (interface{}, error) { + return fetchByKey("image_id") + }, + }, + "flavor_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + DefaultFunc: func() (interface{}, error) { + return fetchByKey("flavor_id") + }, + }, + "disk_size": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + DefaultFunc: func() (interface{}, error) { + return 20, nil + }, + }, + "disk_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + DefaultFunc: func() (interface{}, error) { + return fetchByKey("volume_type_id") + }, + }, + "enable_private_nodes": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + DefaultFunc: func() (interface{}, error) { + return false, nil + }, + }, + "security_groups": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "ssh_key_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Description: `The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node.`, + }, + "taint": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `List of Kubernetes taints to be applied to each node.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + Description: `Key for taint.`, + }, + "value": { + Type: schema.TypeString, + Required: true, + Description: `Value for taint.`, + }, + "effect": { + Type: schema.TypeString, + Optional: true, + Default: "NoSchedule", + ValidateFunc: validation.StringInSlice([]string{"NoSchedule", "PreferNoSchedule", "NoExecute"}, false), + Description: `Effect for taint.`, + }, + }, + }, + }, +} + +func getSecurityGroups(input []interface{}) []string { + + securityGroups := make([]string, len(input)) + + for i, v := range input { + str, ok := v.(string) + if !ok { + return []string{} + } + securityGroups[i] = str + } + + return securityGroups +} + +func getUpgradeConfig(input []interface{}) vks.NodeGroupUpgradeConfigDto { + if len(input) == 0 { + return vks.NodeGroupUpgradeConfigDto{ + MaxUnavailable: 0, + MaxSurge: 1, + Strategy: "SURGE", + } + } + upgradeConfig, ok := input[0].(map[string]interface{}) + if !ok { + log.Fatalf("Element at index %d is not a map", 0) + } + + return vks.NodeGroupUpgradeConfigDto{ + Strategy: upgradeConfig["strategy"].(string), + MaxSurge: int32(upgradeConfig["max_surge"].(int)), + MaxUnavailable: int32(upgradeConfig["max_unavailable"].(int)), + } +} + +func getAutoScaleConfig(input []interface{}) *vks.NodeGroupAutoScaleConfigDto { + if len(input) == 0 { + return nil + } + autoScaleConfig := input[0].(map[string]interface{}) + + return &vks.NodeGroupAutoScaleConfigDto{ + MaxSize: int32(autoScaleConfig["max_size"].(int)), + MinSize: int32(autoScaleConfig["min_size"].(int)), + } +} + +func getLabels(input map[string]interface{}) map[string]string { + labels := make(map[string]string, len(input)) + + for k, v := range input { + str, ok := v.(string) + if !ok { + return nil + } + labels[k] = str + } + + return labels +} + +func getTaints(input []interface{}) []vks.NodeGroupTaintDto { + taints := make([]vks.NodeGroupTaintDto, len(input)) + + for i, rawTaint := range input { + taint := rawTaint.(map[string]interface{}) + taintDto := vks.NodeGroupTaintDto{ + Key: taint["key"].(string), + Value: taint["value"].(string), + Effect: taint["effect"].(string), + } + taints[i] = taintDto + } + + return taints +} + +func resourceClusterNodeGroupStateRefreshFunc(cli *client.Client, clusterID string, clusterNodeGroupID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterID, clusterNodeGroupID, nil) + if httpResponse.StatusCode != http.StatusOK { + return nil, "", fmt.Errorf("Error : %s", GetResponseBody(httpResponse)) + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + clusterNodeGroup := resp + return clusterNodeGroup, clusterNodeGroup.Status, nil + } +} + +func resourceClusterNodeGroupRead(d *schema.ResourceData, m interface{}) error { + clusterID := d.Get("cluster_id").(string) + cli := m.(*client.Client) + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterID, d.Id(), nil) + if httpResponse.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + return errorResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + upgradeConfig := []interface{}{ + map[string]interface{}{ + "strategy": resp.UpgradeConfig.Strategy, + "max_surge": resp.UpgradeConfig.MaxSurge, + "max_unavailable": resp.UpgradeConfig.MaxUnavailable, + }, + } + d.Set("upgrade_config", upgradeConfig) + if resp.AutoScaleConfig != nil { + autoScaleConfig := []interface{}{ + map[string]interface{}{ + "min_size": resp.AutoScaleConfig.MinSize, + "max_size": resp.AutoScaleConfig.MaxSize, + }, + } + d.Set("auto_scale_config", autoScaleConfig) + } else { + d.Set("auto_scale_config", nil) + } + d.Set("image_id", resp.ImageId) + if !checkSecurityGroupsSame(d, resp) { + d.Set("security_groups", resp.SecurityGroups) + } + d.Set("disk_size", resp.DiskSize) + d.Set("disk_type", resp.DiskType) + d.Set("enable_private_nodes", resp.EnablePrivateNodes) + d.Set("flavor_id", resp.FlavorId) + d.Set("name", resp.Name) + d.Set("ssh_key_id", resp.SshKeyId) + if _, ok := d.GetOkExists("num_nodes"); ok && int32(d.Get("num_nodes").(int)) != -1 { + d.Set("num_nodes", resp.NumNodes) + } + return nil +} + +//func resourceClusterNodeGroupReadForCreate(d *schema.ResourceData, m interface{}) error { +// clusterID := d.Get("cluster_id").(string) +// cli := m.(*client.Client) +// resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterID, d.Id(), nil) +// if httpResponse.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if CheckErrorResponse(httpResponse) { +// responseBody := GetResponseBody(httpResponse) +// errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) +// return errorResponse +// } +// respJSON, _ := json.Marshal(resp) +// log.Printf("-------------------------------------\n") +// log.Printf("%s\n", string(respJSON)) +// log.Printf("-------------------------------------\n") +// upgradeConfig := []interface{}{ +// map[string]interface{}{ +// "strategy": resp.UpgradeConfig.Strategy, +// "max_surge": resp.UpgradeConfig.MaxSurge, +// "max_unavailable": resp.UpgradeConfig.MaxUnavailable, +// }, +// } +// d.Set("upgrade_config", upgradeConfig) +// if resp.AutoScaleConfig != nil { +// autoScaleConfig := []interface{}{ +// map[string]interface{}{ +// "min_size": resp.AutoScaleConfig.MinSize, +// "max_size": resp.AutoScaleConfig.MaxSize, +// }, +// } +// d.Set("auto_scale_config", autoScaleConfig) +// } else { +// d.Set("auto_scale_config", nil) +// } +// d.Set("image_id", resp.ImageId) +// if !checkSecurityGroupsSame(d, resp) { +// d.Set("security_groups", resp.SecurityGroups) +// } +// d.Set("disk_size", resp.DiskSize) +// d.Set("disk_type", resp.DiskType) +// d.Set("enable_private_nodes", resp.EnablePrivateNodes) +// d.Set("flavor_id", resp.FlavorId) +// d.Set("name", resp.Name) +// d.Set("ssh_key_id", resp.SshKeyId) +// +// return nil +//} + +func resourceClusterNodeGroupCreate(d *schema.ResourceData, m interface{}) error { + + createNodeGroupRequest := getCreateNodeGroupRequest(d) + cli := m.(*client.Client) + request := vks.V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsPostOpts{ + Body: optional.NewInterface(createNodeGroupRequest), + } + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsPost(context.TODO(), d.Get("cluster_id").(string), &request) + + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return errResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + + stateConf := &resource.StateChangeConf{ + Pending: CREATING, + Target: ACTIVE, + Refresh: resourceClusterNodeGroupStateRefreshFunc(cli, d.Get("cluster_id").(string), resp.Id), + Timeout: 180 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err := stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for create cluster node group (%s) %s", resp.Id, err) + } + d.SetId(resp.Id) + return resourceClusterNodeGroupRead(d, m) +} + +func getCreateNodeGroupRequest(d *schema.ResourceData) vks.CreateNodeGroupDto { + taintsInput, ok := d.Get("taint").([]interface{}) + var tains []vks.NodeGroupTaintDto + if ok { + tains = getTaints(taintsInput) + } else { + tains = nil + } + return vks.CreateNodeGroupDto{ + Name: d.Get("name").(string), + NumNodes: int32(d.Get("num_nodes").(int)), + ImageId: d.Get("image_id").(string), + FlavorId: d.Get("flavor_id").(string), + DiskSize: int32(d.Get("disk_size").(int)), + DiskType: d.Get("disk_type").(string), + EnablePrivateNodes: d.Get("enable_private_nodes").(bool), + SshKeyId: d.Get("ssh_key_id").(string), + Labels: getLabels(d.Get("labels").(map[string]interface{})), + Taints: tains, + SecurityGroups: getSecurityGroups(d.Get("security_groups").([]interface{})), + UpgradeConfig: getUpgradeConfig(d.Get("upgrade_config").([]interface{})), + AutoScaleConfig: getAutoScaleConfig(d.Get("auto_scale_config").([]interface{})), + } +} + +func resourceClusterNodeGroupUpdate(d *schema.ResourceData, m interface{}) error { + hasChangeSecurityGroups := false + cli := m.(*client.Client) + clusterId := d.Get("cluster_id").(string) + clusterNodeGroupId := d.Id() + if d.HasChange("security_groups") { + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterId, clusterNodeGroupId, nil) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + return errorResponse + } + if checkSecurityGroupsSame(d, resp) { + return resourceClusterRead(d, m) + } else { + hasChangeSecurityGroups = true + } + } + if hasChangeSecurityGroups || d.HasChange("auto_scale_config") || d.HasChange("num_nodes") || d.HasChange("upgrade_config") || d.HasChange("image_id") { + securityGroupsRequest := d.Get("security_groups").([]interface{}) + var securityGroups []string + for _, s := range securityGroupsRequest { + securityGroups = append(securityGroups, s.(string)) + } + if securityGroups == nil { + securityGroups = make([]string, 0) + } + autoScaleConfig := getAutoScaleConfig(d.Get("auto_scale_config").([]interface{})) + upgradeConfig := getUpgradeConfig(d.Get("upgrade_config").([]interface{})) + var numNodes *int32 + if value, ok := d.GetOkExists("num_nodes"); ok { + num := int32(value.(int)) + if num != -1 { + numNodes = &num + } + } + var err error + if autoScaleConfig != nil && numNodes != nil { + err = fmt.Errorf("If auto_scale_config is set then num_nodes must be -1\n") + } + if autoScaleConfig == nil && numNodes == nil { + err = fmt.Errorf("If auto_scale_config is not set then num_nodes must be different from -1\n") + } + if err != nil { + if d.HasChange("auto_scale_config") { + oldAutoScaleConfig, _ := d.GetChange("auto_scale_config") + d.Set("auto_scale_config", oldAutoScaleConfig) + } + if d.HasChange("num_nodes") { + oldNumNodes, _ := d.GetChange("num_nodes") + d.Set("num_nodes", oldNumNodes) + } + return err + } + imageId := d.Get("image_id").(string) + updateNodeGroupRequest := vks.UpdateNodeGroupDto{ + AutoScaleConfig: autoScaleConfig, + NumNodes: numNodes, + UpgradeConfig: &upgradeConfig, + SecurityGroups: securityGroups, + ImageId: imageId, + } + requestPutOpts := vks.V1NodeGroupControllerApiV1ClustersClusterIdNodeGroupsNodeGroupIdPutOpts{ + Body: optional.NewInterface(updateNodeGroupRequest), + } + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdPut(context.TODO(), clusterId, clusterNodeGroupId, &requestPutOpts) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errResponse := fmt.Errorf("request fail with errMsg: %s", responseBody) + return errResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + + stateConf := &resource.StateChangeConf{ + Pending: UPDATING, + Target: ACTIVE, + Refresh: resourceClusterNodeGroupStateRefreshFunc(cli, clusterId, d.Id()), + Timeout: 180 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for update cluster node group (%s) %s", resp.Id, err) + } + } + return resourceClusterNodeGroupRead(d, m) +} + +func resourceClusterNodeGroupDelete(d *schema.ResourceData, m interface{}) error { + cli := m.(*client.Client) + resp, httpResponse, err := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdDelete(context.TODO(), d.Get("cluster_id").(string), d.Id(), nil) + if CheckErrorResponse(httpResponse) { + responseBody := GetResponseBody(httpResponse) + errorResponse := fmt.Errorf("request fail with errMsg : %s", responseBody) + return errorResponse + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + stateConf := &resource.StateChangeConf{ + Pending: DELETING, + Target: DELETED, + Refresh: resourceClusterNodeGroupDeleteStateRefreshFunc(cli, d.Get("cluster_id").(string), d.Id()), + Timeout: d.Timeout(schema.TimeoutCreate), + Delay: 10 * time.Second, + MinTimeout: 1 * time.Second, + } + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for instance (%s) to be created: %s", d.Id(), err) + } + d.SetId("") + return nil +} + +func resourceClusterNodeGroupDeleteStateRefreshFunc(cli *client.Client, clusterId string, clusterNodeGroupId string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, httpResponse, _ := cli.VksClient.V1NodeGroupControllerApi.V1ClustersClusterIdNodeGroupsNodeGroupIdGet(context.TODO(), clusterId, clusterNodeGroupId, nil) + if httpResponse.StatusCode != http.StatusOK { + if httpResponse.StatusCode == http.StatusNotFound { + return vks.ClusterDto{Status: "DELETED"}, "DELETED", nil + } else { + return nil, "", fmt.Errorf("Error describing instance: %s", GetResponseBody(httpResponse)) + } + } + respJSON, _ := json.Marshal(resp) + log.Printf("-------------------------------------\n") + log.Printf("%s\n", string(respJSON)) + log.Printf("-------------------------------------\n") + return resp, resp.Status, nil + } +} + +func checkSecurityGroupsSame(d *schema.ResourceData, clusterNodeGroup vks.NodeGroupDetailDto) bool { + securityGroupsRequest := d.Get("security_groups").([]interface{}) + var securityGroups []string + for _, s := range securityGroupsRequest { + securityGroups = append(securityGroups, s.(string)) + } + var securityGroupsCluster []string + for _, securityGroup := range clusterNodeGroup.SecurityGroups { + securityGroupsCluster = append(securityGroupsCluster, securityGroup) + } + return CheckListStringEqual(securityGroups, securityGroupsCluster) +} diff --git a/resource/vks/util.go b/resource/vks/util.go new file mode 100644 index 0000000..e876c13 --- /dev/null +++ b/resource/vks/util.go @@ -0,0 +1,93 @@ +package vks + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "io" + "io/ioutil" + "net/http" +) + +func CheckErrorResponse(httpResponse *http.Response) bool { + if httpResponse.StatusCode < 200 || httpResponse.StatusCode > 299 { + return true + } + return false +} + +func GetResponseBody(httpResponse *http.Response) string { + localVarBody, _ := io.ReadAll(httpResponse.Body) + responseMessage := string(localVarBody) + if httpResponse.StatusCode == 403 { + responseMessage = "You don't have permission to do this action" + } + return fmt.Sprint("Status Code: ", httpResponse.StatusCode, ", ", responseMessage) +} + +func CheckContainString(list []string, findElement string) bool { + for _, element := range list { + if element == findElement { + return true + } + } + return false +} + +func CheckListStringEqual(firstList []string, secondList []string) bool { + if len(firstList) == len(secondList) { + for _, element := range firstList { + if !CheckContainString(secondList, element) { + return false + } + } + return true + } + return false +} + +func MergeSchemas(a, b map[string]*schema.Schema) map[string]*schema.Schema { + merged := make(map[string]*schema.Schema) + + for k, v := range a { + merged[k] = v + } + + for k, v := range b { + merged[k] = v + } + + return merged +} + +func fetchByKey(key string) (interface{}, error) { + url := "https://terraform.api.vngcloud.vn/config.json" + + resp, err := http.Get(url) + if err != nil { + return nil, fmt.Errorf("failed to make HTTP request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("received non-200 response: %d", resp.StatusCode) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) + } + + var result map[string]interface{} + err = json.Unmarshal(body, &result) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal JSON: %v", err) + } + + response, ok := result[key].(string) + if !ok { + return nil, fmt.Errorf("%s not found in response", key) + } + + return response, nil +} diff --git a/terraform_run_with_debug.sh b/terraform_run_with_debug.sh deleted file mode 100755 index ce6fa72..0000000 --- a/terraform_run_with_debug.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -#cd terraform/examples -cd ./examples || exit - -# Set the log level to debug -export TF_LOG=debug - -#verbose logging -export TF_LOG_PROVIDERS=debug - -# Run the terraform command with the specified arguments -terraform "$@" - -#running ./terraform-debug.sh apply -auto-approve -#running ./terraform-debug.sh init && terraform apply --auto-approve