Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 92431c5c65 | |||
|
|
c7a2c4ed5a | ||
| 0c44daa241 | |||
|
|
650b1c158b | ||
| 8a101c6fcb | |||
|
|
3f21a89e80 | ||
| cbce7f434f | |||
| e04dc42d2b | |||
|
|
88eb9e8898 | ||
| 9ec34c6bfc | |||
| 80491ed643 | |||
| f1e0f7abb6 | |||
| 8eeef825c0 | |||
| 9a7a7b6f36 | |||
| 3393934456 | |||
| e7c968797b | |||
| bc264c4d90 | |||
| d137c7507a | |||
| 55027a1605 | |||
| de9cca4053 | |||
| 83bf1fb1fa | |||
| 16cad7a3e7 | |||
| 96273d2a12 | |||
| d4065938ac | |||
| cd741b7f11 | |||
| a85ad3acd5 | |||
| 823dfb49bc | |||
| e6440bc4a3 | |||
| 84c0248019 | |||
| 4120cd2b1a |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -3,3 +3,8 @@ cmd/
|
||||
.vscode/
|
||||
.fleet/
|
||||
.DS_Store
|
||||
tests/platform_upgrade/.env
|
||||
tests/platform_upgrade/input.json
|
||||
tests/platform_upgrade/*.txt
|
||||
tests/platform_upgrade/*.log
|
||||
*.env
|
||||
|
||||
14
CHANGELOG.md
14
CHANGELOG.md
@@ -1,10 +1,8 @@
|
||||
## Version 1.6.6
|
||||
## Version 1.11.4
|
||||
|
||||
## Bugfix
|
||||
- Fixed model RecordExtNet in cloudbroker/extnet/models for correct work of get request
|
||||
- Fixed json tags in ItemResourceConsumption model and delete extra model Consumed in cloudbroker/account/models
|
||||
- Fixed statelessSepId field type from uint64 to int64 in cloudbroker/compute/models for correct work of list request
|
||||
### Исправлено
|
||||
|
||||
## Feature
|
||||
- Added GetRaw and ListRaw methods that give response as an array of bytes for cloudAPI groups: account, compute, k8s, disks, rg, bservice, disks,extnet, flipgroup, image, k8ci, lb, locations(list), sizes(list), stack, tasks, vins
|
||||
- Added GetRaw and ListRaw methods that give response as an array of bytes for cloudbroker groups: account, apiaccess, compute, disks, extnet, flipgroup, grid, group, image, k8ci, k8s, lb, rg, sep, stack, tasks, user, vgpu, vins
|
||||
#### compute
|
||||
| Идентификатор<br>задачи | Описание |
|
||||
| --- | --- |
|
||||
| BGOS-486 | Изменен тип параметров `VGPUs` с []uint64 на []VGPUItem в структуре `RecordCompute` в cloudapi/compute и в cloudbroker/compute |
|
||||
2
LICENSE
2
LICENSE
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2022 Basis LTD
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
62
README_EN.md
62
README_EN.md
@@ -1,62 +0,0 @@
|
||||
# Decort SDK
|
||||
|
||||
Decort SDK is a library, written in GO (Golang) for interact with the **DECORT** API.
|
||||
The library contents structures and methods for requesting to an user (cloudapi) and admin (cloudbroker) groups of API.
|
||||
Also the library have structures for responses.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Install](#install)
|
||||
- [API List](#api-list)
|
||||
- [Examples](#examples)
|
||||
- [Examples2](#examples2)
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
||||
```
|
||||
|
||||
## API List
|
||||
|
||||
## Examples
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/kvmx86"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Config{
|
||||
AppID: "<APPID>",
|
||||
AppSecret: "<APPSECRET>",
|
||||
SSOURL: "https://sso.digitalenergy.online",
|
||||
DecortURL: "https://mr4.digitalenergy.online",
|
||||
Retries: 5,
|
||||
}
|
||||
client := decort.New(cfg)
|
||||
req := kvmx86.CreateRequest{
|
||||
RGID: 123,
|
||||
Name: "compute",
|
||||
CPU: 4,
|
||||
RAM: 4096,
|
||||
ImageID: 321,
|
||||
}
|
||||
|
||||
res, err := client.KVMX86().Create(context.Background(), req)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(res)
|
||||
}
|
||||
```
|
||||
|
||||
## Examples2
|
||||
619
client.go
619
client.go
@@ -4,25 +4,26 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
k8s_cb"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
|
||||
"github.com/google/go-querystring/query"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
)
|
||||
|
||||
// HTTP-client for platform
|
||||
// DecortClient is HTTP-client for platform
|
||||
type DecortClient struct {
|
||||
decortURL string
|
||||
client *http.Client
|
||||
@@ -53,7 +54,7 @@ func New(cfg config.Config) *DecortClient {
|
||||
},
|
||||
},
|
||||
},
|
||||
cfg: cfg,
|
||||
cfg: trimConfig(&cfg),
|
||||
expiryTime: expiryTime,
|
||||
mutex: &sync.Mutex{},
|
||||
}
|
||||
@@ -71,400 +72,306 @@ func (dc *DecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
||||
|
||||
// DecortApiCall method for sending requests to the platform
|
||||
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
|
||||
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
|
||||
|
||||
if okCa {
|
||||
reqBody := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(reqBody)
|
||||
if k8sCaCreateReq.OidcCertificate != "" {
|
||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
||||
_, _ = io.Copy(part, strings.NewReader(k8sCaCreateReq.OidcCertificate))
|
||||
}
|
||||
var body *bytes.Buffer
|
||||
var ctype string
|
||||
|
||||
_ = writer.WriteField("name", k8sCaCreateReq.Name)
|
||||
_ = writer.WriteField("rgId", strconv.FormatUint(k8sCaCreateReq.RGID, 10))
|
||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(k8sCaCreateReq.K8SCIID, 10))
|
||||
_ = writer.WriteField("workerGroupName", k8sCaCreateReq.WorkerGroupName)
|
||||
_ = writer.WriteField("networkPlugin", k8sCaCreateReq.NetworkPlugin)
|
||||
|
||||
if k8sCaCreateReq.MasterSEPID != 0 {
|
||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(k8sCaCreateReq.MasterSEPID, 10))
|
||||
}
|
||||
if k8sCaCreateReq.MasterSEPPool != "" {
|
||||
_ = writer.WriteField("masterSepPool", k8sCaCreateReq.MasterSEPPool)
|
||||
}
|
||||
if k8sCaCreateReq.WorkerSEPID != 0 {
|
||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(k8sCaCreateReq.WorkerSEPID, 10))
|
||||
}
|
||||
if k8sCaCreateReq.WorkerSEPPool != "" {
|
||||
_ = writer.WriteField("workerSepPool", k8sCaCreateReq.WorkerSEPPool)
|
||||
}
|
||||
|
||||
if k8sCaCreateReq.Labels != nil {
|
||||
for _, v := range k8sCaCreateReq.Labels {
|
||||
_ = writer.WriteField("labels", v)
|
||||
}
|
||||
}
|
||||
if k8sCaCreateReq.Taints != nil {
|
||||
for _, v := range k8sCaCreateReq.Taints {
|
||||
_ = writer.WriteField("taints", v)
|
||||
}
|
||||
}
|
||||
if k8sCaCreateReq.Annotations != nil {
|
||||
for _, v := range k8sCaCreateReq.Annotations {
|
||||
_ = writer.WriteField("annotations", v)
|
||||
}
|
||||
}
|
||||
|
||||
if k8sCaCreateReq.MasterCPU != 0 {
|
||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(k8sCaCreateReq.MasterCPU), 10))
|
||||
}
|
||||
if k8sCaCreateReq.MasterNum != 0 {
|
||||
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(k8sCaCreateReq.MasterNum), 10))
|
||||
}
|
||||
if k8sCaCreateReq.MasterRAM != 0 {
|
||||
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(k8sCaCreateReq.MasterRAM), 10))
|
||||
}
|
||||
if k8sCaCreateReq.MasterDisk != 0 {
|
||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(k8sCaCreateReq.MasterDisk), 10))
|
||||
}
|
||||
if k8sCaCreateReq.WorkerCPU != 0 {
|
||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(k8sCaCreateReq.WorkerCPU), 10))
|
||||
}
|
||||
if k8sCaCreateReq.WorkerNum != 0 {
|
||||
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(k8sCaCreateReq.WorkerNum), 10))
|
||||
}
|
||||
if k8sCaCreateReq.WorkerRAM != 0 {
|
||||
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(k8sCaCreateReq.WorkerRAM), 10))
|
||||
}
|
||||
if k8sCaCreateReq.WorkerDisk != 0 {
|
||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(k8sCaCreateReq.WorkerDisk), 10))
|
||||
}
|
||||
if k8sCaCreateReq.ExtNetID != 0 {
|
||||
_ = writer.WriteField("extnetId", strconv.FormatUint(k8sCaCreateReq.ExtNetID, 10))
|
||||
}
|
||||
if k8sCaCreateReq.VinsId != 0 {
|
||||
_ = writer.WriteField("vinsId", strconv.FormatUint(k8sCaCreateReq.VinsId, 10))
|
||||
}
|
||||
if !k8sCaCreateReq.WithLB {
|
||||
_ = writer.WriteField("withLB", strconv.FormatBool(k8sCaCreateReq.WithLB))
|
||||
}
|
||||
|
||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(k8sCaCreateReq.HighlyAvailable))
|
||||
|
||||
if k8sCaCreateReq.AdditionalSANs != nil {
|
||||
for _, v := range k8sCaCreateReq.AdditionalSANs {
|
||||
_ = writer.WriteField("additionalSANs", v)
|
||||
}
|
||||
}
|
||||
if k8sCaCreateReq.InitConfiguration != "" {
|
||||
_ = writer.WriteField("initConfiguration", k8sCaCreateReq.InitConfiguration)
|
||||
}
|
||||
if k8sCaCreateReq.ClusterConfiguration != "" {
|
||||
_ = writer.WriteField("clusterConfiguration", k8sCaCreateReq.ClusterConfiguration)
|
||||
}
|
||||
if k8sCaCreateReq.KubeletConfiguration != "" {
|
||||
_ = writer.WriteField("kubeletConfiguration", k8sCaCreateReq.KubeletConfiguration)
|
||||
}
|
||||
if k8sCaCreateReq.KubeProxyConfiguration != "" {
|
||||
_ = writer.WriteField("kubeProxyConfiguration", k8sCaCreateReq.KubeProxyConfiguration)
|
||||
}
|
||||
if k8sCaCreateReq.JoinConfiguration != "" {
|
||||
_ = writer.WriteField("joinConfiguration", k8sCaCreateReq.JoinConfiguration)
|
||||
}
|
||||
if k8sCaCreateReq.Description != "" {
|
||||
_ = writer.WriteField("desc", k8sCaCreateReq.Description)
|
||||
}
|
||||
if k8sCaCreateReq.UserData != "" {
|
||||
_ = writer.WriteField("userData", k8sCaCreateReq.UserData)
|
||||
}
|
||||
|
||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(k8sCaCreateReq.ExtNetOnly))
|
||||
_ = writer.FormDataContentType()
|
||||
|
||||
ct := writer.FormDataContentType()
|
||||
|
||||
writer.Close()
|
||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, reqBody)
|
||||
byteSlice, ok := params.([]byte)
|
||||
if ok {
|
||||
body = bytes.NewBuffer(byteSlice)
|
||||
// ctype = "application/x-iso9660-image"
|
||||
ctype = "application/octet-stream"
|
||||
} else {
|
||||
values, err := query.Values(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = dc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := dc.domp(req, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New(string(respBytes))
|
||||
}
|
||||
|
||||
return respBytes, nil
|
||||
} else if okCb {
|
||||
reqBody := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(reqBody)
|
||||
if k8sCbCreateReq.OidcCertificate != "" {
|
||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
||||
_, _ = io.Copy(part, strings.NewReader(k8sCbCreateReq.OidcCertificate))
|
||||
}
|
||||
|
||||
_ = writer.WriteField("name", k8sCbCreateReq.Name)
|
||||
_ = writer.WriteField("rgId", strconv.FormatUint(k8sCbCreateReq.RGID, 10))
|
||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(k8sCbCreateReq.K8CIID, 10))
|
||||
_ = writer.WriteField("workerGroupName", k8sCbCreateReq.WorkerGroupName)
|
||||
_ = writer.WriteField("networkPlugin", k8sCbCreateReq.NetworkPlugin)
|
||||
|
||||
if k8sCbCreateReq.MasterSEPID != 0 {
|
||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(k8sCbCreateReq.MasterSEPID, 10))
|
||||
}
|
||||
if k8sCbCreateReq.MasterSEPPool != "" {
|
||||
_ = writer.WriteField("masterSepPool", k8sCbCreateReq.MasterSEPPool)
|
||||
}
|
||||
if k8sCbCreateReq.WorkerSEPID != 0 {
|
||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(k8sCbCreateReq.WorkerSEPID, 10))
|
||||
}
|
||||
if k8sCbCreateReq.WorkerSEPPool != "" {
|
||||
_ = writer.WriteField("workerSepPool", k8sCbCreateReq.WorkerSEPPool)
|
||||
}
|
||||
|
||||
if k8sCbCreateReq.Labels != nil {
|
||||
for _, v := range k8sCbCreateReq.Labels {
|
||||
_ = writer.WriteField("labels", v)
|
||||
}
|
||||
}
|
||||
if k8sCbCreateReq.Taints != nil {
|
||||
for _, v := range k8sCbCreateReq.Taints {
|
||||
_ = writer.WriteField("taints", v)
|
||||
}
|
||||
}
|
||||
if k8sCbCreateReq.Annotations != nil {
|
||||
for _, v := range k8sCbCreateReq.Annotations {
|
||||
_ = writer.WriteField("annotations", v)
|
||||
}
|
||||
}
|
||||
|
||||
if k8sCbCreateReq.MasterCPU != 0 {
|
||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(k8sCbCreateReq.MasterCPU, 10))
|
||||
}
|
||||
if k8sCbCreateReq.MasterNum != 0 {
|
||||
_ = writer.WriteField("masterNum", strconv.FormatUint(k8sCbCreateReq.MasterNum, 10))
|
||||
}
|
||||
if k8sCbCreateReq.MasterRAM != 0 {
|
||||
_ = writer.WriteField("masterRam", strconv.FormatUint(k8sCbCreateReq.MasterRAM, 10))
|
||||
}
|
||||
if k8sCbCreateReq.MasterDisk != 0 {
|
||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(k8sCbCreateReq.MasterDisk, 10))
|
||||
}
|
||||
if k8sCbCreateReq.WorkerCPU != 0 {
|
||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(k8sCbCreateReq.WorkerCPU, 10))
|
||||
}
|
||||
if k8sCbCreateReq.WorkerNum != 0 {
|
||||
_ = writer.WriteField("workerNum", strconv.FormatUint(k8sCbCreateReq.WorkerNum, 10))
|
||||
}
|
||||
if k8sCbCreateReq.WorkerRAM != 0 {
|
||||
_ = writer.WriteField("workerRam", strconv.FormatUint(k8sCbCreateReq.WorkerRAM, 10))
|
||||
}
|
||||
if k8sCbCreateReq.WorkerDisk != 0 {
|
||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(k8sCbCreateReq.WorkerDisk, 10))
|
||||
}
|
||||
if k8sCbCreateReq.ExtNetID != 0 {
|
||||
_ = writer.WriteField("extnetId", strconv.FormatUint(k8sCbCreateReq.ExtNetID, 10))
|
||||
}
|
||||
if k8sCbCreateReq.VinsId != 0 {
|
||||
_ = writer.WriteField("vinsId", strconv.FormatUint(k8sCbCreateReq.VinsId, 10))
|
||||
}
|
||||
if !k8sCbCreateReq.WithLB {
|
||||
_ = writer.WriteField("withLB", strconv.FormatBool(k8sCbCreateReq.WithLB))
|
||||
}
|
||||
|
||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(k8sCbCreateReq.HighlyAvailable))
|
||||
|
||||
if k8sCbCreateReq.AdditionalSANs != nil {
|
||||
for _, v := range k8sCbCreateReq.AdditionalSANs {
|
||||
_ = writer.WriteField("additionalSANs", v)
|
||||
}
|
||||
}
|
||||
if k8sCbCreateReq.InitConfiguration != "" {
|
||||
_ = writer.WriteField("initConfiguration", k8sCbCreateReq.InitConfiguration)
|
||||
}
|
||||
if k8sCbCreateReq.ClusterConfiguration != "" {
|
||||
_ = writer.WriteField("clusterConfiguration", k8sCbCreateReq.ClusterConfiguration)
|
||||
}
|
||||
if k8sCbCreateReq.KubeletConfiguration != "" {
|
||||
_ = writer.WriteField("kubeletConfiguration", k8sCbCreateReq.KubeletConfiguration)
|
||||
}
|
||||
if k8sCbCreateReq.KubeProxyConfiguration != "" {
|
||||
_ = writer.WriteField("kubeProxyConfiguration", k8sCbCreateReq.KubeProxyConfiguration)
|
||||
}
|
||||
if k8sCbCreateReq.JoinConfiguration != "" {
|
||||
_ = writer.WriteField("joinConfiguration", k8sCbCreateReq.JoinConfiguration)
|
||||
}
|
||||
if k8sCbCreateReq.Description != "" {
|
||||
_ = writer.WriteField("desc", k8sCbCreateReq.Description)
|
||||
}
|
||||
if k8sCbCreateReq.UserData != "" {
|
||||
_ = writer.WriteField("userData", k8sCbCreateReq.UserData)
|
||||
}
|
||||
|
||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(k8sCbCreateReq.ExtNetOnly))
|
||||
_ = writer.FormDataContentType()
|
||||
|
||||
ct := writer.FormDataContentType()
|
||||
|
||||
writer.Close()
|
||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = dc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := dc.domp(req, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New(string(respBytes))
|
||||
}
|
||||
|
||||
return respBytes, nil
|
||||
body = bytes.NewBufferString(values.Encode())
|
||||
}
|
||||
|
||||
values, err := query.Values(params)
|
||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body := strings.NewReader(values.Encode())
|
||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, body)
|
||||
// get token
|
||||
if err = dc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// perform request
|
||||
respBytes, err := dc.do(req, ctype)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
// DecortApiCallMP method for sending requests to the platform
|
||||
func (dc *DecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
body, ctype, err := multiPartReq(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// get token
|
||||
if err = dc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := dc.do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
// perform request
|
||||
respBytes, err := dc.do(req, ctype)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New(string(respBytes))
|
||||
}
|
||||
|
||||
return respBytes, nil
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
func (dc *DecortClient) getToken(ctx context.Context) error {
|
||||
dc.mutex.Lock()
|
||||
defer dc.mutex.Unlock()
|
||||
|
||||
if dc.cfg.Token == "" || time.Now().After(dc.expiryTime) {
|
||||
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
dc.cfg.SSOURL = strings.TrimSuffix(dc.cfg.SSOURL, "/")
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", dc.cfg.SSOURL+"/v1/oauth/access_token", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := dc.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
|
||||
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
token := string(tokenBytes)
|
||||
|
||||
dc.cfg.Token = token
|
||||
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
// new token is not needed
|
||||
if dc.cfg.Token != "" && !time.Now().After(dc.expiryTime) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// set up request headers and body
|
||||
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
dc.cfg.SSOURL = strings.TrimSuffix(dc.cfg.SSOURL, "/")
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", dc.cfg.SSOURL+"/v1/oauth/access_token", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// request token
|
||||
resp, err := dc.client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
return fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var tokenBytes []byte
|
||||
tokenBytes, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
// save token in config
|
||||
token := string(tokenBytes)
|
||||
dc.cfg.Token = token
|
||||
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dc *DecortClient) do(req *http.Request) (*http.Response, error) {
|
||||
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||
// In any other cases do returns nil response and error.
|
||||
// Retries are implemented in case of connection reset errors.
|
||||
func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||
// set up request headers and body
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
if ctype != "" {
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
}
|
||||
|
||||
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
// var resp *http.Response
|
||||
// var err error
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
// req = req.Clone(req.Context())
|
||||
|
||||
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := dc.client.Do(req)
|
||||
|
||||
// if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, err
|
||||
buf, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
// }
|
||||
// }
|
||||
|
||||
req.Body.Close()
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
resp, err := dc.client.Do(req)
|
||||
if resp != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
// retries logic GOES HERE
|
||||
// get http response
|
||||
//var resp *http.Response
|
||||
//for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||
// req := req.Clone(req.Context())
|
||||
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
//
|
||||
// if i > 0 {
|
||||
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||
// }
|
||||
//
|
||||
// resp, err = dc.client.Do(req)
|
||||
//
|
||||
// // stop retries on success and close response body
|
||||
// if resp != nil {
|
||||
// defer resp.Body.Close()
|
||||
// }
|
||||
// if err == nil {
|
||||
// break
|
||||
// }
|
||||
//
|
||||
// // retries in case of connection errors with time sleep
|
||||
// if isConnectionError(err) {
|
||||
// continue
|
||||
// }
|
||||
//
|
||||
// // return error in case of non-connection error
|
||||
// return nil, err
|
||||
//}
|
||||
|
||||
// handle http request errors
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, fmt.Errorf("got empty response without error")
|
||||
}
|
||||
|
||||
// handle successful request
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == 200 {
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// handle errors with status code other than 200
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
|
||||
func (dc *DecortClient) domp(req *http.Request, ctype string) (*http.Response, error) {
|
||||
req.Header.Add("Content-Type", ctype)
|
||||
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
// isConnectionError checks if given error falls within specific and associated connection errors
|
||||
//func isConnectionError(err error) bool {
|
||||
// if strings.Contains(err.Error(), "connection reset by peer") {
|
||||
// return true
|
||||
// }
|
||||
// if errors.Is(err, io.EOF) {
|
||||
// return true
|
||||
// }
|
||||
//
|
||||
// return false
|
||||
//}
|
||||
|
||||
// var resp *http.Response
|
||||
// var err error
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
// req = req.Clone(req.Context())
|
||||
// multiPartReq writes the request structure to the request body, and also returns string of the content-type
|
||||
func multiPartReq(params interface{}) (*bytes.Buffer, string, error) {
|
||||
reqBody := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(reqBody)
|
||||
values := reflect.ValueOf(params)
|
||||
types := values.Type()
|
||||
defer writer.Close()
|
||||
for i := 0; i < values.NumField(); i++ {
|
||||
if !values.Field(i).IsValid() {
|
||||
continue
|
||||
}
|
||||
|
||||
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := dc.client.Do(req)
|
||||
if values.Field(i).IsZero() {
|
||||
continue
|
||||
}
|
||||
|
||||
// if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, err
|
||||
if file, ok := constants.FileName[types.Field(i).Name]; ok {
|
||||
part, err := writer.CreateFormFile(trimString(types.Field(i)), file)
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
_, err = io.Copy(part, strings.NewReader(valueToString(values.Field(i).Interface())))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if values.Field(i).Type().Kind() == reflect.Slice {
|
||||
switch slice := values.Field(i).Interface().(type) {
|
||||
case []string:
|
||||
if validators.IsInSlice(trimString(types.Field(i)), constants.K8sValues) {
|
||||
code, err := json.Marshal(slice)
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
err = writer.WriteField(trimString(types.Field(i)), string(code))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
} else {
|
||||
for _, val := range slice {
|
||||
err := writer.WriteField(trimString(types.Field(i)), val)
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
case []uint:
|
||||
for _, val := range slice {
|
||||
err := writer.WriteField(trimString(types.Field(i)), strconv.FormatUint(uint64(val), 10))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
}
|
||||
case []uint64:
|
||||
for _, val := range slice {
|
||||
err := writer.WriteField(trimString(types.Field(i)), strconv.FormatUint(val, 10))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
}
|
||||
case []map[string]interface{}:
|
||||
for _, val := range slice {
|
||||
encodeStr, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
err = writer.WriteField(trimString(types.Field(i)), string(encodeStr))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return &bytes.Buffer{}, "", fmt.Errorf("unsupported slice type:%T", slice)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
err := writer.WriteField(trimString(types.Field(i)), valueToString(values.Field(i).Interface()))
|
||||
if err != nil {
|
||||
return &bytes.Buffer{}, "", err
|
||||
}
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
// }
|
||||
// }
|
||||
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
ct := writer.FormDataContentType()
|
||||
return reqBody, ct, nil
|
||||
}
|
||||
|
||||
func valueToString(a any) string {
|
||||
switch str := a.(type) {
|
||||
case string:
|
||||
return str
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(str), 10)
|
||||
case uint64:
|
||||
return strconv.FormatUint(str, 10)
|
||||
case bool:
|
||||
return strconv.FormatBool(str)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func trimString(el reflect.StructField) string {
|
||||
return strings.TrimSuffix(el.Tag.Get("url"), ",omitempty")
|
||||
}
|
||||
|
||||
func trimConfig(cfg *config.Config) config.Config {
|
||||
cfg.SSOURL = strings.TrimSuffix(cfg.SSOURL, "/")
|
||||
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||
return *cfg
|
||||
}
|
||||
|
||||
395
client_bvs.go
Normal file
395
client_bvs.go
Normal file
@@ -0,0 +1,395 @@
|
||||
package decortsdk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-querystring/query"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
)
|
||||
|
||||
// BVSDecortClient is HTTP-client for platform
|
||||
type BVSDecortClient struct {
|
||||
client *http.Client
|
||||
cfg config.BVSConfig
|
||||
mutex *sync.Mutex
|
||||
decortURL string
|
||||
}
|
||||
|
||||
type tokenJSON struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn uint64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
// Сlient builder
|
||||
func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
||||
if cfg.Retries == 0 {
|
||||
cfg.Retries = 5
|
||||
}
|
||||
if cfg.TimeToRefresh == 0 {
|
||||
cfg.TimeToRefresh = 1
|
||||
}
|
||||
|
||||
return &BVSDecortClient{
|
||||
decortURL: cfg.DecortURL,
|
||||
client: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
//nolint:gosec
|
||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||
},
|
||||
},
|
||||
},
|
||||
cfg: trimBVSConfig(&cfg),
|
||||
mutex: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// CloudAPI builder
|
||||
func (bdc *BVSDecortClient) CloudAPI() *cloudapi.CloudAPI {
|
||||
return cloudapi.New(bdc)
|
||||
}
|
||||
|
||||
// CloudBroker builder
|
||||
func (bdc *BVSDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
||||
return cloudbroker.New(bdc)
|
||||
}
|
||||
|
||||
// DecortApiCall method for sending requests to the platform
|
||||
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
var body *bytes.Buffer
|
||||
var ctype string
|
||||
|
||||
byteSlice, ok := params.([]byte)
|
||||
if ok {
|
||||
body = bytes.NewBuffer(byteSlice)
|
||||
// ctype = "application/x-iso9660-image"
|
||||
ctype = "application/octet-stream"
|
||||
} else {
|
||||
values, err := query.Values(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body = bytes.NewBufferString(values.Encode())
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// get token
|
||||
if bdc.cfg.Token.AccessToken == "" {
|
||||
if _, err = bdc.GetToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// refresh token
|
||||
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||
if _, err = bdc.GetToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// perform request
|
||||
reqCopy := req.Clone(ctx)
|
||||
respBytes, err := bdc.do(req, ctype)
|
||||
if err == nil {
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// get token and retry in case of access denied
|
||||
if err.Error() == "access is denied" {
|
||||
_, err = bdc.GetToken(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
respBytes, err = bdc.do(reqCopy, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
func (bdc *BVSDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
body, ctype, err := multiPartReq(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// get token
|
||||
if bdc.cfg.Token.AccessToken == "" {
|
||||
if _, err = bdc.GetToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// refresh token
|
||||
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||
if _, err = bdc.GetToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// perform request
|
||||
reqCopy := req.Clone(ctx)
|
||||
respBytes, err := bdc.do(req, ctype)
|
||||
if err == nil {
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// get token and retry in case of access denied
|
||||
if err.Error() == "access is denied" {
|
||||
_, err = bdc.GetToken(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
respBytes, err = bdc.do(reqCopy, ctype)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
// GetToken allows you to get a token and returns the token structure. When specifying the PathCfg variable,
|
||||
// the token and configuration will be written to a file.
|
||||
// When specifying the PathToken variable, the token will be written to a file.
|
||||
func (bdc *BVSDecortClient) GetToken(ctx context.Context) (config.Token, error) {
|
||||
bdc.mutex.Lock()
|
||||
defer bdc.mutex.Unlock()
|
||||
|
||||
// set up request headers and body
|
||||
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Username, bdc.cfg.Password)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// request token
|
||||
resp, err := bdc.client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var tokenBytes []byte
|
||||
tokenBytes, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return config.Token{}, fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
// save token in config
|
||||
var tj tokenJSON
|
||||
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||
return config.Token{}, fmt.Errorf("cannot unmarshal token: %w", err)
|
||||
}
|
||||
|
||||
bdc.cfg.Token = config.Token{
|
||||
AccessToken: tj.AccessToken,
|
||||
TokenType: tj.TokenType,
|
||||
RefreshToken: tj.RefreshToken,
|
||||
Expiry: tj.expiry(),
|
||||
}
|
||||
|
||||
if bdc.cfg.PathCfg != "" {
|
||||
ser, _ := bdc.cfg.Serialize("", " ")
|
||||
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||
}
|
||||
|
||||
if bdc.cfg.PathToken != "" {
|
||||
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||
}
|
||||
|
||||
return bdc.cfg.Token, nil
|
||||
}
|
||||
|
||||
// RefreshToken allows you to refresh a token and returns the token structure. When specifying the PathCfg variable,
|
||||
// the token and configuration will be written to a file.
|
||||
// When specifying the PathToken variable, the token will be written to a file
|
||||
func (bdc *BVSDecortClient) RefreshToken(ctx context.Context) (config.Token, error) {
|
||||
bdc.mutex.Lock()
|
||||
defer bdc.mutex.Unlock()
|
||||
|
||||
// set up request headers and body
|
||||
body := fmt.Sprintf("grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Token.RefreshToken)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// refresh token
|
||||
resp, err := bdc.client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var tokenBytes []byte
|
||||
tokenBytes, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return config.Token{}, fmt.Errorf("cannot refresh token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
// save token in config
|
||||
var tj tokenJSON
|
||||
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||
return config.Token{}, fmt.Errorf("cannot unmarshal after refresh token: %w", err)
|
||||
}
|
||||
|
||||
bdc.cfg.Token = config.Token{
|
||||
AccessToken: tj.AccessToken,
|
||||
TokenType: tj.TokenType,
|
||||
RefreshToken: tj.RefreshToken,
|
||||
Expiry: tj.expiry(),
|
||||
}
|
||||
|
||||
if bdc.cfg.PathCfg != "" {
|
||||
ser, _ := bdc.cfg.Serialize("", " ")
|
||||
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||
}
|
||||
|
||||
if bdc.cfg.PathToken != "" {
|
||||
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||
}
|
||||
|
||||
return bdc.cfg.Token, nil
|
||||
}
|
||||
|
||||
func (e *tokenJSON) expiry() (t time.Time) {
|
||||
if v := e.ExpiresIn; v != 0 {
|
||||
return time.Now().Add(time.Duration(v) * time.Second)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||
// In any other cases do returns nil response and error.
|
||||
// Retries are implemented in case of connection reset errors.
|
||||
func (bdc *BVSDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||
// set up request headers and body
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
if ctype != "" {
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
}
|
||||
|
||||
req.Header.Add("Authorization", "bearer "+bdc.cfg.Token.AccessToken)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
buf, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Body.Close()
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
resp, err := bdc.client.Do(req)
|
||||
if resp != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
// retries logic GOES HERE
|
||||
// get http response
|
||||
//var resp *http.Response
|
||||
//for i := uint64(0); i < bdc.cfg.Retries; i++ {
|
||||
// req := req.Clone(req.Context())
|
||||
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
//
|
||||
// if i > 0 {
|
||||
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||
// }
|
||||
//
|
||||
// resp, err = bdc.client.Do(req)
|
||||
//
|
||||
// // stop retries on success and close response body
|
||||
// if resp != nil {
|
||||
// defer resp.Body.Close()
|
||||
// }
|
||||
// if err == nil {
|
||||
// break
|
||||
// }
|
||||
//
|
||||
// // retries in case of connection errors with time sleep
|
||||
// if isConnectionError(err) {
|
||||
// continue
|
||||
// }
|
||||
//
|
||||
// // return error in case of non-connection error
|
||||
// return nil, err
|
||||
//}
|
||||
|
||||
// handle http request errors
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, fmt.Errorf("got empty response without error")
|
||||
}
|
||||
|
||||
var respBytes []byte
|
||||
respBytes, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// handle access denied and successful request
|
||||
if resp.StatusCode == 401 {
|
||||
return respBytes, errors.New("access is denied")
|
||||
}
|
||||
if resp.StatusCode == 200 {
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// handle errors with other status codes
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
|
||||
func trimBVSConfig(cfg *config.BVSConfig) config.BVSConfig {
|
||||
cfg.SSOURL = strings.TrimSuffix(cfg.SSOURL, "/")
|
||||
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||
return *cfg
|
||||
}
|
||||
@@ -72,9 +72,7 @@ func ParseConfigJSON(path string) (Config, error) {
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return Config{}, validators.ValidationError(validationError)
|
||||
}
|
||||
return Config{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -96,9 +94,7 @@ func ParseConfigYAML(path string) (Config, error) {
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return Config{}, validators.ValidationError(validationError)
|
||||
}
|
||||
return Config{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
|
||||
216
config/config_bvs.go
Normal file
216
config/config_bvs.go
Normal file
@@ -0,0 +1,216 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
type BVSConfig struct {
|
||||
// ServiceAccount username
|
||||
// Required: true
|
||||
// Example : "osh_mikoev"
|
||||
Username string `json:"username" yaml:"username" validate:"required"`
|
||||
|
||||
// ServiceAccount password
|
||||
// Required: true
|
||||
// Example: "[1o>hYkjnJr)HI78q7t&#%8Lm"
|
||||
Password string `json:"password" yaml:"password" validate:"required"`
|
||||
|
||||
// Domain name
|
||||
// Required: true
|
||||
// Example: "dynamix"
|
||||
Domain string `json:"domain" yaml:"domain" validate:"required"`
|
||||
|
||||
// Application (client) identifier for authorization
|
||||
// in the cloud platform controller in oauth2 mode.
|
||||
// Required: true
|
||||
// Example: "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
|
||||
AppID string `json:"appId" yaml:"appId" validate:"required"`
|
||||
|
||||
// Application (client) secret code for authorization
|
||||
// in the cloud platform controller in oauth2 mode.
|
||||
// Example: "frvet09rvesfis0c9erv9fsov0vsdfi09ovds0f"
|
||||
AppSecret string `json:"appSecret" yaml:"appSecret" validate:"required"`
|
||||
|
||||
// Platform authentication service address
|
||||
// Required: true
|
||||
// Example: "https://sso.digitalenergy.online"
|
||||
SSOURL string `json:"ssoUrl" yaml:"ssoUrl" validate:"url"`
|
||||
|
||||
// The address of the platform on which the actions are planned
|
||||
// Required: true
|
||||
// Example: "https://mr4.digitalenergy.online"
|
||||
DecortURL string `json:"decortUrl" yaml:"decortUrl" validate:"url"`
|
||||
|
||||
// JWT platform token
|
||||
// Required: false
|
||||
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
||||
Token Token `json:"token" yaml:"token"`
|
||||
|
||||
// Amount platform request attempts
|
||||
// Default value: 5
|
||||
// Required: false
|
||||
Retries uint64 `json:"retries" yaml:"retries"`
|
||||
|
||||
// Skip verify
|
||||
// Required: false
|
||||
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||
|
||||
// HTTP client timeout, unlimited if left empty
|
||||
// Required: false
|
||||
Timeout Duration `json:"timeout" yaml:"timeout"`
|
||||
|
||||
// The path of the configuration file entry
|
||||
// Required: false
|
||||
PathCfg string `json:"path_cfg" yaml:"path_cfg"`
|
||||
|
||||
// The path of the token file entry
|
||||
// Required: false
|
||||
PathToken string `json:"path_token" yaml:"path_token"`
|
||||
|
||||
// The number of minutes before the expiration of the token, a refresh will be made
|
||||
// Required: false
|
||||
TimeToRefresh int64 `json:"timeToRefresh" yaml:"timeToRefresh"`
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
// AccessToken is the token that authorizes and authenticates
|
||||
// the requests.
|
||||
// Required: false
|
||||
AccessToken string `json:"access_token" yaml:"access_token"`
|
||||
|
||||
// TokenType is the type of token.
|
||||
// The Type method returns either this or "Bearer", the default.
|
||||
// Required: false
|
||||
TokenType string `json:"token_type" yaml:"token_type"`
|
||||
|
||||
// RefreshToken is a token that's used by the application
|
||||
// (as opposed to the user) to refresh the access token
|
||||
// if it expires.
|
||||
// Required: false
|
||||
RefreshToken string `json:"refresh_token" yaml:"refresh_token"`
|
||||
|
||||
// Expiry is the optional expiration time of the access token.
|
||||
// Required: false
|
||||
Expiry time.Time `json:"expiry" yaml:"expiry"`
|
||||
}
|
||||
|
||||
// SetTimeout is used to set HTTP client timeout.
|
||||
func (c *BVSConfig) SetTimeout(dur time.Duration) {
|
||||
c.Timeout = Duration(dur)
|
||||
}
|
||||
|
||||
// ParseConfigJSON parses Config from specified JSON-formatted file.
|
||||
func ParseConfigBVSJSON(path string) (BVSConfig, error) {
|
||||
file, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return BVSConfig{}, err
|
||||
}
|
||||
|
||||
var config BVSConfig
|
||||
|
||||
err = json.Unmarshal(file, &config)
|
||||
if err != nil {
|
||||
return BVSConfig{}, err
|
||||
}
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// ParseConfigJSON parses Token from specified JSON-formatted file.
|
||||
func ParseTokenBVSJSON(path string) (Token, error) {
|
||||
file, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Token{}, err
|
||||
}
|
||||
|
||||
var token Token
|
||||
|
||||
err = json.Unmarshal(file, &token)
|
||||
if err != nil {
|
||||
return Token{}, err
|
||||
}
|
||||
|
||||
err = validators.ValidateConfig(token)
|
||||
if err != nil {
|
||||
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// ParseTokenBVSYAML parses Token from specified YAML-formatted file.
|
||||
func ParseTokenBVSYAML(path string) (Token, error) {
|
||||
file, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Token{}, err
|
||||
}
|
||||
|
||||
var token Token
|
||||
|
||||
err = yaml.Unmarshal(file, &token)
|
||||
if err != nil {
|
||||
return Token{}, err
|
||||
}
|
||||
|
||||
err = validators.ValidateConfig(token)
|
||||
if err != nil {
|
||||
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// ParseConfigYAML parses Config from specified YAML-formatted file.
|
||||
func ParseConfigBVSYAML(path string) (BVSConfig, error) {
|
||||
file, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return BVSConfig{}, err
|
||||
}
|
||||
|
||||
var config BVSConfig
|
||||
|
||||
err = yaml.Unmarshal(file, &config)
|
||||
if err != nil {
|
||||
return BVSConfig{}, err
|
||||
}
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (t Token) Serialize(params ...string) (serialization.Serialized, error) {
|
||||
if len(params) > 1 {
|
||||
prefix := params[0]
|
||||
indent := params[1]
|
||||
|
||||
return json.MarshalIndent(t, prefix, indent)
|
||||
}
|
||||
|
||||
return json.Marshal(t)
|
||||
}
|
||||
|
||||
func (c BVSConfig) Serialize(params ...string) (serialization.Serialized, error) {
|
||||
if len(params) > 1 {
|
||||
prefix := params[0]
|
||||
indent := params[1]
|
||||
|
||||
return json.MarshalIndent(c, prefix, indent)
|
||||
}
|
||||
|
||||
return json.Marshal(c)
|
||||
}
|
||||
@@ -66,9 +66,7 @@ func ParseLegacyConfigJSON(path string) (LegacyConfig, error) {
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||
}
|
||||
return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -90,9 +88,7 @@ func ParseLegacyConfigYAML(path string) (LegacyConfig, error) {
|
||||
|
||||
err = validators.ValidateConfig(config)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||
}
|
||||
return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
|
||||
@@ -22,6 +22,8 @@ func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||
}
|
||||
*d = Duration(tmp)
|
||||
return nil
|
||||
case float64:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid duration %v", value)
|
||||
}
|
||||
@@ -40,6 +42,8 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
|
||||
}
|
||||
*d = Duration(tmp)
|
||||
return nil
|
||||
case float64:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid duration %v", value)
|
||||
}
|
||||
|
||||
8
config/universal-config.go
Normal file
8
config/universal-config.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package config
|
||||
|
||||
// UniversalConfig combines configurations for different types of clients
|
||||
type UniversalConfig struct {
|
||||
Decs3oConfig *Config `json:"decs3oConfig,omitempty" yaml:"decs3oConfig,omitempty"`
|
||||
BVSConfig *BVSConfig `json:"bvsConfig,omitempty" yaml:"bvsConfig,omitempty"`
|
||||
LegacyConfig *LegacyConfig `json:"legacyConfig,omitempty" yaml:"legacyConfig,omitempty"`
|
||||
}
|
||||
8
go.mod
8
go.mod
@@ -5,15 +5,17 @@ go 1.20
|
||||
require (
|
||||
github.com/go-playground/validator/v10 v10.11.2
|
||||
github.com/google/go-querystring v1.1.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
golang.org/x/crypto v0.5.0 // indirect
|
||||
golang.org/x/sys v0.4.0 // indirect
|
||||
golang.org/x/text v0.6.0 // indirect
|
||||
golang.org/x/crypto v0.15.0 // indirect
|
||||
golang.org/x/sys v0.14.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
)
|
||||
|
||||
17
go.sum
17
go.sum
@@ -8,10 +8,13 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU=
|
||||
github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s=
|
||||
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
@@ -23,12 +26,12 @@ github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUA
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
|
||||
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
|
||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
|
||||
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
|
||||
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
||||
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
|
||||
@@ -6,4 +6,7 @@ import "context"
|
||||
type Caller interface {
|
||||
// DecortApiCall method for sending requests to the platform
|
||||
DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
||||
|
||||
// DecortApiCallMP method for sending requests to the platform
|
||||
DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
||||
}
|
||||
|
||||
7
interfaces/request.go
Normal file
7
interfaces/request.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package interfaces
|
||||
|
||||
// Interface to valiate RAM values
|
||||
type RequestWithRAM interface {
|
||||
// GetRAM returns RAM values
|
||||
GetRAM() map[string]uint64
|
||||
}
|
||||
14
internal/constants/constants.go
Normal file
14
internal/constants/constants.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package constants
|
||||
|
||||
const (
|
||||
RESTMACHINE = "/restmachine"
|
||||
|
||||
// RAM_DIVISIBILITY sets divisibility of RAM value
|
||||
RAM_DIVISIBILITY uint64 = 128
|
||||
)
|
||||
|
||||
var FileName = map[string]string{
|
||||
"OidcCertificate": "ca.crt",
|
||||
}
|
||||
|
||||
var K8sValues = []string{"labels", "taints", "annotations, additionalSANs"}
|
||||
41
internal/multierror/join.go
Normal file
41
internal/multierror/join.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package multierror
|
||||
|
||||
func Join(errs ...error) error {
|
||||
n := 0
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
e := &joinError{
|
||||
errs: make([]error, 0, n),
|
||||
}
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
e.errs = append(e.errs, err)
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
type joinError struct {
|
||||
errs []error
|
||||
}
|
||||
|
||||
func (e *joinError) Error() string {
|
||||
var b []byte
|
||||
for i, err := range e.errs {
|
||||
if i > 0 {
|
||||
b = append(b, '\n')
|
||||
}
|
||||
b = append(b, err.Error()...)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (e *joinError) Unwrap() []error {
|
||||
return e.errs
|
||||
}
|
||||
@@ -1,31 +1,44 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/multierror"
|
||||
)
|
||||
|
||||
// computeDriverValidator is used to validate Driver field in kvmx86/kvmppc create.
|
||||
// computeDriverValidator is used to validate Driver field in kvmx86 create.
|
||||
func computeDriverValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeDriverValues)
|
||||
return IsInSlice(fieldValue, computeDriverValues)
|
||||
}
|
||||
|
||||
// protoValidator is used to validate Proto fields.
|
||||
func protoValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, protoValues)
|
||||
return IsInSlice(fieldValue, protoValues)
|
||||
}
|
||||
|
||||
// apiGroupValidator is used to validate APIGroup fields
|
||||
func apiGroupValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, apiGroupValues)
|
||||
}
|
||||
|
||||
// accessTypeValidator is used to validate AccessType fields.
|
||||
func accessTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, accessTypeValues)
|
||||
return IsInSlice(fieldValue, accessTypeValues)
|
||||
}
|
||||
|
||||
// resTypesValidator is used to validate ResTypes fields.
|
||||
@@ -36,7 +49,7 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
||||
}
|
||||
|
||||
for _, value := range fieldSlice {
|
||||
if !StringInSlice(value, resTypesValues) {
|
||||
if !IsInSlice(value, resTypesValues) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -48,56 +61,63 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
||||
func driverValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, driverValues)
|
||||
return IsInSlice(fieldValue, driverValues)
|
||||
}
|
||||
|
||||
// accountCUTypeValidator is used to validate CUType field.
|
||||
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, accountCUTypeValues)
|
||||
return IsInSlice(fieldValue, accountCUTypeValues)
|
||||
}
|
||||
|
||||
// bserviceModeValidator is used to validate Mode field.
|
||||
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, bserviceModeValues)
|
||||
return IsInSlice(fieldValue, bserviceModeValues)
|
||||
}
|
||||
|
||||
// computeTopologyValidator is used to validate Topology field.
|
||||
func computeTopologyValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeTopologyValues)
|
||||
return IsInSlice(fieldValue, computeTopologyValues)
|
||||
}
|
||||
|
||||
// computePolicyValidator is used to validate Policy field.
|
||||
func computePolicyValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computePolicyValues)
|
||||
return IsInSlice(fieldValue, computePolicyValues)
|
||||
}
|
||||
|
||||
// computeModeValidator is used to validate Mode field.
|
||||
func computeModeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeModeValues)
|
||||
return IsInSlice(fieldValue, computeModeValues)
|
||||
}
|
||||
|
||||
// computeDiskTypeValidator is used to validate DiskType field.
|
||||
func computeDiskTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeDiskTypeValues)
|
||||
return IsInSlice(fieldValue, computeDiskTypeValues)
|
||||
}
|
||||
|
||||
// computeNetTypeValidator is used to validate NetType field.
|
||||
func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeNetTypeValues)
|
||||
return IsInSlice(fieldValue, computeNetTypeValues)
|
||||
}
|
||||
|
||||
// computex86NetTypeValidator is used to validate NetType field.
|
||||
func computex86NetTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, computex86NetTypeValues)
|
||||
}
|
||||
|
||||
// computeOrderValidator is used to validate Order field.
|
||||
@@ -108,7 +128,7 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
||||
}
|
||||
|
||||
for _, value := range fieldSlice {
|
||||
if !StringInSlice(value, computeOrderValues) {
|
||||
if !IsInSlice(value, computeOrderValues) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -120,70 +140,70 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
||||
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, computeDataDisksValues)
|
||||
return IsInSlice(fieldValue, computeDataDisksValues)
|
||||
}
|
||||
|
||||
// diskTypeValidator is used to validate Type field.
|
||||
func diskTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, diskTypeValues)
|
||||
return IsInSlice(fieldValue, diskTypeValues)
|
||||
}
|
||||
|
||||
// flipgroupClientTypeValidator is used to validate ClientType field.
|
||||
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, flipgroupClientTypeValues)
|
||||
return IsInSlice(fieldValue, flipgroupClientTypeValues)
|
||||
}
|
||||
|
||||
// kvmNetTypeValidator is used to validate NetType field.
|
||||
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, kvmNetTypeValues)
|
||||
return IsInSlice(fieldValue, kvmNetTypeValues)
|
||||
}
|
||||
|
||||
// lbAlgorithmValidator is used to validate Algorithm field.
|
||||
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, lbAlgorithmValues)
|
||||
return IsInSlice(fieldValue, lbAlgorithmValues)
|
||||
}
|
||||
|
||||
// rgDefNetValidator is used to validate DefNet field.
|
||||
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, rgDefNetValues)
|
||||
return IsInSlice(fieldValue, rgDefNetValues)
|
||||
}
|
||||
|
||||
// rgNetTypeValidator is used to validate NetType field.
|
||||
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, rgNetTypeValues)
|
||||
return IsInSlice(fieldValue, rgNetTypeValues)
|
||||
}
|
||||
|
||||
// vinsTypeValidator is used to validate Type field.
|
||||
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, vinsTypeValues)
|
||||
return IsInSlice(fieldValue, vinsTypeValues)
|
||||
}
|
||||
|
||||
// imageBootTypeValidator is used to validate BootType field.
|
||||
func imageBootTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, imageBootTypeValues)
|
||||
return IsInSlice(fieldValue, imageBootTypeValues)
|
||||
}
|
||||
|
||||
// imageTypeValidator is used to validate ImageType field.
|
||||
func imageTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, imageTypeValues)
|
||||
return IsInSlice(fieldValue, imageTypeValues)
|
||||
}
|
||||
|
||||
// imageDriversValidator is used to validate Drivers field.
|
||||
@@ -194,7 +214,7 @@ func imageDriversValidator(fe validator.FieldLevel) bool {
|
||||
}
|
||||
|
||||
for _, item := range fieldSlice {
|
||||
if !StringInSlice(item, imageDriversValues) {
|
||||
if !IsInSlice(item, imageDriversValues) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -206,14 +226,14 @@ func imageDriversValidator(fe validator.FieldLevel) bool {
|
||||
func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, imageArchitectureValues)
|
||||
return IsInSlice(fieldValue, imageArchitectureValues)
|
||||
}
|
||||
|
||||
// sepFieldTypeValidator is used to validate FieldType field.
|
||||
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return StringInSlice(fieldValue, sepFieldTypeValues)
|
||||
return IsInSlice(fieldValue, sepFieldTypeValues)
|
||||
}
|
||||
|
||||
// hwPathValidator is used to validate HWPath field.
|
||||
@@ -230,7 +250,7 @@ func networkPluginValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return StringInSlice(fieldValue, networkPluginValues)
|
||||
return IsInSlice(fieldValue, networkPluginValues)
|
||||
}
|
||||
|
||||
// networkPluginsValidator is used to validate NetworkPlugins field
|
||||
@@ -243,7 +263,7 @@ func networkPluginsValidator(fe validator.FieldLevel) bool {
|
||||
for _, item := range fieldSlice {
|
||||
item = strings.ToLower(item)
|
||||
|
||||
if !StringInSlice(item, networkPluginValues) {
|
||||
if !IsInSlice(item, networkPluginValues) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -255,14 +275,35 @@ func interfaceStateValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return StringInSlice(fieldValue, interfaceStateValues)
|
||||
return IsInSlice(fieldValue, interfaceStateValues)
|
||||
}
|
||||
|
||||
func interfaceTXModelValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return IsInSlice(fieldValue, txModelValues)
|
||||
}
|
||||
|
||||
func interfaceIOEventFDValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return IsInSlice(fieldValue, ioEventFDValues)
|
||||
}
|
||||
|
||||
func interfaceEventIDxValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return IsInSlice(fieldValue, eventIDxValues)
|
||||
}
|
||||
|
||||
func strictLooseValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
fieldValue = strings.ToLower(fieldValue)
|
||||
|
||||
return StringInSlice(fieldValue, strictLooseValues)
|
||||
return IsInSlice(fieldValue, strictLooseValues)
|
||||
}
|
||||
|
||||
// name workerGroup must be more 3 symbol
|
||||
@@ -272,3 +313,132 @@ func workerGroupNameValidator(fe validator.FieldLevel) bool {
|
||||
|
||||
return len(fieldValue) >= 3
|
||||
}
|
||||
|
||||
func sortByValidator(fe validator.FieldLevel) bool {
|
||||
|
||||
sortByRegexp := regexp.MustCompile(`^[+-][a-zA-Z_]+`)
|
||||
|
||||
return sortByRegexp.MatchString(fe.Field().String())
|
||||
}
|
||||
|
||||
func actionValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, actionValues)
|
||||
}
|
||||
|
||||
func vmActionValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, vmActionValues)
|
||||
}
|
||||
|
||||
func mtuValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().Uint()
|
||||
|
||||
return fieldValue >= uint64(mtuMin) && fieldValue <= uint64(mtuMax)
|
||||
}
|
||||
|
||||
func computeFeaturesValidator(fe validator.FieldLevel) bool {
|
||||
field := fe.Field()
|
||||
slice, ok := field.Interface().([]string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return IsSubSlice(slice, computeFeaturesValues)
|
||||
}
|
||||
|
||||
func networkInterfaceNamingValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, networkInterfaceNamingValues)
|
||||
}
|
||||
|
||||
func numaAffinityValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, numaAffinityValues)
|
||||
}
|
||||
|
||||
// kvmx86NetTypeValidator is used to validate NetType field for x86 compute.
|
||||
func kvmx86NetTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, kvmx86NetTypeValues)
|
||||
}
|
||||
|
||||
func isBoolTypeValidator(fe validator.FieldLevel) bool {
|
||||
return fe.Field().CanConvert(reflect.TypeOf(true))
|
||||
}
|
||||
|
||||
func urlValidartor(fl validator.FieldLevel) bool {
|
||||
fieldValues := fl.Field().String()
|
||||
|
||||
_, err := url.ParseRequestURI(fieldValues)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func chipsetValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, chipsetValues)
|
||||
}
|
||||
|
||||
func preferredCPUValidator(fe validator.FieldLevel) bool {
|
||||
fieldSlice, ok := fe.Field().Interface().([]int64)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, value := range fieldSlice {
|
||||
if value < -1 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// loaderTypeValidator is used to validate loaderType fields
|
||||
func loaderTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, loaderTypeValues)
|
||||
}
|
||||
|
||||
// languageValidator is used to validate language fields
|
||||
func languageValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, languageValues)
|
||||
}
|
||||
|
||||
// sepTypeValidator is used to validate sepType fields
|
||||
func sepTypeValidator(fe validator.FieldLevel) bool {
|
||||
fieldValue := fe.Field().String()
|
||||
|
||||
return IsInSlice(fieldValue, sepTypeValues)
|
||||
}
|
||||
|
||||
// ValidateRAM checks if request contains RAM value that is positive integer divisible by divisibility passed.
|
||||
// It is recommended to pass constants.RAM_DIVISIBILITY as divisility arguement
|
||||
func ValidateRAM(r interfaces.RequestWithRAM, divisibility uint64) error {
|
||||
|
||||
if divisibility == 0 {
|
||||
|
||||
return errors.New("second argument of ValidateRAM should be greater than 0")
|
||||
}
|
||||
mapRAM := r.GetRAM()
|
||||
|
||||
errs := make([]error, 0, len(mapRAM))
|
||||
|
||||
for k, v := range mapRAM {
|
||||
|
||||
if v%divisibility != 0 {
|
||||
|
||||
errs = append(errs, fmt.Errorf("expected value of %s: \"%d\" should be divisible by %d", k, v, divisibility))
|
||||
}
|
||||
}
|
||||
return multierror.Join(errs...)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package validators
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/multierror"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
@@ -20,12 +21,20 @@ func ValidationError(fe validator.FieldError) error {
|
||||
return errors.New(errorMessage(fe))
|
||||
}
|
||||
|
||||
func ValidationErrors(fes []validator.FieldError) error {
|
||||
errs := make([]error, 0, len(fes))
|
||||
for _, fe := range fes {
|
||||
errs = append(errs, ValidationError(fe))
|
||||
}
|
||||
return multierror.Join(errs...)
|
||||
}
|
||||
|
||||
//nolint:errorlint
|
||||
func GetErrors(err error) validator.ValidationErrors {
|
||||
return err.(validator.ValidationErrors)
|
||||
}
|
||||
|
||||
func StringInSlice(str string, target []string) bool {
|
||||
func IsInSlice(str string, target []string) bool {
|
||||
for _, v := range target {
|
||||
if v == str {
|
||||
return true
|
||||
@@ -33,3 +42,12 @@ func StringInSlice(str string, target []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsSubSlice(source []string, target []string) bool {
|
||||
for _, s := range source {
|
||||
if !IsInSlice(s, target) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ func errorMessage(fe validator.FieldError) string {
|
||||
return fmt.Sprintf("%s %s: unexpected URL format", prefix, fe.Field())
|
||||
case "email":
|
||||
return fmt.Sprintf("%s %s: unexpected E-Mail format", prefix, fe.Field())
|
||||
case "isBool":
|
||||
return fmt.Sprintf("%s %s: must be bool type", prefix, fe.Field())
|
||||
|
||||
case "driver":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
@@ -50,6 +52,13 @@ func errorMessage(fe validator.FieldError) string {
|
||||
fe.Field(),
|
||||
joinValues(protoValues))
|
||||
|
||||
// apiGroup Validators
|
||||
case "apiGroup":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(apiGroupValues))
|
||||
|
||||
// Account Validators
|
||||
case "accountCUType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
@@ -89,6 +98,18 @@ func errorMessage(fe validator.FieldError) string {
|
||||
fe.Field(),
|
||||
joinValues(computeDiskTypeValues))
|
||||
|
||||
case "mtu":
|
||||
return fmt.Sprint(prefix, fe.Field(), "must be ", mtuMin, "-", mtuMax)
|
||||
|
||||
case "preferredCPU":
|
||||
return fmt.Sprint(prefix, fe.Field(), "must be equal to or greater than", -1)
|
||||
|
||||
case "computex86NetType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(computex86NetTypeValues))
|
||||
|
||||
case "computeNetType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
@@ -133,7 +154,7 @@ func errorMessage(fe validator.FieldError) string {
|
||||
prefix,
|
||||
fe.Field())
|
||||
|
||||
// KVM_X86/KVM_PPC Validators
|
||||
// KVM_X86 Validators
|
||||
case "kvmNetType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
@@ -229,6 +250,89 @@ func errorMessage(fe validator.FieldError) string {
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(interfaceStateValues))
|
||||
|
||||
case "interfaceTXModel":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(txModelValues))
|
||||
|
||||
case "interfaceIOEventFD":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(ioEventFDValues))
|
||||
|
||||
case "interfaceEventIDx":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(eventIDxValues))
|
||||
|
||||
case "sortBy":
|
||||
return fmt.Sprintf("%s %s must be in format +|-(field)",
|
||||
prefix,
|
||||
fe.Field())
|
||||
|
||||
case "action":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(actionValues))
|
||||
|
||||
case "vmaction":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(vmActionValues))
|
||||
|
||||
case "computeFeatures":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(computeFeaturesValues))
|
||||
|
||||
case "networkInterfaceNaming":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(networkInterfaceNamingValues))
|
||||
|
||||
case "numaAffinity":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(numaAffinityValues))
|
||||
|
||||
case "kvmx86NetType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(kvmx86NetTypeValues))
|
||||
|
||||
case "chipset":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(chipsetValues))
|
||||
|
||||
case "loaderType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(loaderTypeValues))
|
||||
|
||||
case "language":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(languageValues))
|
||||
|
||||
case "sepType":
|
||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||
prefix,
|
||||
fe.Field(),
|
||||
joinValues(sepTypeValues))
|
||||
}
|
||||
|
||||
return fe.Error()
|
||||
|
||||
@@ -25,6 +25,7 @@ func getDecortValidator() *validator.Validate {
|
||||
|
||||
// registerAllValidators registers all custom validators in DecortValidator.
|
||||
func registerAllValidators(validate *validator.Validate) error {
|
||||
|
||||
err := validate.RegisterValidation("proto", protoValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -35,6 +36,11 @@ func registerAllValidators(validate *validator.Validate) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("apiGroup", apiGroupValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("accessType", accessTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -105,6 +111,11 @@ func registerAllValidators(validate *validator.Validate) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("computex86NetType", computex86NetTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("computeOrder", computeOrderValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -180,10 +191,100 @@ func registerAllValidators(validate *validator.Validate) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("interfaceTXModel", interfaceTXModelValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("interfaceIOEventFD", interfaceIOEventFDValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("interfaceEventIDx", interfaceEventIDxValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("workerGroupName", workerGroupNameValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("sortBy", sortByValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("action", actionValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("vmaction", vmActionValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("mtu", mtuValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("computeFeatures", computeFeaturesValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("networkInterfaceNaming", networkInterfaceNamingValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("numaAffinity", numaAffinityValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("kvmx86NetType", kvmx86NetTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("isBool", isBoolTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("url", urlValidartor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("chipset", chipsetValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("preferredCPU", preferredCPUValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("loaderType", loaderTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("language", languageValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = validate.RegisterValidation("sepType", sepTypeValidator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package validators
|
||||
|
||||
var (
|
||||
driverValues = []string{"KVM_X86", "KVM_PPC"}
|
||||
apiGroupValues = []string{"cloudapi", "cloudbroker", "system"}
|
||||
|
||||
driverValues = []string{"KVM_X86"}
|
||||
accessTypeValues = []string{"R", "RCX", "ARCXDU"}
|
||||
resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"}
|
||||
protoValues = []string{"tcp", "udp"}
|
||||
@@ -10,38 +12,70 @@ var (
|
||||
|
||||
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
|
||||
|
||||
computeTopologyValues = []string{"compute", "node"}
|
||||
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
||||
computeModeValues = []string{"EQ", "EN", "ANY"}
|
||||
computeDiskTypeValues = []string{"D", "B"}
|
||||
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
||||
computeOrderValues = []string{"cdrom", "network", "hd"}
|
||||
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
|
||||
computeDriverValues = []string{"KVM_X86", "SVA_KVM_X86"}
|
||||
computeTopologyValues = []string{"compute", "node"}
|
||||
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
||||
computeModeValues = []string{"EQ", "EN", "ANY"}
|
||||
computeDiskTypeValues = []string{"D", "B"}
|
||||
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
||||
computex86NetTypeValues = []string{"EXTNET", "VINS", "VFNIC", "DPDK"}
|
||||
computeOrderValues = []string{"cdrom", "network", "hd"}
|
||||
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
|
||||
computeDriverValues = []string{"KVM_X86", "SVA_KVM_X86"}
|
||||
|
||||
diskTypeValues = []string{"B", "T", "D"}
|
||||
|
||||
flipgroupClientTypeValues = []string{"compute", "vins"}
|
||||
|
||||
kvmNetTypeValues = []string{"EXTNET", "VINS", "NONE"}
|
||||
kvmNetTypeValues = []string{"EXTNET", "VINS", "NONE"}
|
||||
kvmx86NetTypeValues = []string{"EXTNET", "VINS", "NONE", "VFNIC", "DPDK"}
|
||||
|
||||
lbAlgorithmValues = []string{"roundrobin", "static-rr", "leastconn"}
|
||||
|
||||
rgDefNetValues = []string{"PRIVATE", "PUBLIC", "NONE"}
|
||||
rgNetTypeValues = []string{"PUBLIC", "PRIVATE"}
|
||||
|
||||
vinsTypeValues = []string{"DHCP", "VIP", "EXCLUDE"}
|
||||
vinsTypeValues = []string{"DHCP", "VIP", "EXCLUDED"}
|
||||
|
||||
imageBootTypeValues = []string{"uefi", "bios"}
|
||||
imageTypeValues = []string{"windows", "linux", "other"}
|
||||
imageTypeValues = []string{"windows", "linux", "unknown"}
|
||||
imageDriversValues = []string{"KVM_X86"}
|
||||
imageArchitectureValues = []string{"X86_64", "PPC64_LE"}
|
||||
imageArchitectureValues = []string{"X86_64"}
|
||||
|
||||
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
||||
|
||||
networkPluginValues = []string{"flannel", "weawenet", "calico"}
|
||||
networkPluginValues = []string{"flannel", "weavenet", "calico"}
|
||||
|
||||
strictLooseValues = []string{"strict", "loose"}
|
||||
|
||||
interfaceStateValues = []string{"on", "off"}
|
||||
|
||||
actionValues = []string{"power_on", "shutdown", "force_shutdown", "reboot"}
|
||||
|
||||
vmActionValues = []string{"stop", "move"}
|
||||
|
||||
computeFeaturesValues = []string{"hugepages", "numa", "cpupin", "vfnic", "dpdk", "changemac"}
|
||||
|
||||
networkInterfaceNamingValues = []string{"eth", "ens"}
|
||||
|
||||
numaAffinityValues = []string{"none", "strict", "loose"}
|
||||
|
||||
txModelValues = []string{"iothread", "timer", "selected by hypervisor"}
|
||||
|
||||
ioEventFDValues = []string{"on", "off", "selected by hypervisor"}
|
||||
|
||||
eventIDxValues = []string{"on", "off", "selected by hypervisor"}
|
||||
|
||||
chipsetValues = []string{"i440fx", "Q35"}
|
||||
|
||||
loaderTypeValues = []string{"linux", "windows", "unknown"}
|
||||
|
||||
sepTypeValues = []string{"hitachi", "dorado", "tatlin", "shared", "local", "des"}
|
||||
|
||||
languageValues = []string{"ru", "en"}
|
||||
)
|
||||
|
||||
const (
|
||||
mtuMin = 1
|
||||
|
||||
mtuMax = 9216
|
||||
)
|
||||
|
||||
379
legacy-client.go
379
legacy-client.go
@@ -4,25 +4,22 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-querystring/query"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
)
|
||||
|
||||
// Legacy HTTP-client for platform
|
||||
// LegacyDecortClient is Legacy HTTP-client for platform
|
||||
type LegacyDecortClient struct {
|
||||
decortURL string
|
||||
client *http.Client
|
||||
@@ -53,7 +50,7 @@ func NewLegacy(cfg config.LegacyConfig) *LegacyDecortClient {
|
||||
},
|
||||
},
|
||||
},
|
||||
cfg: cfg,
|
||||
cfg: trimLegacyConfig(&cfg),
|
||||
expiryTime: expiryTime,
|
||||
mutex: &sync.Mutex{},
|
||||
}
|
||||
@@ -71,263 +68,181 @@ func (ldc *LegacyDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
||||
|
||||
// DecortApiCall method for sending requests to the platform
|
||||
func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
if k8sCreateReq, ok := params.(k8s.CreateRequest); ok {
|
||||
reqBody := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(reqBody)
|
||||
if k8sCreateReq.OidcCertificate != "" {
|
||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
||||
_, _ = io.Copy(part, strings.NewReader(k8sCreateReq.OidcCertificate))
|
||||
}
|
||||
|
||||
_ = writer.WriteField("name", k8sCreateReq.Name)
|
||||
_ = writer.WriteField("rgId", strconv.FormatUint(k8sCreateReq.RGID, 10))
|
||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(k8sCreateReq.K8SCIID, 10))
|
||||
_ = writer.WriteField("workerGroupName", k8sCreateReq.WorkerGroupName)
|
||||
_ = writer.WriteField("networkPlugin", k8sCreateReq.NetworkPlugin)
|
||||
|
||||
if k8sCreateReq.MasterSEPID != 0 {
|
||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(k8sCreateReq.MasterSEPID, 10))
|
||||
}
|
||||
if k8sCreateReq.MasterSEPPool != "" {
|
||||
_ = writer.WriteField("masterSepPool", k8sCreateReq.MasterSEPPool)
|
||||
}
|
||||
if k8sCreateReq.WorkerSEPID != 0 {
|
||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(k8sCreateReq.WorkerSEPID, 10))
|
||||
}
|
||||
if k8sCreateReq.WorkerSEPPool != "" {
|
||||
_ = writer.WriteField("workerSepPool", k8sCreateReq.WorkerSEPPool)
|
||||
}
|
||||
|
||||
if k8sCreateReq.Labels != nil {
|
||||
for _, v := range k8sCreateReq.Labels {
|
||||
_ = writer.WriteField("labels", v)
|
||||
}
|
||||
}
|
||||
if k8sCreateReq.Taints != nil {
|
||||
for _, v := range k8sCreateReq.Taints {
|
||||
_ = writer.WriteField("taints", v)
|
||||
}
|
||||
}
|
||||
if k8sCreateReq.Annotations != nil {
|
||||
for _, v := range k8sCreateReq.Annotations {
|
||||
_ = writer.WriteField("annotations", v)
|
||||
}
|
||||
}
|
||||
|
||||
if k8sCreateReq.MasterCPU != 0 {
|
||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(k8sCreateReq.MasterCPU), 10))
|
||||
}
|
||||
if k8sCreateReq.MasterNum != 0 {
|
||||
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(k8sCreateReq.MasterNum), 10))
|
||||
}
|
||||
if k8sCreateReq.MasterRAM != 0 {
|
||||
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(k8sCreateReq.MasterRAM), 10))
|
||||
}
|
||||
if k8sCreateReq.MasterDisk != 0 {
|
||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(k8sCreateReq.MasterDisk), 10))
|
||||
}
|
||||
if k8sCreateReq.WorkerCPU != 0 {
|
||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(k8sCreateReq.WorkerCPU), 10))
|
||||
}
|
||||
if k8sCreateReq.WorkerNum != 0 {
|
||||
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(k8sCreateReq.WorkerNum), 10))
|
||||
}
|
||||
if k8sCreateReq.WorkerRAM != 0 {
|
||||
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(k8sCreateReq.WorkerRAM), 10))
|
||||
}
|
||||
if k8sCreateReq.WorkerDisk != 0 {
|
||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(k8sCreateReq.WorkerDisk), 10))
|
||||
}
|
||||
if k8sCreateReq.ExtNetID != 0 {
|
||||
_ = writer.WriteField("extnetId", strconv.FormatUint(k8sCreateReq.ExtNetID, 10))
|
||||
}
|
||||
if k8sCreateReq.VinsId != 0 {
|
||||
_ = writer.WriteField("vinsId", strconv.FormatUint(k8sCreateReq.VinsId, 10))
|
||||
}
|
||||
if !k8sCreateReq.WithLB {
|
||||
_ = writer.WriteField("withLB", strconv.FormatBool(k8sCreateReq.WithLB))
|
||||
}
|
||||
|
||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(k8sCreateReq.HighlyAvailable))
|
||||
|
||||
if k8sCreateReq.AdditionalSANs != nil {
|
||||
for _, v := range k8sCreateReq.AdditionalSANs {
|
||||
_ = writer.WriteField("additionalSANs", v)
|
||||
}
|
||||
}
|
||||
if k8sCreateReq.InitConfiguration != "" {
|
||||
_ = writer.WriteField("initConfiguration", k8sCreateReq.InitConfiguration)
|
||||
}
|
||||
if k8sCreateReq.ClusterConfiguration != "" {
|
||||
_ = writer.WriteField("clusterConfiguration", k8sCreateReq.ClusterConfiguration)
|
||||
}
|
||||
if k8sCreateReq.KubeletConfiguration != "" {
|
||||
_ = writer.WriteField("kubeletConfiguration", k8sCreateReq.KubeletConfiguration)
|
||||
}
|
||||
if k8sCreateReq.KubeProxyConfiguration != "" {
|
||||
_ = writer.WriteField("kubeProxyConfiguration", k8sCreateReq.KubeProxyConfiguration)
|
||||
}
|
||||
if k8sCreateReq.JoinConfiguration != "" {
|
||||
_ = writer.WriteField("joinConfiguration", k8sCreateReq.JoinConfiguration)
|
||||
}
|
||||
if k8sCreateReq.Description != "" {
|
||||
_ = writer.WriteField("desc", k8sCreateReq.Description)
|
||||
}
|
||||
if k8sCreateReq.UserData != "" {
|
||||
_ = writer.WriteField("userData", k8sCreateReq.UserData)
|
||||
}
|
||||
|
||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(k8sCreateReq.ExtNetOnly))
|
||||
_ = writer.FormDataContentType()
|
||||
|
||||
ct := writer.FormDataContentType()
|
||||
|
||||
if err := ldc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_ = writer.WriteField("authkey", ldc.cfg.Token)
|
||||
|
||||
writer.Close()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+"/restmachine"+url, reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := ldc.domp(req, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New(string(respBytes))
|
||||
}
|
||||
|
||||
return respBytes, nil
|
||||
// get token
|
||||
if err := ldc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
values, err := query.Values(params)
|
||||
var body *bytes.Buffer
|
||||
var ctype string
|
||||
|
||||
byteSlice, ok := params.([]byte)
|
||||
if ok {
|
||||
body = bytes.NewBuffer(byteSlice)
|
||||
ctype = "application/octet-stream"
|
||||
} else {
|
||||
values, err := query.Values(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body = bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// perform request
|
||||
respBytes, err := ldc.do(req, ctype)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
func (ldc *LegacyDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||
body, ctype, err := multiPartReq(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// get token
|
||||
if err = ldc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body := strings.NewReader(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+"/restmachine"+url, body)
|
||||
// perform request
|
||||
respBytes, err := ldc.do(req, ctype)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := ldc.do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New(string(respBytes))
|
||||
}
|
||||
|
||||
return respBytes, nil
|
||||
return respBytes, err
|
||||
}
|
||||
|
||||
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
||||
ldc.mutex.Lock()
|
||||
defer ldc.mutex.Unlock()
|
||||
|
||||
if ldc.cfg.Token == "" || time.Now().After(ldc.expiryTime) {
|
||||
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := ldc.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to get token: %w", err)
|
||||
}
|
||||
|
||||
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("unable to get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
token := string(tokenBytes)
|
||||
ldc.cfg.Token = token
|
||||
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
// new token is not needed
|
||||
if ldc.cfg.Token != "" && !time.Now().After(ldc.expiryTime) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// set up request headers and body
|
||||
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+constants.RESTMACHINE+"/cloudapi/user/authenticate", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// request token
|
||||
resp, err := ldc.client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
return fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var tokenBytes []byte
|
||||
tokenBytes, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
// save token in config
|
||||
token := string(tokenBytes)
|
||||
ldc.cfg.Token = token
|
||||
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ldc *LegacyDecortClient) do(req *http.Request) (*http.Response, error) {
|
||||
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||
// In any other cases do returns nil response and error.
|
||||
// Retries are implemented in case of connection reset errors.
|
||||
func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||
// set up request headers and body
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
if ctype != "" {
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
// var resp *http.Response
|
||||
// var err error
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
// req = req.Clone(req.Context())
|
||||
|
||||
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := ldc.client.Do(req)
|
||||
|
||||
// if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, err
|
||||
buf, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
// }
|
||||
// }
|
||||
|
||||
req.Body.Close()
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
resp, err := ldc.client.Do(req)
|
||||
if resp != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
// retries logic GOES HERE
|
||||
// get http response
|
||||
//var resp *http.Response
|
||||
//for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||
// req := req.Clone(req.Context())
|
||||
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
//
|
||||
// if i > 0 {
|
||||
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||
// }
|
||||
//
|
||||
// resp, err = ldc.client.Do(req)
|
||||
//
|
||||
// // stop retries on success and close response body
|
||||
// if resp != nil {
|
||||
// defer resp.Body.Close()
|
||||
// }
|
||||
// if err == nil {
|
||||
// break
|
||||
// }
|
||||
//
|
||||
// // retries in case of connection errors with time sleep
|
||||
// if isConnectionError(err) {
|
||||
// continue
|
||||
// }
|
||||
//
|
||||
// // return error in case of non-connection error
|
||||
// return nil, err
|
||||
//}
|
||||
|
||||
// handle http request errors
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, fmt.Errorf("got empty response without error")
|
||||
}
|
||||
|
||||
// handle successful request
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == 200 {
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// handle errors with status code other than 200
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
|
||||
func (ldc *LegacyDecortClient) domp(req *http.Request, ctype string) (*http.Response, error) {
|
||||
req.Header.Add("Content-Type", ctype)
|
||||
req.Header.Add("Authorization", "bearer "+ldc.cfg.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
// var resp *http.Response
|
||||
// var err error
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
// req = req.Clone(req.Context())
|
||||
|
||||
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := ldc.client.Do(req)
|
||||
|
||||
// if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, err
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
// }
|
||||
// }
|
||||
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
func trimLegacyConfig(cfg *config.LegacyConfig) config.LegacyConfig {
|
||||
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||
return *cfg
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for adding permission to access to account for a user
|
||||
// AddUserRequest struct to add permission to access account for a user
|
||||
type AddUserRequest struct {
|
||||
// ID of account to add to
|
||||
// Required: true
|
||||
@@ -30,9 +30,7 @@ type AddUserRequest struct {
|
||||
func (a Account) AddUser(ctx context.Context, req AddUserRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/addUser"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for give list account audits
|
||||
// AuditsRequest struct to give list of account audits
|
||||
type AuditsRequest struct {
|
||||
// ID of the account
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AuditsRequest struct {
|
||||
func (a Account) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/audits"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for creating account
|
||||
// CreateRequest struct for creating account
|
||||
type CreateRequest struct {
|
||||
// Display name
|
||||
// Required: true
|
||||
@@ -56,9 +56,7 @@ type CreateRequest struct {
|
||||
func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/create"
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for delete account
|
||||
// DeleteRequest struct to delete account
|
||||
type DeleteRequest struct {
|
||||
// ID of account to delete
|
||||
// Required: true
|
||||
@@ -22,9 +22,7 @@ type DeleteRequest struct {
|
||||
func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/delete"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for revoke access to account
|
||||
// DeleteUserRequest struct to revoke access to account
|
||||
type DeleteUserRequest struct {
|
||||
// ID of the account
|
||||
// Required: true
|
||||
@@ -17,19 +17,13 @@ type DeleteUserRequest struct {
|
||||
// ID or emailaddress of the user to remove
|
||||
// Required: true
|
||||
UserID string `url:"userId" json:"userId" validate:"required"`
|
||||
|
||||
// Recursively revoke access rights from owned cloudspaces and vmachines
|
||||
// Required: false
|
||||
RecursiveDelete bool `url:"recursivedelete,omitempty" json:"recursivedelete,omitempty"`
|
||||
}
|
||||
|
||||
// DeleteUser revokes user access from the account
|
||||
func (a Account) DeleteUser(ctx context.Context, req DeleteUserRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/deleteUser"
|
||||
|
||||
@@ -8,20 +8,22 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for change status of account
|
||||
// DisableEnableRequest struct to change status of account
|
||||
type DisableEnableRequest struct {
|
||||
// ID of account
|
||||
// Required: true
|
||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||
|
||||
// Reason of disabling
|
||||
// Required: false
|
||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// Disable disables an account
|
||||
func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/disable"
|
||||
@@ -43,9 +45,7 @@ func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, e
|
||||
func (a Account) Enable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/enable"
|
||||
|
||||
@@ -37,9 +37,7 @@ func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error
|
||||
func (a Account) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/get"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for calculate the currently consumed units for all cloudspaces and resource groups in the account
|
||||
// GetConsumedAccountUnitsRequest struct to calculate the currently consumed units for all cloudspaces and resource groups in the account
|
||||
type GetConsumedAccountUnitsRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -25,9 +25,7 @@ type GetConsumedAccountUnitsRequest struct {
|
||||
func (a Account) GetConsumedAccountUnits(ctx context.Context, req GetConsumedAccountUnitsRequest) (*ResourceLimits, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getConsumedAccountUnits"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for calculate the currently consumed cloud units of the specified type for all cloudspaces and resource groups in the account
|
||||
// GetConsumedCloudUnitsByTypeRequest struct to calculate the currently consumed cloud units of the specified type for all cloudspaces and resource groups in the account
|
||||
type GetConsumedCloudUnitsByTypeRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -35,9 +35,7 @@ type GetConsumedCloudUnitsByTypeRequest struct {
|
||||
func (a Account) GetConsumedCloudUnitsByType(ctx context.Context, req GetConsumedCloudUnitsByTypeRequest) (float64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getConsumedCloudUnitsByType"
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for download the resources tracking files for an account
|
||||
type GetConsumptionRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||
|
||||
// Epoch represents the start time
|
||||
// Required: true
|
||||
Start uint64 `url:"start" json:"start" validate:"required"`
|
||||
|
||||
// Epoch represents the end time
|
||||
// Required: true
|
||||
End uint64 `url:"end" json:"end" validate:"required"`
|
||||
}
|
||||
|
||||
// GetConsumption downloads the resources tracking files for an account within a given period
|
||||
func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return "", validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getConsumption"
|
||||
|
||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(res), nil
|
||||
|
||||
}
|
||||
|
||||
// GetConsumptionGet downloads the resources tracking files for an account within a given period
|
||||
func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return "", validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getConsumption"
|
||||
|
||||
res, err := a.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(res), nil
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for calculate the reserved units for all cloudspaces and resource groups in the account
|
||||
// GetReservedAccountUnitsRequest struct to calculate the reserved units for all cloudspaces and resource groups in the account
|
||||
type GetReservedAccountUnitsRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -26,9 +26,7 @@ type GetReservedAccountUnitsRequest struct {
|
||||
func (a Account) GetReservedAccountUnits(ctx context.Context, req GetReservedAccountUnitsRequest) (*ResourceLimits, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getReservedAccountUnits"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for getting resource consumption
|
||||
// GetResourceConsumptionRequest struct to get resource consumption
|
||||
type GetResourceConsumptionRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type GetResourceConsumptionRequest struct {
|
||||
func (a Account) GetResourceConsumption(ctx context.Context, req GetResourceConsumptionRequest) (*RecordResourceConsumption, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/getResourceConsumption"
|
||||
|
||||
73
pkg/cloudapi/account/ids.go
Normal file
73
pkg/cloudapi/account/ids.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package account
|
||||
|
||||
// IDs gets array of AccountIDs from ListAccounts struct
|
||||
func (la ListAccounts) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(la.Data))
|
||||
for _, acc := range la.Data {
|
||||
res = append(res, acc.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of ComputeIDs from ListComputes struct
|
||||
func (lc ListComputes) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lc.Data))
|
||||
for _, c := range lc.Data {
|
||||
res = append(res, c.ComputeID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of DiskIDs from ListDisks struct
|
||||
func (ld ListDisks) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(ld.Data))
|
||||
for _, d := range ld.Data {
|
||||
res = append(res, d.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of FLIPGroupIDs from ListFLIPGroups struct
|
||||
func (fg ListFLIPGroups) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(fg.Data))
|
||||
for _, g := range fg.Data {
|
||||
res = append(res, g.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of AccountIDs from ListResourceConsumption struct
|
||||
func (rc ListResourceConsumption) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(rc.Data))
|
||||
for _, r := range rc.Data {
|
||||
res = append(res, r.AccountID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of RGIDs from ListRG struct
|
||||
func (rg ListRG) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(rg.Data))
|
||||
for _, g := range rg.Data {
|
||||
res = append(res, g.RGID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of TemplateIDs from ListTemplates struct
|
||||
func (lt ListTemplates) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lt.Data))
|
||||
for _, t := range lt.Data {
|
||||
res = append(res, t.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of VINSIDs from ListVINS struct
|
||||
func (lv ListVINS) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lv.Data))
|
||||
for _, v := range lv.Data {
|
||||
res = append(res, v.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// ListRequest struct to get list of accounts
|
||||
@@ -24,6 +26,10 @@ type ListRequest struct {
|
||||
// Required: false
|
||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -35,6 +41,7 @@ type ListRequest struct {
|
||||
|
||||
// List gets a list of all accounts the user has access to a ListAccounts struct
|
||||
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
||||
|
||||
res, err := a.ListRaw(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -52,6 +59,11 @@ func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, erro
|
||||
|
||||
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
||||
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||
|
||||
if err := validators.ValidateRequest(req); err != nil {
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/list"
|
||||
|
||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for a get list compute instances
|
||||
// ListComputesRequest struct to get a list of compute instances
|
||||
type ListComputesRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -46,6 +46,10 @@ type ListComputesRequest struct {
|
||||
// Required: false
|
||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -57,11 +61,10 @@ type ListComputesRequest struct {
|
||||
|
||||
// ListComputes gets list all compute instances under specified account, accessible by the user
|
||||
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listComputes"
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list deleted accounts
|
||||
// ListDeletedRequest struct to get a list of deleted accounts
|
||||
type ListDeletedRequest struct {
|
||||
// Page number
|
||||
// Required: false
|
||||
@@ -27,10 +29,20 @@ type ListDeletedRequest struct {
|
||||
// Find by access control list
|
||||
// Required: false
|
||||
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
}
|
||||
|
||||
// ListDeleted gets list all deleted accounts the user has access to
|
||||
// ListDeleted gets list of all deleted accounts the user has access to
|
||||
func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listDeleted"
|
||||
|
||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list deleted disks
|
||||
// ListDisksRequest struct to get a list of deleted disks
|
||||
type ListDisksRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -30,6 +30,10 @@ type ListDisksRequest struct {
|
||||
// Required: false
|
||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -41,11 +45,10 @@ type ListDisksRequest struct {
|
||||
|
||||
// ListDisks gets list all currently unattached disks under specified account
|
||||
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listDisks"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list FLIPGroups
|
||||
// ListFLIPGroupsRequest struct to get a list of FLIPGroups
|
||||
type ListFLIPGroupsRequest struct {
|
||||
// ID of the account
|
||||
// Required: true
|
||||
@@ -38,6 +38,10 @@ type ListFLIPGroupsRequest struct {
|
||||
// Required: false
|
||||
FLIPGroupID uint64 `url:"flipGroupId,omitempty" json:"flipGroupId,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -49,11 +53,10 @@ type ListFLIPGroupsRequest struct {
|
||||
|
||||
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
|
||||
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listFlipGroups"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list resource groups
|
||||
// ListRGRequest struct to get a list of resource groups
|
||||
type ListRGRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -41,15 +41,18 @@ type ListRGRequest struct {
|
||||
// Find by status
|
||||
// Required: false
|
||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
}
|
||||
|
||||
// ListRG gets list all resource groups under specified account, accessible by the user
|
||||
// ListRG gets list of all resource groups under specified account, accessible by the user
|
||||
func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listRG"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list templates
|
||||
// ListTemplatesRequest struct to get a list of templates
|
||||
type ListTemplatesRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -30,6 +30,10 @@ type ListTemplatesRequest struct {
|
||||
// Required: false
|
||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -39,13 +43,12 @@ type ListTemplatesRequest struct {
|
||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// ListTemplates gets list templates which can be managed by this account
|
||||
// ListTemplates gets list of templates which can be managed by this account
|
||||
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listTemplates"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list VINS
|
||||
// ListVINSRequest struct to get a list of VINS
|
||||
type ListVINSRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -30,6 +30,10 @@ type ListVINSRequest struct {
|
||||
// Required: false
|
||||
ExtIP string `url:"extIp,omitempty" json:"extIp,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -39,13 +43,12 @@ type ListVINSRequest struct {
|
||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// ListVINS gets list all ViNSes under specified account, accessible by the user
|
||||
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
||||
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
||||
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/listVins"
|
||||
|
||||
@@ -53,12 +53,18 @@ type ItemAccount struct {
|
||||
// Access Control List
|
||||
ACL []RecordACL `json:"acl"`
|
||||
|
||||
// Compute Features
|
||||
ComputeFeatures []string `json:"computeFeatures"`
|
||||
|
||||
// Created time
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
|
||||
// Deleted time
|
||||
DeletedTime uint64 `json:"deletedTime"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
@@ -176,6 +182,9 @@ type RecordAccount struct {
|
||||
// Company URL
|
||||
CompanyURL string `json:"companyurl"`
|
||||
|
||||
// Compute Features
|
||||
ComputeFeatures []string `json:"computeFeatures"`
|
||||
|
||||
// Computes
|
||||
Computes Computes `json:"computes"`
|
||||
|
||||
@@ -191,6 +200,9 @@ type RecordAccount struct {
|
||||
// Created time
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Deactivation time
|
||||
DeactivationTime float64 `json:"deactivationTime"`
|
||||
|
||||
@@ -374,6 +386,12 @@ type ItemVINS struct {
|
||||
// External IP
|
||||
ExternalIP string `json:"externalIP"`
|
||||
|
||||
// Extnet ID
|
||||
ExtnetId uint64 `json:"extnetId"`
|
||||
|
||||
// Free IPs
|
||||
FreeIPs int64 `json:"freeIPs"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
@@ -500,6 +518,9 @@ type ItemRG struct {
|
||||
// Deleted time
|
||||
DeletedTime uint64 `json:"deletedTime"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Resource group ID
|
||||
RGID uint64 `json:"id"`
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for restore a deleted account
|
||||
// RestoreRequest struct to restore a deleted account
|
||||
type RestoreRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
@@ -17,9 +17,7 @@ type RestoreRequest struct {
|
||||
func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/restore"
|
||||
|
||||
@@ -8,12 +8,16 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for updaate account
|
||||
// UpdateRequest struct to update account
|
||||
type UpdateRequest struct {
|
||||
// ID an account
|
||||
// Required: true
|
||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||
|
||||
// Description
|
||||
// Required: false
|
||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||
|
||||
// Name of the account
|
||||
// Required: false
|
||||
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||
@@ -45,15 +49,18 @@ type UpdateRequest struct {
|
||||
// Limit (positive) or disable (0) GPU resources
|
||||
// Required: false
|
||||
GPUUnits int64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
||||
|
||||
// List of strings with pools
|
||||
// i.e.: ["sep1_poolName1", "sep2_poolName2", etc]
|
||||
// Required: false
|
||||
UniqPools []string `url:"uniqPools,omitempty" json:"uniqPools,omitempty"`
|
||||
}
|
||||
|
||||
// Update updates an account name and resource types and limits
|
||||
func (a Account) Update(ctx context.Context, req UpdateRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/update"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for update user access rights
|
||||
// UpdateUserRequest struct to update user access rights
|
||||
type UpdateUserRequest struct {
|
||||
// ID of the account
|
||||
// Required: true
|
||||
@@ -30,9 +30,7 @@ type UpdateUserRequest struct {
|
||||
func (a Account) UpdateUser(ctx context.Context, req UpdateUserRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/account/updateUser"
|
||||
|
||||
10
pkg/cloudapi/audit.go
Normal file
10
pkg/cloudapi/audit.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package cloudapi
|
||||
|
||||
import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/audit"
|
||||
)
|
||||
|
||||
// Accessing the Stack method group
|
||||
func (ca *CloudAPI) Audit() *audit.Audit {
|
||||
return audit.New(ca.client)
|
||||
}
|
||||
15
pkg/cloudapi/audit/audit.go
Normal file
15
pkg/cloudapi/audit/audit.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package audit
|
||||
|
||||
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||
|
||||
// Structure for creating request to audit
|
||||
type Audit struct {
|
||||
client interfaces.Caller
|
||||
}
|
||||
|
||||
// Builder for audit endpoint
|
||||
func New(client interfaces.Caller) *Audit{
|
||||
return &Audit{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
46
pkg/cloudapi/audit/get.go
Normal file
46
pkg/cloudapi/audit/get.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// GetRequest struct to get information about account
|
||||
type GetRequest struct {
|
||||
// Audit GUID
|
||||
// Required: true
|
||||
AuditGuid string `url:"audit_guid" json:"audit_guid" validate:"required"`
|
||||
}
|
||||
|
||||
// Get gets information about audit as a RecordAudit struct
|
||||
func (a Audit) Get(ctx context.Context, req GetRequest) (*RecordAudit, error) {
|
||||
res, err := a.GetRaw(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := RecordAudit{}
|
||||
|
||||
err = json.Unmarshal(res, &info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// GetRaw gets information about audit as an array of bytes
|
||||
func (a Audit) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/audit/get"
|
||||
|
||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
return res, err
|
||||
}
|
||||
41
pkg/cloudapi/audit/models.go
Normal file
41
pkg/cloudapi/audit/models.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package audit
|
||||
|
||||
// Main info about audit
|
||||
type RecordAudit struct {
|
||||
|
||||
// Arguments
|
||||
Arguments string `json:"args"`
|
||||
|
||||
// Call
|
||||
Call string `json:"call"`
|
||||
|
||||
// GUID
|
||||
GUID string `json:"guid"`
|
||||
|
||||
// Kwargs
|
||||
Kwargs string `json:"kwargs"`
|
||||
|
||||
// RemoteAddr
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
|
||||
// Response time
|
||||
ResponseTime float64 `json:"responsetime"`
|
||||
|
||||
// Result
|
||||
Result string `json:"result"`
|
||||
|
||||
// Status code
|
||||
StatusCode uint64 `json:"statuscode"`
|
||||
|
||||
// Tags
|
||||
Tags string `json:"tags"`
|
||||
|
||||
// Timestamp
|
||||
Timestamp float64 `json:"timestamp"`
|
||||
|
||||
// TimestampEnd
|
||||
TimestampEnd float64 `json:"timestampEnd"`
|
||||
|
||||
// User
|
||||
User string `json:"user"`
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for BasicService
|
||||
// CreateRequest struct for BasicService
|
||||
type CreateRequest struct {
|
||||
// Name of the service
|
||||
// Required: true
|
||||
@@ -31,9 +31,7 @@ type CreateRequest struct {
|
||||
func (b BService) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/create"
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for delete basic service
|
||||
// DeleteRequest struct to delete basic service
|
||||
type DeleteRequest struct {
|
||||
// ID of the BasicService to be delete
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// If set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately
|
||||
// Required: false
|
||||
@@ -23,9 +23,7 @@ type DeleteRequest struct {
|
||||
func (b BService) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/delete"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for disable service
|
||||
// DisableRequest struct for disable service
|
||||
type DisableRequest struct {
|
||||
// ID of the service to disable
|
||||
// Required: true
|
||||
@@ -21,12 +21,10 @@ type DisableRequest struct {
|
||||
func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/delete"
|
||||
url := "/cloudapi/bservice/disable"
|
||||
|
||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for disable service
|
||||
// EnableRequest struct to disable service
|
||||
type EnableRequest struct {
|
||||
// ID of the service to enable
|
||||
// Required: true
|
||||
@@ -22,9 +22,7 @@ type EnableRequest struct {
|
||||
func (b BService) Enable(ctx context.Context, req EnableRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/enable"
|
||||
|
||||
@@ -36,9 +36,7 @@ func (b BService) Get(ctx context.Context, req GetRequest) (*RecordBasicService,
|
||||
func (b BService) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/get"
|
||||
|
||||
@@ -8,42 +8,41 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for create new compute group within BasicService
|
||||
// GroupAddRequest struct to create new compute group within BasicService
|
||||
type GroupAddRequest struct {
|
||||
// ID of the Basic Service to add a group to
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// Name of the Compute Group to add
|
||||
// Required: true
|
||||
Name string `url:"name" json:"name" validate:"required"`
|
||||
Name string `url:"name" json:"name" validate:"required"`
|
||||
|
||||
// Computes number. Defines how many computes must be there in the group
|
||||
// Required: true
|
||||
Count uint64 `url:"count" json:"count" validate:"required"`
|
||||
Count uint64 `url:"count" json:"count" validate:"required"`
|
||||
|
||||
// Compute CPU number. All computes in the group have the same CPU count
|
||||
// Required: true
|
||||
CPU uint64 `url:"cpu" json:"cpu" validate:"required"`
|
||||
CPU uint64 `url:"cpu" json:"cpu" validate:"required"`
|
||||
|
||||
// Compute RAM volume in MB. All computes in the group have the same RAM volume
|
||||
// Required: true
|
||||
RAM uint64 `url:"ram" json:"ram" validate:"required"`
|
||||
RAM uint64 `url:"ram" json:"ram" validate:"required"`
|
||||
|
||||
// Compute boot disk size in GB
|
||||
// Required: true
|
||||
Disk uint64 `url:"disk" json:"disk" validate:"required"`
|
||||
Disk uint64 `url:"disk" json:"disk" validate:"required"`
|
||||
|
||||
// OS image ID to create computes from
|
||||
// Required: true
|
||||
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
||||
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
||||
|
||||
// Compute driver
|
||||
// should be one of:
|
||||
// - KVM_X86
|
||||
// - KVM_PPC
|
||||
// Required: true
|
||||
Driver string `url:"driver" json:"driver" validate:"driver"`
|
||||
Driver string `url:"driver" json:"driver" validate:"driver"`
|
||||
|
||||
// Storage endpoint provider ID
|
||||
// Required: false
|
||||
@@ -72,6 +71,20 @@ type GroupAddRequest struct {
|
||||
// Meta data for working group computes, format YAML "user_data": 1111
|
||||
// Required: false
|
||||
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
||||
|
||||
//Chipset "i440fx" or "Q35
|
||||
//Required: false
|
||||
Chipset string `url:"chipset,omitempty" json:"chipset,omitempty" validate:"chipset,omitempty"`
|
||||
}
|
||||
|
||||
// GetRAM returns RAM field values
|
||||
func (r GroupAddRequest) GetRAM() map[string]uint64 {
|
||||
|
||||
res := make(map[string]uint64, 1)
|
||||
|
||||
res["RAM"] = r.RAM
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// GroupAdd creates new Compute Group within BasicService.
|
||||
@@ -80,9 +93,7 @@ type GroupAddRequest struct {
|
||||
func (b BService) GroupAdd(ctx context.Context, req GroupAddRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupAdd"
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for remove group compute
|
||||
// GroupComputeRemoveRequest struct to remove group compute
|
||||
type GroupComputeRemoveRequest struct {
|
||||
// ID of the Basic Service
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute GROUP
|
||||
// Required: true
|
||||
@@ -27,9 +27,7 @@ type GroupComputeRemoveRequest struct {
|
||||
func (b BService) GroupComputeRemove(ctx context.Context, req GroupComputeRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupComputeRemove"
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get detailed information about Compute Group
|
||||
// GroupGetRequest struct to get detailed information about Compute Group
|
||||
type GroupGetRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute Group
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type GroupGetRequest struct {
|
||||
func (b BService) GroupGet(ctx context.Context, req GroupGetRequest) (*RecordGroup, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupGet"
|
||||
|
||||
@@ -8,12 +8,11 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for add parent Compute Group relation emove parent Compute Group
|
||||
// relation to the specified Compute Group
|
||||
// GroupParentAddRequest struct to add parent Compute Group relation to the specified Compute Group
|
||||
type GroupParentAddRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute Group
|
||||
// Required: true
|
||||
@@ -28,9 +27,7 @@ type GroupParentAddRequest struct {
|
||||
func (b BService) GroupParentAdd(ctx context.Context, req GroupParentAddRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupParentAdd"
|
||||
|
||||
@@ -8,30 +8,28 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for remove parent Compute Group
|
||||
// relation to the specified Compute Group
|
||||
// GroupParentRemoveRequest struct to remove parent Compute Group
|
||||
// relation from the specified Compute Group
|
||||
type GroupParentRemoveRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute Group
|
||||
// Required: true
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
|
||||
// ID of the parent Compute Group
|
||||
// to remove from the current Compute Group
|
||||
// Required: true
|
||||
ParentID uint64 `url:"parentId" json:"parentId" validate:"required"`
|
||||
ParentID uint64 `url:"parentId" json:"parentId" validate:"required"`
|
||||
}
|
||||
|
||||
// GroupParentRemove removes parent Compute Group relation to the specified Compute Group
|
||||
func (b BService) GroupParentRemove(ctx context.Context, req GroupParentRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupParentRemove"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for destroy the specified Compute Group
|
||||
// GroupRemoveRequest struct for destroy the specified Compute Group
|
||||
type GroupRemoveRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type GroupRemoveRequest struct {
|
||||
func (b BService) GroupRemove(ctx context.Context, req GroupRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupRemove"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for resize the group
|
||||
// GroupResizeRequest struct to resize the group
|
||||
type GroupResizeRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
@@ -22,6 +22,12 @@ type GroupResizeRequest struct {
|
||||
// Required: true
|
||||
Count int64 `url:"count" json:"count" validate:"required"`
|
||||
|
||||
//Chipset for new computes, either i440fx or Q35 (i440fx by default)
|
||||
//Available values : i440fx, Q35
|
||||
//Default value : i440fx
|
||||
//Required: true
|
||||
Chipset string `url:"chipset" json:"chipset" validate:"required,chipset"`
|
||||
|
||||
// Either delta or absolute value of computes
|
||||
// Should be one of:
|
||||
// - ABSOLUTE
|
||||
@@ -34,9 +40,7 @@ type GroupResizeRequest struct {
|
||||
func (b BService) GroupResize(ctx context.Context, req GroupResizeRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupResize"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for start the specified Compute Group
|
||||
// GroupStartRequest struct to start the specified Compute Group
|
||||
type GroupStartRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type GroupStartRequest struct {
|
||||
func (b BService) GroupStart(ctx context.Context, req GroupStartRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupStart"
|
||||
|
||||
@@ -8,15 +8,15 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for stop the specified Compute Group
|
||||
// GroupStopRequest struct to stop the specified Compute Group
|
||||
type GroupStopRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute Group to stop
|
||||
// Required: true
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
|
||||
// Force stop Compute Group
|
||||
// Required: false
|
||||
@@ -27,9 +27,7 @@ type GroupStopRequest struct {
|
||||
func (b BService) GroupStop(ctx context.Context, req GroupStopRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupStop"
|
||||
|
||||
@@ -8,15 +8,15 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for update existing Compute group
|
||||
// GroupUpdateRequest struct to update existing Compute group
|
||||
type GroupUpdateRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||
|
||||
// ID of the Compute Group
|
||||
// Required: true
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||
|
||||
// Specify non-empty string to update Compute Group name
|
||||
// Required: false
|
||||
@@ -43,13 +43,21 @@ type GroupUpdateRequest struct {
|
||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||
}
|
||||
|
||||
// GetRAM returns RAM field values
|
||||
func (r GroupUpdateRequest) GetRAM() map[string]uint64 {
|
||||
|
||||
res := make(map[string]uint64, 1)
|
||||
|
||||
res["RAM"] = r.RAM
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// GroupUpdate updates existing Compute group within Basic Service and apply new settings to its computes as necessary
|
||||
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupUpdate"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for update External Network settings
|
||||
// GroupUpdateExtNetRequest struct to update External Network settings
|
||||
type GroupUpdateExtNetRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
@@ -27,9 +27,7 @@ type GroupUpdateExtNetRequest struct {
|
||||
func (b BService) GroupUpdateExtNet(ctx context.Context, req GroupUpdateExtNetRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupUpdateExtnet"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for update VINS settings
|
||||
// GroupUpdateVINSRequest struct to update VINS settings
|
||||
type GroupUpdateVINSRequest struct {
|
||||
// ID of the Basic Service of Compute Group
|
||||
// Required: true
|
||||
@@ -27,9 +27,7 @@ type GroupUpdateVINSRequest struct {
|
||||
func (b BService) GroupUpdateVINS(ctx context.Context, req GroupUpdateVINSRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/groupUpdateVins"
|
||||
|
||||
37
pkg/cloudapi/bservice/ids.go
Normal file
37
pkg/cloudapi/bservice/ids.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package bservice
|
||||
|
||||
// IDs gets array of BasicServiceIDs from ListBasicServices struct
|
||||
func (lbs ListBasicServices) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lbs.Data))
|
||||
for _, bs := range lbs.Data {
|
||||
res = append(res, bs.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of ComputeIDs from ListComputes struct
|
||||
func (lc ListComputes) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lc))
|
||||
for _, c := range lc {
|
||||
res = append(res, c.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of GroupIDs from ListGroups struct
|
||||
func (lg ListGroups) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lg))
|
||||
for _, g := range lg {
|
||||
res = append(res, g.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// IDs gets array of GroupComputeIDs from ListGroupComputes struct
|
||||
func (lgc ListGroupComputes) IDs() []uint64 {
|
||||
res := make([]uint64, 0, len(lgc))
|
||||
for _, gc := range lgc {
|
||||
res = append(res, gc.ID)
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// ListRequest struct to get list of BasicService instances
|
||||
@@ -40,6 +42,10 @@ type ListRequest struct {
|
||||
// Required: false
|
||||
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -51,6 +57,7 @@ type ListRequest struct {
|
||||
|
||||
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
||||
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
||||
|
||||
res, err := b.ListRaw(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -68,6 +75,11 @@ func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices
|
||||
|
||||
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
||||
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||
|
||||
if err := validators.ValidateRequest(req); err != nil {
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/list"
|
||||
|
||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list of deleted BasicService instances
|
||||
// ListDeletedRequest struct to get list of deleted BasicService instances
|
||||
type ListDeletedRequest struct {
|
||||
// ID of the account to query for BasicService instances
|
||||
// Required: false
|
||||
@@ -16,6 +18,10 @@ type ListDeletedRequest struct {
|
||||
// Required: false
|
||||
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||
|
||||
// Sort by one of supported fields, format +|-(field)
|
||||
// Required: false
|
||||
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
@@ -25,8 +31,13 @@ type ListDeletedRequest struct {
|
||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// ListDeleted gets list deleted BasicService instances associated with the specified Resource Group
|
||||
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
||||
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
|
||||
|
||||
if err := validators.ValidateRequest(req); err != nil {
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/listDeleted"
|
||||
|
||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
|
||||
@@ -93,7 +93,7 @@ type RecordBasicService struct {
|
||||
// Main information about Compute
|
||||
type ItemCompute struct {
|
||||
// Account ID
|
||||
AccountID uint64
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
// Architecture
|
||||
Architecture string `json:"arch"`
|
||||
@@ -168,9 +168,18 @@ type ItemSnapshot struct {
|
||||
Valid bool `json:"valid"`
|
||||
}
|
||||
|
||||
// List of Snapshots
|
||||
// List of Snapshot
|
||||
type ListSnapshots []ItemSnapshot
|
||||
|
||||
// List of Snapshots
|
||||
type ListInfoSnapshots struct {
|
||||
// Data
|
||||
Data ListSnapshots `json:"data"`
|
||||
|
||||
// EntryCount
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
}
|
||||
|
||||
// Main information about Group
|
||||
type RecordGroup struct {
|
||||
// Account ID
|
||||
@@ -286,6 +295,9 @@ type ItemGroupCompute struct {
|
||||
|
||||
// List of information about OS Users
|
||||
OSUsers ListOSUsers `json:"osUsers"`
|
||||
|
||||
//Chipset
|
||||
Chipset string `json:"chipset"`
|
||||
}
|
||||
|
||||
// List of Group Computes
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for restores BasicService instance
|
||||
// RestoreRequest struct to restore BasicService instance
|
||||
type RestoreRequest struct {
|
||||
// ID of the BasicService to be restored
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type RestoreRequest struct {
|
||||
func (b BService) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/restore"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for create snapshot
|
||||
// SnapshotCreateRequest struct to create snapshot
|
||||
type SnapshotCreateRequest struct {
|
||||
// ID of the Basic Service
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type SnapshotCreateRequest struct {
|
||||
func (b BService) SnapshotCreate(ctx context.Context, req SnapshotCreateRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/snapshotCreate"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for delete snapshot
|
||||
// SnapshotDeleteRequest struct to delete snapshot
|
||||
type SnapshotDeleteRequest struct {
|
||||
// ID of the Basic Service
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type SnapshotDeleteRequest struct {
|
||||
func (b BService) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/snapshotDelete"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list existing snapshots
|
||||
// SnapshotListRequest struct to get list of existing snapshots
|
||||
type SnapshotListRequest struct {
|
||||
// ID of the Basic Service
|
||||
// Required: true
|
||||
@@ -16,12 +16,10 @@ type SnapshotListRequest struct {
|
||||
}
|
||||
|
||||
// SnapshotList gets list existing snapshots of the Basic Service
|
||||
func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (ListSnapshots, error) {
|
||||
func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (*ListInfoSnapshots, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/snapshotList"
|
||||
@@ -31,12 +29,12 @@ func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (Li
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := ListSnapshots{}
|
||||
list := ListInfoSnapshots{}
|
||||
|
||||
err = json.Unmarshal(res, &list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return list, nil
|
||||
return &list, nil
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for rollback snapshot
|
||||
// SnapshotRollbackRequest struct to rollback snapshot
|
||||
type SnapshotRollbackRequest struct {
|
||||
// ID of the Basic Service
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type SnapshotRollbackRequest struct {
|
||||
func (b BService) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/snapshotRollback"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for start service
|
||||
// StartRequest struct to start service
|
||||
type StartRequest struct {
|
||||
// ID of the service to start
|
||||
// Required: true
|
||||
@@ -21,9 +21,7 @@ type StartRequest struct {
|
||||
func (b BService) Start(ctx context.Context, req StartRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/start"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for stop service
|
||||
// StopRequest struct to stop service
|
||||
type StopRequest struct {
|
||||
// ID of the service to stop
|
||||
// Required: true
|
||||
@@ -21,9 +21,7 @@ type StopRequest struct {
|
||||
func (b BService) Stop(ctx context.Context, req StopRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/bservice/stop"
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for check all computes with current affinity label can start
|
||||
// AffinityGroupCheckStartRequest struct to check all computes with current affinity label can start
|
||||
type AffinityGroupCheckStartRequest struct {
|
||||
// ID of the resource group
|
||||
// Required: true
|
||||
@@ -22,9 +22,7 @@ type AffinityGroupCheckStartRequest struct {
|
||||
func (c Compute) AffinityGroupCheckStart(ctx context.Context, req AffinityGroupCheckStartRequest) (string, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return "", validators.ValidationError(validationError)
|
||||
}
|
||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityGroupCheckStart"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for clear affinity label for compute
|
||||
// AffinityLabelRemoveRequest struct to clear affinity label for compute
|
||||
type AffinityLabelRemoveRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AffinityLabelRemoveRequest struct {
|
||||
func (c Compute) AffinityLabelRemove(ctx context.Context, req AffinityLabelRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityLabelRemove"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for set affinity label for compute
|
||||
// AffinityLabelSetRequest struct to set affinity label for compute
|
||||
type AffinityLabelSetRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type AffinityLabelSetRequest struct {
|
||||
func (c Compute) AffinityLabelSet(ctx context.Context, req AffinityLabelSetRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityLabelSet"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get dict of computes
|
||||
// AffinityRelationsRequest struct to get dict of computes
|
||||
type AffinityRelationsRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AffinityRelationsRequest struct {
|
||||
func (c Compute) AffinityRelations(ctx context.Context, req AffinityRelationsRequest) (*RecordAffinityRelations, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityRelations"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for add affinity rule
|
||||
// AffinityRuleAddRequest struct to add affinity rule
|
||||
type AffinityRuleAddRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -38,17 +38,16 @@ type AffinityRuleAddRequest struct {
|
||||
Key string `url:"key" json:"key" validate:"required"`
|
||||
|
||||
// Value that must match the key to be taken into account when analyzing this rule
|
||||
// Required: true
|
||||
Value string `url:"value" json:"value" validate:"required"`
|
||||
// Required: false
|
||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||
Value string `url:"value" json:"value"`
|
||||
}
|
||||
|
||||
// AffinityRuleAdd add affinity rule
|
||||
func (c Compute) AffinityRuleAdd(ctx context.Context, req AffinityRuleAddRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityRuleAdd"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for remove affinity rule
|
||||
// AffinityRuleRemoveRequest struct to remove affinity rule
|
||||
type AffinityRuleRemoveRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -38,17 +38,16 @@ type AffinityRuleRemoveRequest struct {
|
||||
Key string `url:"key" json:"key" validate:"required"`
|
||||
|
||||
// Value that must match the key to be taken into account when analyzing this rule
|
||||
// Required: true
|
||||
Value string `url:"value" json:"value" validate:"required"`
|
||||
// Required: false
|
||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||
Value string `url:"value" json:"value"`
|
||||
}
|
||||
|
||||
// AffinityRuleRemove remove affinity rule
|
||||
func (c Compute) AffinityRuleRemove(ctx context.Context, req AffinityRuleRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityRuleRemove"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for clear affinity rules
|
||||
// AffinityRulesClearRequest struct to clear affinity rules
|
||||
type AffinityRulesClearRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AffinityRulesClearRequest struct {
|
||||
func (c Compute) AffinityRulesClear(ctx context.Context, req AffinityRulesClearRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/affinityRulesClear"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for add anti affinity rule
|
||||
// AntiAffinityRuleAddRequest struct to add anti affinity rule
|
||||
type AntiAffinityRuleAddRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -38,17 +38,16 @@ type AntiAffinityRuleAddRequest struct {
|
||||
Key string `url:"key" json:"key" validate:"required"`
|
||||
|
||||
// Value that must match the key to be taken into account when analyzing this rule
|
||||
// Required: true
|
||||
Value string `url:"value" json:"value" validate:"required"`
|
||||
// Required: false
|
||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||
Value string `url:"value" json:"value"`
|
||||
}
|
||||
|
||||
// AntiAffinityRuleAdd add anti affinity rule
|
||||
func (c Compute) AntiAffinityRuleAdd(ctx context.Context, req AntiAffinityRuleAddRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/antiAffinityRuleAdd"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for remove anti affinity rule
|
||||
// AntiAffinityRuleRemoveRequest struct to remove anti affinity rule
|
||||
type AntiAffinityRuleRemoveRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -38,17 +38,16 @@ type AntiAffinityRuleRemoveRequest struct {
|
||||
Key string `url:"key" json:"key" validate:"required"`
|
||||
|
||||
// Value that must match the key to be taken into account when analyzing this rule
|
||||
// Required: true
|
||||
Value string `url:"value" json:"value" validate:"required"`
|
||||
// Required: false
|
||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||
Value string `url:"value" json:"value"`
|
||||
}
|
||||
|
||||
// AntiAffinityRuleRemove remove anti affinity rule
|
||||
func (c Compute) AntiAffinityRuleRemove(ctx context.Context, req AntiAffinityRuleRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/antiAffinityRuleRemove"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for clear anti affinity rules
|
||||
// AntiAffinityRulesClearRequest struct to clear anti affinity rules
|
||||
type AntiAffinityRulesClearRequest struct {
|
||||
// ID of the compute instance
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AntiAffinityRulesClearRequest struct {
|
||||
func (c Compute) AntiAffinityRulesClear(ctx context.Context, req AntiAffinityRulesClearRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/antiAffinityRulesClear"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for attach GPU for compute
|
||||
// AttachGPURequest struct to attach GPU for compute
|
||||
type AttachGPURequest struct {
|
||||
// Identifier compute
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type AttachGPURequest struct {
|
||||
func (c Compute) AttachGPU(ctx context.Context, req AttachGPURequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/attachGpu"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for atttach PCI device
|
||||
// AttachPCIDeviceRequest struct to attach PCI device
|
||||
type AttachPCIDeviceRequest struct {
|
||||
// Identifier compute
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type AttachPCIDeviceRequest struct {
|
||||
func (c Compute) AttachPCIDevice(ctx context.Context, req AttachPCIDeviceRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/attachPciDevice"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get audit records
|
||||
// AuditsRequest struct to get audit records
|
||||
type AuditsRequest struct {
|
||||
// ID of the compute
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type AuditsRequest struct {
|
||||
func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/audits"
|
||||
|
||||
@@ -8,27 +8,25 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for repair filesystem
|
||||
type RepairBootFSRequest struct {
|
||||
// BootDiskSetRequest struct to set boot disk for compute
|
||||
type BootDiskSetRequest struct {
|
||||
// ID of compute instance
|
||||
// Required: true
|
||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||
|
||||
// Reason for action
|
||||
// Required: false
|
||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
||||
// ID of the disk to set as boot
|
||||
// Required: true
|
||||
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||
}
|
||||
|
||||
// RepairBootFS repair compute boot disk filesystem
|
||||
func (c Compute) RepairBootFS(ctx context.Context, req RepairBootFSRequest) (bool, error) {
|
||||
// BootDiskSet sets boot disk for compute
|
||||
func (c Compute) BootDiskSet(ctx context.Context, req BootDiskSetRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudbroker/compute/repairBootFs"
|
||||
url := "/cloudapi/compute/bootDiskSet"
|
||||
|
||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for getting boot order
|
||||
// BootOrderGetRequest struct to get boot order
|
||||
type BootOrderGetRequest struct {
|
||||
// Compute ID
|
||||
// Required: true
|
||||
@@ -18,9 +18,7 @@ type BootOrderGetRequest struct {
|
||||
func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/bootOrderGet"
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for setting boot order
|
||||
// BootOrderSetRequest struct to set boot order
|
||||
type BootOrderSetRequest struct {
|
||||
// ID of compute instance
|
||||
// Required: true
|
||||
@@ -26,9 +26,7 @@ type BootOrderSetRequest struct {
|
||||
func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/bootOrderSet"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for eject CD image
|
||||
// CDEjectRequest struct to eject CD image
|
||||
type CDEjectRequest struct {
|
||||
// ID of compute instance
|
||||
// Required: true
|
||||
@@ -19,9 +19,7 @@ type CDEjectRequest struct {
|
||||
func (c Compute) CDEject(ctx context.Context, req CDEjectRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/cdEject"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for insert new CD image
|
||||
// CDInsertRequest struct to insert new CD image
|
||||
type CDInsertRequest struct {
|
||||
// ID of compute instance
|
||||
// Required: true
|
||||
@@ -23,9 +23,7 @@ type CDInsertRequest struct {
|
||||
func (c Compute) CDInsert(ctx context.Context, req CDInsertRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/cdInsert"
|
||||
|
||||
54
pkg/cloudapi/compute/change_ip.go
Normal file
54
pkg/cloudapi/compute/change_ip.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package compute
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// ChangeIPRequest struct to change IP for network
|
||||
type ChangeIPRequest struct {
|
||||
// ID of compute instance
|
||||
// Required: true
|
||||
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||
|
||||
// Network type
|
||||
// 'EXTNET' for connect to external network directly
|
||||
// 'VINS' for connect to ViNS
|
||||
// Required: true
|
||||
NetType string `url:"net_type" json:"net_type" validate:"computeNetType"`
|
||||
|
||||
// Network ID for connect to
|
||||
// For EXTNET - external network ID
|
||||
// For VINS - VINS ID
|
||||
// Required: true
|
||||
NetID uint64 `url:"net_id" json:"net_id" validate:"required"`
|
||||
|
||||
// IP address to which we will change the existing one, it must be from the same subnet
|
||||
// Required: true
|
||||
IPAddr string `url:"ip_addr" json:"ip_addr" validate:"required"`
|
||||
}
|
||||
|
||||
// ChangeIP change reserved IP for compute instance
|
||||
func (c Compute) ChangeIP(ctx context.Context, req ChangeIPRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||
}
|
||||
|
||||
url := "/cloudapi/compute/changeIp"
|
||||
|
||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
result, err := strconv.ParseBool(string(res))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user