Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10d6e90dfe | |||
| 0183f50cc8 | |||
| 888923c6ce | |||
| e496f8fb7e | |||
| fda016d011 | |||
| 082f577e17 | |||
| 78a4152471 | |||
| 3e55195831 | |||
| 9f5e76aee4 | |||
| df8b045e77 | |||
| 4d9b8fc9d8 | |||
| e8270453cc | |||
| 7de095302b | |||
| a3711057ba | |||
| 1c59ca338a |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,3 +1,5 @@
|
||||
cmd/
|
||||
.idea/
|
||||
.vscode/
|
||||
.vscode/
|
||||
.fleet/
|
||||
.DS_Store
|
||||
|
||||
14
CHANGELOG.md
14
CHANGELOG.md
@@ -1,14 +1,4 @@
|
||||
## Version 1.5.2
|
||||
## Version 1.5.13
|
||||
|
||||
### Bugfix
|
||||
- Fix tag 'url' VINSID field in cloudbroker/account/list_vins
|
||||
|
||||
- Made the field Reason not required in cloudbroker/account/enable and cloudbroker/account/disable
|
||||
|
||||
- Made the field RecursiveDelete required in cloudbroker/account/deleteUser
|
||||
|
||||
- Add a validator function to a workersGroupName field - must be 3 or more symbol
|
||||
|
||||
- Add a token actuality check, add an error handler in client/client-transport and client/http-client
|
||||
|
||||
- Add a fields SEPID and Pool in ListRequest struct in cloudbroker/disks/list and cloudapi/disks/list
|
||||
- Fix EOF error by closing request
|
||||
|
||||
46
README.md
46
README.md
@@ -62,12 +62,11 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
||||
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
||||
- `BService` - управление группами виртуальных машин (computes);
|
||||
- `Compute` - управление виртуальными машинами (индивидуально);
|
||||
- `ComputeCI` - управление конвейром для создания виртуальных машин;
|
||||
- `Disks` - управление виртуальными дисками;
|
||||
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
||||
- `FLIPgroup` - управление группами "плавающими" ip - адресами;
|
||||
- `Image` - управление образами операционных систем;
|
||||
- `K8CI` - управление конвейром для создания кластера;
|
||||
- `K8CI` - получение информации о конвейере для создания кластера;
|
||||
- `K8S` - управление кластерами kubernetes;
|
||||
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
||||
- `KVMx86` - создание виртуальной машины x86;
|
||||
@@ -84,30 +83,39 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
||||
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
||||
|
||||
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
||||
- `APIAccess` - управление доступом к API и его объектам;
|
||||
- `Backup` - управление резервным копированием;
|
||||
- `Compute` - управление виртуальными машинами (индивидуально);
|
||||
- `Disks` - управление виртуальными дисками;
|
||||
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
||||
- `FLIPGroup` - управление группами с «плавающими» ip адресами;
|
||||
- `Grid` - управление площадками;
|
||||
- `Group` - управление группами пользователей;
|
||||
- `Image` - управление образами операционных систем;
|
||||
- `K8CI` - управление конвейром для создания кластера;
|
||||
- `K8S` - управление кластерами kubernetes;
|
||||
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
||||
- `KVMx86` - создание виртуальной машины x86;
|
||||
- `LB` - управление балансировщиками нагрузки;
|
||||
- `PCIDevice` - управление устройствами;
|
||||
- `RG` - управление ресурсными группами аккаунта;
|
||||
- `SEP` - управление storage endpoint (sep);
|
||||
- `Stack` - получение информации о стеках;
|
||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||
- `User` - управление пользователями (индивидуально);
|
||||
- `VGPU` - управление виртуальными графическими процессорами;
|
||||
- `VINS` - управление виртуальными изолированными сетями.
|
||||
|
||||
## Работа с библиотекой
|
||||
|
||||
Алгоритм работы с библиотекой выглядит следующим образом:
|
||||
|
||||
1. Настройка конфигурации клиента.
|
||||
2. Парсинг конфигурации из файла.
|
||||
3. Создание клиента.
|
||||
4. Создание структуры запроса.
|
||||
5. Выполнение запроса.
|
||||
1. Выполнение одного из действий:
|
||||
- настройка конфигурации клиента;
|
||||
- парсинг конфигурации из файла.
|
||||
2. Создание клиента.
|
||||
3. Создание структуры запроса.
|
||||
4. Выполнение запроса.
|
||||
|
||||
### Настройка конфигурации клиента
|
||||
|
||||
@@ -120,7 +128,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
||||
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true |
|
||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||
| Token | string | Нет | JWT токен |
|
||||
|
||||
#### Пример конфигурации клиента
|
||||
@@ -231,7 +239,6 @@ func main() {
|
||||
- `pkg/cloudapi/account` - для `Account`
|
||||
- `pkg/cloudapi/bservice` - для `Basic Service`
|
||||
- `pkg/cloudapi/compute` - для `Compute`
|
||||
- `pkg/cloudapi/computeci` - для `ComputeCI`
|
||||
- `pkg/cloudapi/disks` - для `Disks`
|
||||
- `pkg/cloudapi/extnet` - для `ExtNet`
|
||||
- `pkg/cloudapi/flipgroup` - для `FLIPGroup`
|
||||
@@ -248,19 +255,27 @@ func main() {
|
||||
- `pkg/cloudapi/vins` - для `VINS`
|
||||
- **cloudbroker**:
|
||||
- `pkg/cloudbroker/account` - для `Account`
|
||||
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
|
||||
- `pkg/cloudbroker/backup` - для `Backup`
|
||||
- `pkg/cloudbroker/compute` - для `Compute`
|
||||
- `pkg/cloudbroker/disks` - для `Disks`
|
||||
- `pkg/cloudbroker/extnet` - для `ExtNet`
|
||||
- `pkg/cloudbroker/flipgroup` - для `FLIPGroup`
|
||||
- `pkg/cloudbroker/grid` - для `Grid`
|
||||
- `pkg/cloudbroker/group` - для `Group`
|
||||
- `pkg/cloudbroker/image` - для `Image`
|
||||
- `pkg/cloudbroker/k8ci` - для `K8CI`
|
||||
- `pkg/cloudbroker/k8s` - для `K8S`
|
||||
- `pkg/cloudbroker/kvmppc` - для `KVMPPC`
|
||||
- `pkg/cloudbroker/kvmx86` - для `KVMX86`
|
||||
- `pkg/cloudbroker/lb` - для `LB`
|
||||
- `pkg/cloudbroker/pcidevice` - для `PCIDevice`
|
||||
- `pkg/cloudbroker/rg` - для `RG`
|
||||
- `pkg/cloudbroker/sep` - для `SEP`
|
||||
- `pkg/cloudbroker/stack` - для `Stack`
|
||||
- `pkg/cloudbroker/tasks` - для `Tasks`
|
||||
- `pkg/cloudbroker/user` - для `User`
|
||||
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
||||
- `pkg/cloudbroker/vins` - для `VINS`
|
||||
|
||||
Все поля структуры имеют описание, в которых содержится:
|
||||
@@ -405,7 +420,6 @@ func main() {
|
||||
- `.Account()` - для работы с `Account`
|
||||
- `.BService()` - для работы с `BService`
|
||||
- `.Compute()` - для работы с `Compute`
|
||||
- `.ComputeCI()` - для работы с `ComputeCI`
|
||||
- `.Disks()` - для работы с `Disks`
|
||||
- `.ExtNet()` - для работы с `ExtNet`
|
||||
- `.FLIPgroup()` - для работы с `FLIPGroup`
|
||||
@@ -424,19 +438,27 @@ func main() {
|
||||
Доступные методы для `.CloudBroker()`:
|
||||
|
||||
- `.Account()` - для работы с `Account`
|
||||
- `.APIAccess()` - для работы с `APIAccess`
|
||||
- `.Backup()` - для работы с `Backup`
|
||||
- `.Compute()` - для работы с `Compute`
|
||||
- `.Disks()` - для работы с `Disks`
|
||||
- `.ExtNet()` - для работы с `ExtNet`
|
||||
- `.FLIPGroup()` - для работы с `FLIPGroup`
|
||||
- `.Grid()` - для работы с `Grid`
|
||||
- `.Group()` - для работы с `Group`
|
||||
- `.Image()` - для работы с `Image`
|
||||
- `.K8CI()` - для работы с `K8CI`
|
||||
- `.K8S()` - для работы с `K8S`
|
||||
- `.KVMPPC()` - для работы с `KVMPPC`
|
||||
- `.KVMx86()` - для работы с `KVMX86`
|
||||
- `.LB()` - для работы с `LB`
|
||||
- `.PCIDevice()` - для работы с `PCIDevice`
|
||||
- `.RG()` - для работы с `RG`
|
||||
- `.SEP()` - для работы с `SEP`
|
||||
- `.Stack()` - для работы с `Stack`
|
||||
- `.Tasks()` - для работы с `Tasks`
|
||||
- `.User()` - для работы с `User`
|
||||
- `.VGPU()` - для работы с `VGPU`
|
||||
- `.VINS()` - для работы с `VINS`
|
||||
|
||||
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||
@@ -448,7 +470,7 @@ func main() {
|
||||
4. Обработать результат и ошибки.
|
||||
|
||||
Т.к. все вызовы методов идут последовательно, можно их объеденить в конвейер:
|
||||
Общий вид вонвейра будет выглядеть так:
|
||||
Общий вид конвейера будет выглядеть так:
|
||||
|
||||
```go
|
||||
client.<API>.<группа>.<метод>
|
||||
@@ -705,7 +727,7 @@ func main() {
|
||||
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true |
|
||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||
| Token | string | Нет | JWT токен |
|
||||
|
||||
#### Пример конфигурации legacy клиента
|
||||
|
||||
109
client.go
109
client.go
@@ -1,24 +1,31 @@
|
||||
package decortsdk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
|
||||
"github.com/google/go-querystring/query"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/client"
|
||||
)
|
||||
|
||||
// HTTP-client for platform
|
||||
type DecortClient struct {
|
||||
decortURL string
|
||||
client *http.Client
|
||||
decortURL string
|
||||
client *http.Client
|
||||
cfg config.Config
|
||||
expiryTime time.Time
|
||||
mutex *sync.Mutex
|
||||
}
|
||||
|
||||
// Сlient builder
|
||||
@@ -27,9 +34,25 @@ func New(cfg config.Config) *DecortClient {
|
||||
cfg.Retries = 5
|
||||
}
|
||||
|
||||
var expiryTime time.Time
|
||||
|
||||
if cfg.Token != "" {
|
||||
expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
return &DecortClient{
|
||||
decortURL: cfg.DecortURL,
|
||||
client: client.NewHttpClient(cfg),
|
||||
client: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
//nolint:gosec
|
||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||
},
|
||||
},
|
||||
},
|
||||
cfg: cfg,
|
||||
expiryTime: expiryTime,
|
||||
mutex: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +79,11 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := dc.client.Do(req)
|
||||
if err = dc.getToken(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := dc.do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -73,3 +100,75 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
||||
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dc *DecortClient) do(req *http.Request) (*http.Response, error) {
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := dc.client.Do(req)
|
||||
req.Close = true
|
||||
if err != nil || resp == nil {
|
||||
if strings.Contains(err.Error(), "connection reset by peer") || errors.Is(err, io.EOF) {
|
||||
for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||
time.Sleep(5 * time.Second)
|
||||
resp, err = dc.client.Do(req)
|
||||
if strings.Contains(err.Error(), "connection reset by peer") || errors.Is(err, io.EOF) {
|
||||
continue
|
||||
} else if err == nil {
|
||||
break
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
)
|
||||
|
||||
func NewHttpClient(cfg config.Config) *http.Client {
|
||||
|
||||
transCfg := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
//nolint:gosec
|
||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||
},
|
||||
}
|
||||
|
||||
var expiredTime time.Time
|
||||
|
||||
if cfg.Token != "" {
|
||||
expiredTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
return &http.Client{
|
||||
Transport: &transport{
|
||||
base: transCfg,
|
||||
retries: cfg.Retries,
|
||||
clientID: cfg.AppID,
|
||||
clientSecret: cfg.AppSecret,
|
||||
ssoURL: cfg.SSOURL,
|
||||
token: cfg.Token,
|
||||
expiryTime: expiredTime,
|
||||
//TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
},
|
||||
|
||||
Timeout: cfg.Timeout.Get(),
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||
)
|
||||
|
||||
// NewLegacyHttpClient creates legacy HTTP Client
|
||||
func NewLegacyHttpClient(cfg config.LegacyConfig) *http.Client {
|
||||
transCfg := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
//nolint:gosec
|
||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||
},
|
||||
}
|
||||
|
||||
var expiredTime time.Time
|
||||
|
||||
if cfg.Token != "" {
|
||||
expiredTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
return &http.Client{
|
||||
Transport: &transportLegacy{
|
||||
base: transCfg,
|
||||
username: url.QueryEscape(cfg.Username),
|
||||
password: url.QueryEscape(cfg.Password),
|
||||
retries: cfg.Retries,
|
||||
token: cfg.Token,
|
||||
decortURL: cfg.DecortURL,
|
||||
expiryTime: expiredTime,
|
||||
},
|
||||
|
||||
Timeout: cfg.Timeout.Get(),
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type transportLegacy struct {
|
||||
base http.RoundTripper
|
||||
username string
|
||||
password string
|
||||
retries uint64
|
||||
token string
|
||||
decortURL string
|
||||
expiryTime time.Time
|
||||
}
|
||||
|
||||
func (t *transportLegacy) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
if t.token == "" || time.Now().After(t.expiryTime) {
|
||||
body := fmt.Sprintf("username=%s&password=%s", t.username, t.password)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
req, _ := http.NewRequestWithContext(request.Context(), "POST", t.decortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to get token: %w", err)
|
||||
}
|
||||
|
||||
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("unable to get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
token := string(tokenBytes)
|
||||
t.token = token
|
||||
t.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
tokenValue := fmt.Sprintf("&authkey=%s", t.token)
|
||||
tokenReader := strings.NewReader(tokenValue)
|
||||
|
||||
newBody := io.MultiReader(request.Body, tokenReader)
|
||||
|
||||
req, _ := http.NewRequestWithContext(request.Context(), request.Method, request.URL.String(), newBody)
|
||||
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
var resp *http.Response
|
||||
var err error
|
||||
for i := uint64(0); i < t.retries; i++ {
|
||||
resp, err = t.base.RoundTrip(req)
|
||||
if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, nil
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type transport struct {
|
||||
base http.RoundTripper
|
||||
retries uint64
|
||||
clientID string
|
||||
clientSecret string
|
||||
token string
|
||||
ssoURL string
|
||||
expiryTime time.Time
|
||||
}
|
||||
|
||||
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
if t.token == "" || time.Now().After(t.expiryTime) {
|
||||
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", t.clientID, t.clientSecret)
|
||||
bodyReader := strings.NewReader(body)
|
||||
|
||||
t.ssoURL = strings.TrimSuffix(t.ssoURL, "/")
|
||||
|
||||
req, _ := http.NewRequestWithContext(req.Context(), "POST", t.ssoURL+"/v1/oauth/access_token", bodyReader)
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot get token: %w", err)
|
||||
}
|
||||
|
||||
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||
}
|
||||
|
||||
token := string(tokenBytes)
|
||||
|
||||
t.token = token
|
||||
t.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Add("Authorization", "bearer "+t.token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
var resp *http.Response
|
||||
var err error
|
||||
for i := uint64(0); i < t.retries; i++ {
|
||||
resp, err = t.base.RoundTrip(req)
|
||||
if err == nil {
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, nil
|
||||
}
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
}
|
||||
//logrus.Errorf("Could not execute request: %v. Retrying %d/%d", err, i+1, t.retries)
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
114
legacy-client.go
114
legacy-client.go
@@ -1,23 +1,31 @@
|
||||
package decortsdk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"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/client"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||
)
|
||||
|
||||
// Legacy HTTP-client for platform
|
||||
type LegacyDecortClient struct {
|
||||
decortURL string
|
||||
client *http.Client
|
||||
decortURL string
|
||||
client *http.Client
|
||||
cfg config.LegacyConfig
|
||||
expiryTime time.Time
|
||||
mutex *sync.Mutex
|
||||
}
|
||||
|
||||
// Legacy client builder
|
||||
@@ -26,9 +34,25 @@ func NewLegacy(cfg config.LegacyConfig) *LegacyDecortClient {
|
||||
cfg.Retries = 5
|
||||
}
|
||||
|
||||
var expiryTime time.Time
|
||||
|
||||
if cfg.Token != "" {
|
||||
expiryTime = time.Now().AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
return &LegacyDecortClient{
|
||||
decortURL: cfg.DecortURL,
|
||||
client: client.NewLegacyHttpClient(cfg),
|
||||
client: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
//nolint:gosec
|
||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||
},
|
||||
},
|
||||
},
|
||||
cfg: cfg,
|
||||
expiryTime: expiryTime,
|
||||
mutex: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,13 +73,18 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body := strings.NewReader(values.Encode())
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := ldc.client.Do(req)
|
||||
resp, err := ldc.do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -72,3 +101,76 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
|
||||
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ldc *LegacyDecortClient) do(req *http.Request) (*http.Response, error) {
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
// var resp *http.Response
|
||||
// var err error
|
||||
buf, _ := io.ReadAll(req.Body)
|
||||
|
||||
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||
// req = req.Clone(req.Context())
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
resp, err := ldc.client.Do(req)
|
||||
req.Close = true
|
||||
if err != nil || resp == nil {
|
||||
if strings.Contains(err.Error(), "connection reset by peer") || errors.Is(err, io.EOF) {
|
||||
for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||
time.Sleep(5 * time.Second)
|
||||
resp, err = ldc.client.Do(req)
|
||||
if strings.Contains(err.Error(), "connection reset by peer") || errors.Is(err, io.EOF) {
|
||||
continue
|
||||
} else if err == nil {
|
||||
break
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if resp.StatusCode == 200 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("%s", respBytes)
|
||||
resp.Body.Close()
|
||||
// }
|
||||
|
||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ type DiskDelRequest struct {
|
||||
|
||||
// False if disk is to be deleted to recycle bin
|
||||
// Required: true
|
||||
Permanently bool `url:"permanently" json:"permanently" validate:"required"`
|
||||
Permanently bool `url:"permanently" json:"permanently"`
|
||||
}
|
||||
|
||||
// DiskDel delete disk and detach from compute
|
||||
|
||||
@@ -32,6 +32,14 @@ type ListUnattachedRequest struct {
|
||||
// Required: false
|
||||
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||
|
||||
// Find by sep ID
|
||||
// Required: false
|
||||
SEPID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||
|
||||
// Find by pool name
|
||||
// Required: false
|
||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
|
||||
@@ -36,7 +36,7 @@ type CreateInRGRequest struct {
|
||||
|
||||
// Number of pre created reservations
|
||||
// Required: false
|
||||
PreReservationsNum uint `url:"preReservationsNum,omitempty" json:"preReservationsNum,omitempty"`
|
||||
PreReservationsNum uint64 `url:"preReservationsNum,omitempty" json:"preReservationsNum,omitempty"`
|
||||
}
|
||||
|
||||
// CreateInRG creates VINS in resource group level
|
||||
|
||||
@@ -397,9 +397,11 @@ type NATConfig struct {
|
||||
Network string `json:"network"`
|
||||
|
||||
// List NAT rules
|
||||
Rules ListNATRules `json:"rules"`
|
||||
Rules ListNATRulesConfig `json:"rules"`
|
||||
}
|
||||
|
||||
type ListNATRulesConfig []ItemNATRule
|
||||
|
||||
// Main information about GW
|
||||
type RecordGW struct {
|
||||
// CKey
|
||||
@@ -570,9 +572,6 @@ type RecordVINS struct {
|
||||
// Main information about VNF device
|
||||
VNFDev RecordVNFDev `json:"VNFDev"`
|
||||
|
||||
// CKey
|
||||
CKey string `json:"_ckey"`
|
||||
|
||||
// Account ID
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
@@ -582,12 +581,24 @@ type RecordVINS struct {
|
||||
// List of VINS computes
|
||||
Computes ListVINSComputes `json:"computes"`
|
||||
|
||||
// Created by
|
||||
CreatedBy string `json:"createdBy"`
|
||||
|
||||
// Created time
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
|
||||
// Default GW
|
||||
DefaultGW string `json:"defaultGW"`
|
||||
|
||||
// Default QOS
|
||||
DefaultQOS QOS `json:"defaultQos"`
|
||||
|
||||
// Deleted by
|
||||
DeletedBy string `json:"deletedBy"`
|
||||
|
||||
// Deleted time
|
||||
DeletedTime uint64 `json:"deletedTime"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ type DiskDelRequest struct {
|
||||
|
||||
// False if disk is to be deleted to recycle bin
|
||||
// Required: true
|
||||
Permanently bool `url:"permanently" json:"permanently" validate:"required"`
|
||||
Permanently bool `url:"permanently" json:"permanently"`
|
||||
|
||||
// Reason for action
|
||||
// Required: false
|
||||
|
||||
@@ -24,10 +24,6 @@ type ListUnattachedRequest struct {
|
||||
// Required: false
|
||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||
|
||||
// Find by shared, true or false
|
||||
// Required: false
|
||||
Shared bool `url:"shared,omitempty" json:"shared,omitempty"`
|
||||
|
||||
// Type of the disks
|
||||
// Required: false
|
||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||
@@ -36,6 +32,14 @@ type ListUnattachedRequest struct {
|
||||
// Required: false
|
||||
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||
|
||||
// Find by sep ID
|
||||
// Required: false
|
||||
SEPID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||
|
||||
// Find by pool name
|
||||
// Required: false
|
||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
|
||||
10
pkg/cloudbroker/flipgoup.go
Normal file
10
pkg/cloudbroker/flipgoup.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package cloudbroker
|
||||
|
||||
import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/flipgroup"
|
||||
)
|
||||
|
||||
// Accessing the FLIPGroup method group
|
||||
func (cb *CloudBroker) FLIPGroup() *flipgroup.FLIPGroup {
|
||||
return flipgroup.New(cb.client)
|
||||
}
|
||||
44
pkg/cloudbroker/flipgroup/compute_add.go
Normal file
44
pkg/cloudbroker/flipgroup/compute_add.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for add compute instance
|
||||
type ComputeAddRequest struct {
|
||||
// ID of the Floating IP group to add compute instance to
|
||||
// Required: true
|
||||
FLIPGroupID uint64 `url:"flipgroupId" json:"flipgroupId" validate:"required"`
|
||||
|
||||
// ID of the compute instance to add to this group
|
||||
// Required: true
|
||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||
}
|
||||
|
||||
// ComputeAdd add compute instance to the Floating IP group
|
||||
func (f FLIPGroup) ComputeAdd(ctx context.Context, req ComputeAddRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/computeAdd"
|
||||
|
||||
res, err := f.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
|
||||
}
|
||||
44
pkg/cloudbroker/flipgroup/compute_remove.go
Normal file
44
pkg/cloudbroker/flipgroup/compute_remove.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for remove compute instance
|
||||
type ComputeRemoveRequest struct {
|
||||
// ID of the Floating IP group to remove compute instance from
|
||||
// Required: true
|
||||
FLIPGroupID uint64 `url:"flipgroupId" json:"flipgroupId" validate:"required"`
|
||||
|
||||
// ID of the compute instance to remove
|
||||
// Required: true
|
||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||
}
|
||||
|
||||
// ComputeRemove remove compute instance from the Floating IP group
|
||||
func (f FLIPGroup) ComputeRemove(ctx context.Context, req ComputeRemoveRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/computeRemove"
|
||||
|
||||
res, err := f.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
|
||||
}
|
||||
71
pkg/cloudbroker/flipgroup/create.go
Normal file
71
pkg/cloudbroker/flipgroup/create.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for create FLIPGroup
|
||||
type CreateRequest struct {
|
||||
// Account ID
|
||||
// Required: true
|
||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||
|
||||
// FLIPGroup name
|
||||
// Required: true
|
||||
Name string `url:"name" json:"name" validate:"required"`
|
||||
|
||||
// Network type
|
||||
// Should be one of:
|
||||
// - EXTNET
|
||||
// - VINS
|
||||
// Required: true
|
||||
NetType string `url:"netType" json:"netType" validate:"computeNetType"`
|
||||
|
||||
// ID of external network or VINS
|
||||
// Required: true
|
||||
NetID uint64 `url:"netId" json:"netId" validate:"required"`
|
||||
|
||||
// Type of client
|
||||
// - 'compute'
|
||||
// - 'vins' (will be later)
|
||||
// Required: true
|
||||
ClientType string `url:"clientType" json:"clientType" validate:"flipgroupClientType"`
|
||||
|
||||
// IP address to associate with this group. If empty, the platform will autoselect IP address
|
||||
// Required: false
|
||||
IP string `url:"ip,omitempty" json:"ip,omitempty"`
|
||||
|
||||
// Text description of this FLIPGorup instance
|
||||
// Required: false
|
||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||
}
|
||||
|
||||
// Create method will create a new FLIPGorup in the specified Account
|
||||
func (f FLIPGroup) Create(ctx context.Context, req CreateRequest) (*RecordFLIPGroupCreated, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/create"
|
||||
|
||||
res, err := f.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := RecordFLIPGroupCreated{}
|
||||
|
||||
err = json.Unmarshal(res, &info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
40
pkg/cloudbroker/flipgroup/delete.go
Normal file
40
pkg/cloudbroker/flipgroup/delete.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for delete FLIPGroup
|
||||
type DeleteRequest struct {
|
||||
// FLIPGroup ID
|
||||
// Required: true
|
||||
FLIPGroupID uint64 `url:"flipgroupId" json:"flipgroupId" validate:"required"`
|
||||
}
|
||||
|
||||
// Delete method wil delete Floating IP group
|
||||
func (f FLIPGroup) 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)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/delete"
|
||||
|
||||
res, err := f.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
|
||||
}
|
||||
48
pkg/cloudbroker/flipgroup/edit.go
Normal file
48
pkg/cloudbroker/flipgroup/edit.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for edit FLIPGroup
|
||||
type EditRequest struct {
|
||||
// FLIPGroup ID
|
||||
// Required: true
|
||||
FLIPGroupID uint64 `url:"flipgroupId" json:"flipgroupId" validate:"required"`
|
||||
|
||||
// FLIPGroup name
|
||||
// Required: false
|
||||
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||
|
||||
// FLIPGroup description
|
||||
// Required: false
|
||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||
}
|
||||
|
||||
// Edit edits FLIPGroup fields
|
||||
func (f FLIPGroup) Edit(ctx context.Context, req EditRequest) (bool, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return false, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/edit"
|
||||
|
||||
res, err := f.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
|
||||
}
|
||||
18
pkg/cloudbroker/flipgroup/flipgroup.go
Normal file
18
pkg/cloudbroker/flipgroup/flipgroup.go
Normal file
@@ -0,0 +1,18 @@
|
||||
// API to manage FLIPGroup instances
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||
)
|
||||
|
||||
// Structure for creating request to FLIPGroup
|
||||
type FLIPGroup struct {
|
||||
client interfaces.Caller
|
||||
}
|
||||
|
||||
// Builder for FLIPGroup endpoints
|
||||
func New(client interfaces.Caller) *FLIPGroup {
|
||||
return &FLIPGroup{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
42
pkg/cloudbroker/flipgroup/get.go
Normal file
42
pkg/cloudbroker/flipgroup/get.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get information about FLIPGroup
|
||||
type GetRequest struct {
|
||||
// FLIPGroup ID
|
||||
// Required: true
|
||||
FLIPGroupID uint64 `url:"flipgroupId" json:"flipgroupId" validate:"required"`
|
||||
}
|
||||
|
||||
// Get gets details of the specified Floating IP group
|
||||
func (f FLIPGroup) Get(ctx context.Context, req GetRequest) (*RecordFLIPGroup, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/flipgroup/get"
|
||||
|
||||
res, err := f.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := RecordFLIPGroup{}
|
||||
|
||||
err = json.Unmarshal(res, &info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
65
pkg/cloudbroker/flipgroup/list.go
Normal file
65
pkg/cloudbroker/flipgroup/list.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Request struct for get list FLIPGroup available to the current user
|
||||
type ListRequest struct {
|
||||
// Find by name
|
||||
// Required: false
|
||||
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||
|
||||
// Find by vinsId
|
||||
// Required: false
|
||||
VINSID uint64 `url:"vinsId,omitempty" json:"vinsId,omitempty"`
|
||||
|
||||
// Find by VINS name
|
||||
// Required: false
|
||||
VINSName string `url:"vinsName,omitempty" json:"vinsName,omitempty"`
|
||||
|
||||
// Find by extnetId
|
||||
// Required: false
|
||||
ExtNetID uint64 `url:"extnetId,omitempty" json:"extnetId,omitempty"`
|
||||
|
||||
// Find by IP
|
||||
// Reuqired: false
|
||||
ByIP string `url:"byIp,omitempty" json:"byIp,omitempty"`
|
||||
|
||||
// Find by resource group ID
|
||||
// Reuqired: false
|
||||
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||
|
||||
// Find by id
|
||||
// Required: false
|
||||
ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
|
||||
// Page size
|
||||
// Required: false
|
||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// List gets list FLIPGroup managed cluster instances available to the current user
|
||||
func (f FLIPGroup) List(ctx context.Context, req ListRequest) (*ListFLIPGroups, error) {
|
||||
url := "/cloudbroker/flipgroup/list"
|
||||
|
||||
res, err := f.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := ListFLIPGroups{}
|
||||
|
||||
err = json.Unmarshal(res, &list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &list, nil
|
||||
}
|
||||
169
pkg/cloudbroker/flipgroup/models.go
Normal file
169
pkg/cloudbroker/flipgroup/models.go
Normal file
@@ -0,0 +1,169 @@
|
||||
package flipgroup
|
||||
|
||||
// Main information about FLIPGroup
|
||||
type RecordFLIPGroupCreated struct {
|
||||
// Default GW
|
||||
DefaultGW string `json:"defaultGW"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// IP
|
||||
IP string `json:"ip"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Network mask
|
||||
NetMask uint64 `json:"netmask"`
|
||||
}
|
||||
|
||||
type RecordFLIPGroup struct {
|
||||
// Account ID
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
// Account name
|
||||
AccountName string `json:"accountName"`
|
||||
|
||||
// List of client IDs
|
||||
ClientIDs []uint64 `json:"clientIds"`
|
||||
|
||||
// Client names
|
||||
ClientNames []string `json:"clientNames"`
|
||||
|
||||
// Client type
|
||||
ClientType string `json:"clientType"`
|
||||
|
||||
// Connection ID
|
||||
ConnID uint64 `json:"connId"`
|
||||
|
||||
// Connection type
|
||||
ConnType string `json:"connType"`
|
||||
|
||||
// Created by
|
||||
CreatedBy string `json:"createdBy"`
|
||||
|
||||
// Created time
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
|
||||
// Default GW
|
||||
DefaultGW string `json:"defaultGW"`
|
||||
|
||||
// Deleted by
|
||||
DeletedBy string `json:"deletedBy"`
|
||||
|
||||
// Deleted time
|
||||
DeletedTime uint64 `json:"deletedTime"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// IP
|
||||
IP string `json:"ip"`
|
||||
|
||||
// Milestones
|
||||
Milestones uint64 `json:"milestones"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Network ID
|
||||
NetID uint64 `json:"netId"`
|
||||
|
||||
// Network type
|
||||
NetType string `json:"netType"`
|
||||
|
||||
// Network
|
||||
Network string `json:"network"`
|
||||
|
||||
// Resource group ID
|
||||
RGID uint64 `json:"rgId"`
|
||||
|
||||
// Resource group name
|
||||
RGName string `json:"rgName"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
// Updated by
|
||||
UpdatedBy string `json:"updatedBy"`
|
||||
|
||||
// Updated time
|
||||
UpdatedTime uint64 `json:"updatedTime"`
|
||||
}
|
||||
|
||||
// Detailed information about FLIPGroup
|
||||
type ItemFLIPGroup struct {
|
||||
// CKey
|
||||
CKey string `json:"_ckey"`
|
||||
|
||||
// Meta
|
||||
Meta []interface{} `json:"_meta"`
|
||||
|
||||
// Account ID
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
// List of client IDs
|
||||
ClientIDs []uint64 `json:"clientIds"`
|
||||
|
||||
// Client type
|
||||
ClientType string `json:"clientType"`
|
||||
|
||||
// Connection ID
|
||||
ConnID uint64 `json:"connId"`
|
||||
|
||||
// Connection type
|
||||
ConnType string `json:"connType"`
|
||||
|
||||
// Default GW
|
||||
DefaultGW string `json:"defaultGW"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// IP
|
||||
IP string `json:"ip"`
|
||||
|
||||
// Milestones
|
||||
Milestones uint64 `json:"milestones"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Network ID
|
||||
NetID uint64 `json:"netId"`
|
||||
|
||||
// Network type
|
||||
NetType string `json:"netType"`
|
||||
|
||||
// NetMask
|
||||
NetMask uint64 `json:"netmask"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// List of FLIPGroup
|
||||
type ListFLIPGroups struct {
|
||||
Data []ItemFLIPGroup `json:"data"`
|
||||
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
}
|
||||
43
pkg/cloudbroker/flipgroup/serialize.go
Normal file
43
pkg/cloudbroker/flipgroup/serialize.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package flipgroup
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
|
||||
)
|
||||
|
||||
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||
//
|
||||
// In order to serialize with indent make sure to follow these guidelines:
|
||||
// - First argument -> prefix
|
||||
// - Second argument -> indent
|
||||
func (lfg ListFLIPGroups) Serialize(params ...string) (serialization.Serialized, error) {
|
||||
if len(lfg.Data) == 0 {
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
if len(params) > 1 {
|
||||
prefix := params[0]
|
||||
indent := params[1]
|
||||
|
||||
return json.MarshalIndent(lfg, prefix, indent)
|
||||
}
|
||||
|
||||
return json.Marshal(lfg)
|
||||
}
|
||||
|
||||
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||
//
|
||||
// In order to serialize with indent make sure to follow these guidelines:
|
||||
// - First argument -> prefix
|
||||
// - Second argument -> indent
|
||||
func (ifg ItemFLIPGroup) Serialize(params ...string) (serialization.Serialized, error) {
|
||||
if len(params) > 1 {
|
||||
prefix := params[0]
|
||||
indent := params[1]
|
||||
|
||||
return json.MarshalIndent(ifg, prefix, indent)
|
||||
}
|
||||
|
||||
return json.Marshal(ifg)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package grid
|
||||
|
||||
// FilterByID returns ListGrids with specified ID.
|
||||
func (lg ListGrids) FilterByID(id uint64) ListGrids {
|
||||
predicate := func(rg RecordGrid) bool {
|
||||
predicate := func(rg ItemGridList) bool {
|
||||
return rg.ID == id
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ func (lg ListGrids) FilterByID(id uint64) ListGrids {
|
||||
|
||||
// FilterByName returns ListGrids with specified Name.
|
||||
func (lg ListGrids) FilterByName(name string) ListGrids {
|
||||
predicate := func(rg RecordGrid) bool {
|
||||
predicate := func(rg ItemGridList) bool {
|
||||
return rg.Name == name
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ func (lg ListGrids) FilterByName(name string) ListGrids {
|
||||
|
||||
// FilterByLocationCode returns ListGrids with specified LocationCode.
|
||||
func (lg ListGrids) FilterByLocationCode(locationCode string) ListGrids {
|
||||
predicate := func(rg RecordGrid) bool {
|
||||
predicate := func(rg ItemGridList) bool {
|
||||
return rg.LocationCode == locationCode
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func (lg ListGrids) FilterByLocationCode(locationCode string) ListGrids {
|
||||
}
|
||||
|
||||
// FilterFunc allows filtering ListGrids based on a user-specified predicate.
|
||||
func (lg ListGrids) FilterFunc(predicate func(RecordGrid) bool) ListGrids {
|
||||
func (lg ListGrids) FilterFunc(predicate func(ItemGridList) bool) ListGrids {
|
||||
var result ListGrids
|
||||
|
||||
for _, item := range lg.Data {
|
||||
@@ -44,9 +44,9 @@ func (lg ListGrids) FilterFunc(predicate func(RecordGrid) bool) ListGrids {
|
||||
|
||||
// FindOne returns first found RecordGrid.
|
||||
// If none was found, returns an empty struct.
|
||||
func (lg ListGrids) FindOne() RecordGrid {
|
||||
func (lg ListGrids) FindOne() ItemGridList {
|
||||
if len(lg.Data) == 0 {
|
||||
return RecordGrid{}
|
||||
return ItemGridList{}
|
||||
}
|
||||
|
||||
return lg.Data[0]
|
||||
|
||||
@@ -3,7 +3,7 @@ package grid
|
||||
import "testing"
|
||||
|
||||
var grids = ListGrids{
|
||||
Data: []RecordGrid{
|
||||
Data: []ItemGridList{
|
||||
{
|
||||
Resources: Resources{
|
||||
Current: RecordResource{
|
||||
@@ -123,7 +123,7 @@ func TestFilterByLocationCode(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFilterFunc(t *testing.T) {
|
||||
actual := grids.FilterFunc(func(rg RecordGrid) bool {
|
||||
actual := grids.FilterFunc(func(rg ItemGridList) bool {
|
||||
return rg.GID == 777
|
||||
}).
|
||||
FindOne()
|
||||
|
||||
@@ -18,7 +18,7 @@ type RecordResourcesConsumption struct {
|
||||
Reserved RecordResource `json:"Reserved"`
|
||||
|
||||
// GID
|
||||
GID uint64 `json:"gid"`
|
||||
GID uint64 `json:"id"`
|
||||
}
|
||||
|
||||
type ListResourceConsumption struct {
|
||||
@@ -67,6 +67,27 @@ type DiskUsage struct {
|
||||
|
||||
// Detailed information about grid
|
||||
type RecordGrid struct {
|
||||
// Flag
|
||||
Flag string `json:"flag"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// Location code
|
||||
LocationCode string `json:"locationCode"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Information about grid
|
||||
type ItemGridList struct {
|
||||
// Resource information
|
||||
Resources Resources `json:"Resources"`
|
||||
|
||||
@@ -92,7 +113,7 @@ type RecordGrid struct {
|
||||
// List Grids
|
||||
type ListGrids struct {
|
||||
//Data
|
||||
Data []RecordGrid `json:"data"`
|
||||
Data []ItemGridList `json:"data"`
|
||||
|
||||
// Entry count
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
|
||||
@@ -20,7 +20,7 @@ type DeleteRequest struct {
|
||||
|
||||
// Whether to completely delete the image
|
||||
// Required: false
|
||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
||||
Permanently bool `url:"permanently" json:"permanently"`
|
||||
}
|
||||
|
||||
// Delete deletes image by ID
|
||||
|
||||
@@ -162,7 +162,7 @@ type ListACL []ACL
|
||||
// History information
|
||||
type History struct {
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
GUID GUID `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
@@ -171,6 +171,20 @@ type History struct {
|
||||
Timestamp uint64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type GUID string
|
||||
|
||||
func (r *GUID) UnmarshalJSON(b []byte) error {
|
||||
|
||||
if b[0] == '"' {
|
||||
*r = GUID(string(b[1:len(b)-1]))
|
||||
return nil
|
||||
}
|
||||
|
||||
*r = GUID(string(b))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// List history
|
||||
type ListHistory []History
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ package k8ci
|
||||
// FilterByID returns ListK8CI with specified ID.
|
||||
func (lkc ListK8CI) FilterByID(id uint64) ListK8CI {
|
||||
predicate := func(ikc ItemK8CI) bool {
|
||||
return ikc.RecordK8CI.ID == id
|
||||
return ikc.RecordK8CIList.ID == id
|
||||
}
|
||||
|
||||
return lkc.FilterFunc(predicate)
|
||||
@@ -12,7 +12,7 @@ func (lkc ListK8CI) FilterByID(id uint64) ListK8CI {
|
||||
// FilterByName returns ListK8CI with specified Name.
|
||||
func (lkc ListK8CI) FilterByName(name string) ListK8CI {
|
||||
predicate := func(ikc ItemK8CI) bool {
|
||||
return ikc.RecordK8CI.Name == name
|
||||
return ikc.RecordK8CIList.Name == name
|
||||
}
|
||||
|
||||
return lkc.FilterFunc(predicate)
|
||||
|
||||
@@ -6,7 +6,7 @@ var k8ciItems = ListK8CI{
|
||||
Data: []ItemK8CI{
|
||||
{
|
||||
CreatedTime: 123902139,
|
||||
RecordK8CI: RecordK8CI{
|
||||
RecordK8CIList: RecordK8CIList{
|
||||
Description: "",
|
||||
GID: 0,
|
||||
GUID: 1,
|
||||
@@ -17,7 +17,7 @@ var k8ciItems = ListK8CI{
|
||||
MaxMasterCount: 2,
|
||||
MaxWorkerCount: 3,
|
||||
Name: "purple_snake",
|
||||
SharedWith: []interface{}{},
|
||||
SharedWith: []uint64{},
|
||||
Status: "ENABLED",
|
||||
Version: "1",
|
||||
WorkerDriver: "KVM_X86",
|
||||
@@ -26,7 +26,7 @@ var k8ciItems = ListK8CI{
|
||||
},
|
||||
{
|
||||
CreatedTime: 123902232,
|
||||
RecordK8CI: RecordK8CI{
|
||||
RecordK8CIList: RecordK8CIList{
|
||||
Description: "",
|
||||
GID: 0,
|
||||
GUID: 2,
|
||||
@@ -37,7 +37,7 @@ var k8ciItems = ListK8CI{
|
||||
MaxMasterCount: 3,
|
||||
MaxWorkerCount: 5,
|
||||
Name: "green_giant",
|
||||
SharedWith: []interface{}{},
|
||||
SharedWith: []uint64{},
|
||||
Status: "DISABLED",
|
||||
Version: "2",
|
||||
WorkerDriver: "KVM_X86",
|
||||
@@ -46,7 +46,7 @@ var k8ciItems = ListK8CI{
|
||||
},
|
||||
{
|
||||
CreatedTime: 123902335,
|
||||
RecordK8CI: RecordK8CI{
|
||||
RecordK8CIList: RecordK8CIList{
|
||||
Description: "",
|
||||
GID: 0,
|
||||
GUID: 3,
|
||||
@@ -57,7 +57,7 @@ var k8ciItems = ListK8CI{
|
||||
MaxMasterCount: 5,
|
||||
MaxWorkerCount: 9,
|
||||
Name: "magenta_cloud",
|
||||
SharedWith: []interface{}{},
|
||||
SharedWith: []uint64{},
|
||||
Status: "ENABLED",
|
||||
Version: "3",
|
||||
WorkerDriver: "KVM_X86",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package k8ci
|
||||
|
||||
// Main information about K8CI
|
||||
// Main information about K8CI in List
|
||||
type ItemK8CI struct {
|
||||
// Created time
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
// Detailed information about K8CI
|
||||
RecordK8CI
|
||||
RecordK8CIList
|
||||
}
|
||||
|
||||
// List K8CI
|
||||
@@ -17,7 +17,55 @@ type ListK8CI struct {
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
}
|
||||
|
||||
// Detailed information about K8CI
|
||||
// Detailed information about K8CI in List
|
||||
type RecordK8CIList struct {
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// Load balancer image ID
|
||||
LBImageID uint64 `json:"lbImageId"`
|
||||
|
||||
// Master driver
|
||||
MasterDriver string `json:"masterDriver"`
|
||||
|
||||
// Master image ID
|
||||
MasterImageID uint64 `json:"masterImageId"`
|
||||
|
||||
// Max master count
|
||||
MaxMasterCount uint64 `json:"maxMasterCount"`
|
||||
|
||||
// Max worker count
|
||||
MaxWorkerCount uint64 `json:"maxWorkerCount"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Shared with
|
||||
SharedWith []uint64 `json:"sharedWith"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
// Version
|
||||
Version string `json:"version"`
|
||||
|
||||
// Worker driver
|
||||
WorkerDriver string `json:"workerDriver"`
|
||||
|
||||
// Worker image ID
|
||||
WorkerImageID uint64 `json:"workerImageId"`
|
||||
}
|
||||
|
||||
// Detailed information about K8CI
|
||||
type RecordK8CI struct {
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
@@ -52,8 +100,11 @@ type RecordK8CI struct {
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
//NetworkPlugins
|
||||
NetworkPlugins []string `json:"networkPlugins"`
|
||||
|
||||
// Shared with
|
||||
SharedWith []interface{} `json:"sharedWith"`
|
||||
SharedWith []uint64 `json:"sharedWith"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
@@ -29,7 +29,7 @@ type CreateRequest struct {
|
||||
|
||||
// Start now Load balancer
|
||||
// Required: false
|
||||
Start bool `url:"start" json:"start" validate:"required"`
|
||||
Start bool `url:"start" json:"start"`
|
||||
|
||||
// Text description of this load balancer
|
||||
// Required: false
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
// FilterByID returns ListLB with specified ID.
|
||||
func (ll ListLB) FilterByID(id uint64) ListLB {
|
||||
predicate := func(rlb RecordLB) bool {
|
||||
predicate := func(rlb ItemLBList) bool {
|
||||
return rlb.ID == id
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func (ll ListLB) FilterByID(id uint64) ListLB {
|
||||
|
||||
// FilterByName returns ListLB with specified Name.
|
||||
func (ll ListLB) FilterByName(name string) ListLB {
|
||||
predicate := func(rlb RecordLB) bool {
|
||||
predicate := func(rlb ItemLBList) bool {
|
||||
return rlb.Name == name
|
||||
}
|
||||
|
||||
@@ -27,22 +27,13 @@ func (ll ListLB) FilterByName(name string) ListLB {
|
||||
|
||||
// FilterByExtNetID returns ListLB with specified ExtNetID.
|
||||
func (ll ListLB) FilterByExtNetID(extNetID uint64) ListLB {
|
||||
predicate := func(rlb RecordLB) bool {
|
||||
predicate := func(rlb ItemLBList) bool {
|
||||
return rlb.ExtNetID == extNetID
|
||||
}
|
||||
|
||||
return ll.FilterFunc(predicate)
|
||||
}
|
||||
|
||||
// FilterByImageID returns ListLB with specified ImageID.
|
||||
func (ll ListLB) FilterByImageID(imageID uint64) ListLB {
|
||||
predicate := func(rlb RecordLB) bool {
|
||||
return rlb.ImageID == imageID
|
||||
}
|
||||
|
||||
return ll.FilterFunc(predicate)
|
||||
}
|
||||
|
||||
// FilterByK8SID returns ListLB used by specified K8S cluster.
|
||||
func (ll ListLB) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient interfaces.Caller) (*ListLB, error) {
|
||||
caller := k8s.New(decortClient)
|
||||
@@ -56,7 +47,7 @@ func (ll ListLB) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient i
|
||||
return nil, err
|
||||
}
|
||||
|
||||
predicate := func(rlb RecordLB) bool {
|
||||
predicate := func(rlb ItemLBList) bool {
|
||||
return cluster.LBID == rlb.ID
|
||||
}
|
||||
|
||||
@@ -66,7 +57,7 @@ func (ll ListLB) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient i
|
||||
}
|
||||
|
||||
// FilterFunc allows filtering ListLB based on a user-specified predicate.
|
||||
func (ll ListLB) FilterFunc(predicate func(RecordLB) bool) ListLB {
|
||||
func (ll ListLB) FilterFunc(predicate func(ItemLBList) bool) ListLB {
|
||||
var result ListLB
|
||||
|
||||
for _, item := range ll.Data {
|
||||
@@ -82,9 +73,9 @@ func (ll ListLB) FilterFunc(predicate func(RecordLB) bool) ListLB {
|
||||
|
||||
// FindOne returns first found RecordLB
|
||||
// If none was found, returns an empty struct.
|
||||
func (ll ListLB) FindOne() RecordLB {
|
||||
func (ll ListLB) FindOne() ItemLBList {
|
||||
if len(ll.Data) == 0 {
|
||||
return RecordLB{}
|
||||
return ItemLBList{}
|
||||
}
|
||||
|
||||
return ll.Data[0]
|
||||
|
||||
@@ -3,11 +3,9 @@ package lb
|
||||
import "testing"
|
||||
|
||||
var lbs = ListLB{
|
||||
Data: []RecordLB{
|
||||
Data: []ItemLBList{
|
||||
{
|
||||
HAMode: true,
|
||||
CKey: "",
|
||||
Meta: []interface{}{},
|
||||
ACL: []interface{}{},
|
||||
Backends: []ItemBackend{},
|
||||
CreatedBy: "test_user_1",
|
||||
@@ -22,7 +20,6 @@ var lbs = ListLB{
|
||||
GID: 212,
|
||||
GUID: 1,
|
||||
ID: 1,
|
||||
ImageID: 2121,
|
||||
Milestones: 129000,
|
||||
Name: "k8s-lb-test-1",
|
||||
PrimaryNode: Node{},
|
||||
@@ -37,8 +34,6 @@ var lbs = ListLB{
|
||||
},
|
||||
{
|
||||
HAMode: false,
|
||||
CKey: "",
|
||||
Meta: []interface{}{},
|
||||
ACL: []interface{}{},
|
||||
Backends: []ItemBackend{},
|
||||
CreatedBy: "test_user_2",
|
||||
@@ -53,7 +48,6 @@ var lbs = ListLB{
|
||||
GID: 212,
|
||||
GUID: 2,
|
||||
ID: 2,
|
||||
ImageID: 2129,
|
||||
Milestones: 129013,
|
||||
Name: "k8s-lb-test-2",
|
||||
PrimaryNode: Node{},
|
||||
@@ -68,8 +62,6 @@ var lbs = ListLB{
|
||||
},
|
||||
{
|
||||
HAMode: true,
|
||||
CKey: "",
|
||||
Meta: []interface{}{},
|
||||
ACL: []interface{}{},
|
||||
Backends: []ItemBackend{},
|
||||
CreatedBy: "te2t_user_3",
|
||||
@@ -84,7 +76,6 @@ var lbs = ListLB{
|
||||
GID: 212,
|
||||
GUID: 3,
|
||||
ID: 3,
|
||||
ImageID: 2139,
|
||||
Milestones: 129025,
|
||||
Name: "k8s-lb-test-3",
|
||||
PrimaryNode: Node{},
|
||||
@@ -125,16 +116,8 @@ func TestFilterByExtNetID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterByImageID(t *testing.T) {
|
||||
actual := lbs.FilterByImageID(2139).FindOne()
|
||||
|
||||
if actual.ImageID != 2139 {
|
||||
t.Fatal("expected ImageID 2139, found: ", actual.ImageID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterFunc(t *testing.T) {
|
||||
actual := lbs.FilterFunc(func(rl RecordLB) bool {
|
||||
actual := lbs.FilterFunc(func(rl ItemLBList) bool {
|
||||
return rl.Status == "DISABLED"
|
||||
})
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ type Node struct {
|
||||
// List of load balancers
|
||||
type ListLB struct {
|
||||
// Data
|
||||
Data []RecordLB `json:"data"`
|
||||
Data []ItemLBList `json:"data"`
|
||||
|
||||
// Entry count
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
@@ -159,6 +159,69 @@ type RecordLB struct {
|
||||
// List of load balancer backends
|
||||
Backends ListBackends `json:"backends"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// DPAPI password
|
||||
DPAPIPassword string `json:"dpApiPassword"`
|
||||
|
||||
// DPAPI user
|
||||
DPAPIUser string `json:"dpApiUser"`
|
||||
|
||||
// External network ID
|
||||
ExtNetID uint64 `json:"extnetId"`
|
||||
|
||||
// List of load balancer frontends
|
||||
Frontends ListFrontends `json:"frontends"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// Image ID
|
||||
ImageID uint64 `json:"imageId"`
|
||||
|
||||
// Milestones
|
||||
Milestones uint64 `json:"milestones"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Primary node
|
||||
PrimaryNode Node `json:"primaryNode"`
|
||||
|
||||
// Resource group ID
|
||||
RGID uint64 `json:"rgId"`
|
||||
|
||||
// Secondary node
|
||||
SecondaryNode Node `json:"secondaryNode"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
// Tech status
|
||||
TechStatus string `json:"techStatus"`
|
||||
|
||||
// VINS ID
|
||||
VINSID uint64 `json:"vinsId"`
|
||||
}
|
||||
|
||||
// Detailed information about load balancer in List
|
||||
type ItemLBList struct {
|
||||
// HAMode
|
||||
HAMode bool `json:"HAmode"`
|
||||
|
||||
// Access Control List
|
||||
ACL []interface{} `json:"acl"`
|
||||
|
||||
// List of load balancer backends
|
||||
Backends ListBackends `json:"backends"`
|
||||
|
||||
// Created by
|
||||
CreatedBy string `json:"createdBy"`
|
||||
|
||||
@@ -195,9 +258,6 @@ type RecordLB struct {
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
// Image ID
|
||||
ImageID uint64 `json:"imageId"`
|
||||
|
||||
// Milestones
|
||||
Milestones uint64 `json:"milestones"`
|
||||
|
||||
|
||||
@@ -24,10 +24,31 @@ type Total struct {
|
||||
UsageLimit uint64 `json:"usage_limit"`
|
||||
}
|
||||
|
||||
type ByPool struct {
|
||||
|
||||
// Disk count
|
||||
DiskCount uint64 `json:"disk_count"`
|
||||
|
||||
// Disk usage
|
||||
DiskUsage uint64 `json:"disk_usage"`
|
||||
|
||||
// Snapshot count
|
||||
SnapshotCount uint64 `json:"snapshot_count"`
|
||||
|
||||
// Snapshot usage
|
||||
SnapshotUsage uint64 `json:"snapshot_usage"`
|
||||
|
||||
// Usage
|
||||
Usage uint64 `json:"usage"`
|
||||
|
||||
// Usage limit
|
||||
UsageLimit uint64 `json:"usage_limit"`
|
||||
}
|
||||
|
||||
// Main information about consumption
|
||||
type RecordConsumption struct {
|
||||
// By pool
|
||||
ByPool map[string]interface{} `json:"byPool"`
|
||||
ByPool map[string]ByPool `json:"byPool"`
|
||||
|
||||
// Total resource information
|
||||
Total Total `json:"total"`
|
||||
@@ -70,6 +91,9 @@ type RecordPool struct {
|
||||
|
||||
// List URIs
|
||||
URIs ListURIs `json:"uris"`
|
||||
|
||||
// Usage Limit
|
||||
UsageLimit uint64 `json:"usage_limit"`
|
||||
}
|
||||
|
||||
// SEP config
|
||||
|
||||
10
pkg/cloudbroker/stack.go
Normal file
10
pkg/cloudbroker/stack.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package cloudbroker
|
||||
|
||||
import (
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/stack"
|
||||
)
|
||||
|
||||
// Accessing the Stack method group
|
||||
func (cb *CloudBroker) Stack() *stack.Stack {
|
||||
return stack.New(cb.client)
|
||||
}
|
||||
42
pkg/cloudbroker/stack/get.go
Normal file
42
pkg/cloudbroker/stack/get.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package stack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
// Request struct for get list stack
|
||||
type GetRequest struct {
|
||||
// Find by ID
|
||||
// Required: true
|
||||
StackId uint64 `url:"stackId" json:"stackId" validate:"required"`
|
||||
}
|
||||
|
||||
// Get stack details by ID
|
||||
func (i Stack) Get(ctx context.Context, req GetRequest) (*InfoStack, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
if err != nil {
|
||||
for _, validationError := range validators.GetErrors(err) {
|
||||
return nil, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
|
||||
url := "/cloudbroker/stack/get"
|
||||
|
||||
res, err := i.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := InfoStack{}
|
||||
|
||||
err = json.Unmarshal(res, &info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
53
pkg/cloudbroker/stack/list.go
Normal file
53
pkg/cloudbroker/stack/list.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package stack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Request struct for get list stack
|
||||
type ListRequest struct {
|
||||
// Find by ID
|
||||
// Required: false
|
||||
ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`
|
||||
|
||||
// Find by name
|
||||
// Required: false
|
||||
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||
|
||||
// Find by type
|
||||
// Required: false
|
||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||
|
||||
// Find by status
|
||||
// Required: false
|
||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||
|
||||
// Page number
|
||||
// Required: false
|
||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||
|
||||
// Page size
|
||||
// Required: false
|
||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// ListStacks gets list stack
|
||||
func (i Stack) List(ctx context.Context, req ListRequest) (*ListStacks, error) {
|
||||
url := "/cloudbroker/stack/list"
|
||||
|
||||
res, err := i.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := ListStacks{}
|
||||
|
||||
err = json.Unmarshal(res, &list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &list, nil
|
||||
}
|
||||
164
pkg/cloudbroker/stack/models.go
Normal file
164
pkg/cloudbroker/stack/models.go
Normal file
@@ -0,0 +1,164 @@
|
||||
package stack
|
||||
|
||||
// Main information about stack
|
||||
type InfoStack struct {
|
||||
// CKey
|
||||
Ckey string `json:"_ckey"`
|
||||
|
||||
// Meta
|
||||
Meta []interface{} `json:"_meta"`
|
||||
|
||||
//API URL
|
||||
APIURL string `json:"apiUrl"`
|
||||
|
||||
//API key
|
||||
Apikey string `json:"apikey"`
|
||||
|
||||
// App ID
|
||||
AppID string `json:"appId"`
|
||||
|
||||
// CPU allocation ratio
|
||||
CPUAllocationRatio float64 `json:"cpu_allocation_ratio"`
|
||||
|
||||
// Description
|
||||
Description string `json:"desc"`
|
||||
|
||||
// Descr
|
||||
Descr string `json:"descr"`
|
||||
|
||||
// Drivers
|
||||
Drivers []string `json:"drivers"`
|
||||
|
||||
// Eco
|
||||
Eco interface{} `json:"eco"`
|
||||
|
||||
// Error
|
||||
Error uint64 `json:"error"`
|
||||
|
||||
// Grid ID
|
||||
GID uint64 `json:"gid"`
|
||||
|
||||
// GID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
// List image IDs
|
||||
Images []uint64 `json:"images"`
|
||||
|
||||
// Login
|
||||
Login string `json:"login"`
|
||||
|
||||
// Mem allocation ratio
|
||||
MemAllocationRatio float64 `json:"mem_allocation_ratio"`
|
||||
|
||||
// Name
|
||||
Name string `json:"name"`
|
||||
|
||||
// Packegas
|
||||
Packages Packages `json:"packages"`
|
||||
|
||||
//Password
|
||||
Password string `json:"passwd"`
|
||||
|
||||
// Reference ID
|
||||
ReferenceID string `json:"referenceId"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
// Type
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// List of stacks
|
||||
type ListStacks struct {
|
||||
|
||||
//List
|
||||
Data []InfoStack `json:"data"`
|
||||
|
||||
//Entry count
|
||||
EntryCount uint64 `json:"entryCount"`
|
||||
}
|
||||
|
||||
// Package
|
||||
type Packages struct {
|
||||
|
||||
// LibvirtBin
|
||||
LibvirtBin LibvirtBin `json:"libvirt-bin"`
|
||||
|
||||
// Lvm2Lockd
|
||||
Lvm2Lockd Lvm2Lockd `json:"lvm2-lockd"`
|
||||
|
||||
// OpenvswitchCommon
|
||||
OpenvswitchCommon OpenvswitchCommon `json:"openvswitch-common"`
|
||||
|
||||
// OpenvswitchSwitch
|
||||
OpenvswitchSwitch OpenvswitchSwitch `json:"openvswitch-switch"`
|
||||
|
||||
// QemuSystemX86
|
||||
QemuSystemX86 QemuSystemX86 `json:"qemu-system-x86"`
|
||||
|
||||
// Sanlock
|
||||
Sanlock Sanlock `json:"sanlock"`
|
||||
}
|
||||
|
||||
// LibvirtBin
|
||||
type LibvirtBin struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
|
||||
// Lvm2Lockd
|
||||
type Lvm2Lockd struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
|
||||
// OpenvswitchCommon
|
||||
type OpenvswitchCommon struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
|
||||
// OpenvswitchSwitch
|
||||
type OpenvswitchSwitch struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
|
||||
// QemuSystemX86
|
||||
type QemuSystemX86 struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
|
||||
// Sanlock
|
||||
type Sanlock struct {
|
||||
|
||||
// InstalledSize
|
||||
InstalledSize string `json:"installed_size"`
|
||||
|
||||
// Version
|
||||
Ver string `json:"ver"`
|
||||
}
|
||||
16
pkg/cloudbroker/stack/stack.go
Normal file
16
pkg/cloudbroker/stack/stack.go
Normal file
@@ -0,0 +1,16 @@
|
||||
// Lists all the stack.
|
||||
package stack
|
||||
|
||||
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||
|
||||
// Structure for creating request to stack
|
||||
type Stack struct {
|
||||
client interfaces.Caller
|
||||
}
|
||||
|
||||
// Builder for stack endpoint
|
||||
func New(client interfaces.Caller) *Stack {
|
||||
return &Stack{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,24 @@ package vins
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
// Destination network
|
||||
Destination string `url:"destination" json:"destination" validate:"required"`
|
||||
|
||||
//Destination network mask in 255.255.255.255 format
|
||||
Netmask string `url:"netmask" json:"netmask" validate:"required"`
|
||||
|
||||
//Next hop host, IP address from ViNS ID free IP pool
|
||||
Gateway string `url:"gateway" json:"gateway" validate:"required"`
|
||||
}
|
||||
|
||||
// Request struct for create VINS in account
|
||||
type CreateInAccountRequest struct {
|
||||
// VINS name
|
||||
@@ -34,11 +46,20 @@ type CreateInAccountRequest struct {
|
||||
// Required: false
|
||||
PreReservationsNum uint64 `url:"preReservationsNum,omitempty" json:"preReservationsNum,omitempty"`
|
||||
|
||||
// List of static routes, each item must have destination, netmask, and gateway fields
|
||||
// Required: false
|
||||
Routes []Route `url:"-" json:"routes,omitempty" validate:"omitempty,dive"`
|
||||
|
||||
// Reason for action
|
||||
// Required: false
|
||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
type wrapperCreateRequestInAcc struct {
|
||||
CreateInAccountRequest
|
||||
Routes []string `url:"routes,omitempty"`
|
||||
}
|
||||
|
||||
// CreateInAccount creates VINS in account level
|
||||
func (v VINS) CreateInAccount(ctx context.Context, req CreateInAccountRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
@@ -48,9 +69,31 @@ func (v VINS) CreateInAccount(ctx context.Context, req CreateInAccountRequest) (
|
||||
}
|
||||
}
|
||||
|
||||
var routes []string
|
||||
|
||||
if len(req.Routes) != 0 {
|
||||
routes = make([]string, 0, len(req.Routes))
|
||||
|
||||
for r := range req.Routes {
|
||||
b, err := json.Marshal(req.Routes[r])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
routes = append(routes, string(b))
|
||||
}
|
||||
} else {
|
||||
routes = []string{"[]"}
|
||||
}
|
||||
|
||||
reqWrapped := wrapperCreateRequestInAcc{
|
||||
CreateInAccountRequest: req,
|
||||
Routes: routes,
|
||||
}
|
||||
|
||||
url := "/cloudbroker/vins/createInAccount"
|
||||
|
||||
res, err := v.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
res, err := v.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package vins
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -36,13 +37,22 @@ type CreateInRGRequest struct {
|
||||
|
||||
// Number of pre created reservations
|
||||
// Required: false
|
||||
PreReservationsNum uint `url:"preReservationsNum,omitempty" json:"preReservationsNum,omitempty"`
|
||||
PreReservationsNum uint64 `url:"preReservationsNum,omitempty" json:"preReservationsNum,omitempty"`
|
||||
|
||||
// List of static routes, each item must have destination, netmask, and gateway fields
|
||||
// Required: false
|
||||
Routes []Route `url:"-" json:"routes,omitempty" validate:"omitempty,dive"`
|
||||
|
||||
// Reason for action
|
||||
// Required: false
|
||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
type wrapperCreateRequestInRG struct {
|
||||
CreateInRGRequest
|
||||
Routes []string `url:"routes,omitempty"`
|
||||
}
|
||||
|
||||
// CreateInRG creates VINS in resource group level
|
||||
func (v VINS) CreateInRG(ctx context.Context, req CreateInRGRequest) (uint64, error) {
|
||||
err := validators.ValidateRequest(req)
|
||||
@@ -51,10 +61,31 @@ func (v VINS) CreateInRG(ctx context.Context, req CreateInRGRequest) (uint64, er
|
||||
return 0, validators.ValidationError(validationError)
|
||||
}
|
||||
}
|
||||
var routes []string
|
||||
|
||||
if len(req.Routes) != 0 {
|
||||
routes = make([]string, 0, len(req.Routes))
|
||||
|
||||
for r := range req.Routes {
|
||||
b, err := json.Marshal(req.Routes[r])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
routes = append(routes, string(b))
|
||||
}
|
||||
} else {
|
||||
routes = []string{"[]"}
|
||||
}
|
||||
|
||||
reqWrapped := wrapperCreateRequestInRG{
|
||||
CreateInRGRequest: req,
|
||||
Routes: routes,
|
||||
}
|
||||
|
||||
url := "/cloudbroker/vins/createInRG"
|
||||
|
||||
res, err := v.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||
res, err := v.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -345,7 +345,7 @@ type NATConfig struct {
|
||||
Network string `json:"network"`
|
||||
|
||||
// Rules
|
||||
Rules []interface{} `json:"rules"`
|
||||
Rules []ItemNATRule `json:"rules"`
|
||||
}
|
||||
|
||||
// Main information about NAT
|
||||
@@ -357,7 +357,7 @@ type RecordNAT struct {
|
||||
InfoVNF
|
||||
}
|
||||
|
||||
// NAT/GW/NAT details
|
||||
// DHCP/GW/NAT details
|
||||
type InfoVNF struct {
|
||||
// CKey
|
||||
CKey string `json:"_ckey"`
|
||||
@@ -368,9 +368,6 @@ type InfoVNF struct {
|
||||
// Account ID
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
// Config
|
||||
Config NATConfig `json:"config"`
|
||||
|
||||
// CreatedTime
|
||||
CreatedTime uint64 `json:"createdTime"`
|
||||
|
||||
@@ -401,6 +398,9 @@ type InfoVNF struct {
|
||||
// Pure virtual
|
||||
PureVirtual bool `json:"pureVirtual"`
|
||||
|
||||
// Routes
|
||||
Routes ListRoutes `json:"routes"`
|
||||
|
||||
// Status
|
||||
Status string `json:"status"`
|
||||
|
||||
@@ -411,6 +411,28 @@ type InfoVNF struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type ListRoutes []ItemRoutes
|
||||
|
||||
type ItemRoutes struct {
|
||||
//Compute Id
|
||||
ComputeIds []uint64 `json:"computeIds"`
|
||||
|
||||
// Destination network
|
||||
Destination string `json:"destination"`
|
||||
|
||||
//Next hop host, IP address from ViNS ID free IP pool
|
||||
Gateway string `json:"gateway"`
|
||||
|
||||
// GUID
|
||||
GUID uint64 `json:"guid"`
|
||||
|
||||
// ID
|
||||
ID uint64 `json:"id"`
|
||||
|
||||
//Destination network mask in 255.255.255.255 format
|
||||
Netmask string `json:"netmask"`
|
||||
}
|
||||
|
||||
// main information about VNF
|
||||
type RecordVNFs struct {
|
||||
// DHCP
|
||||
@@ -428,12 +450,6 @@ type RecordVINS struct {
|
||||
// VNF device
|
||||
VNFDev VNFDev `json:"VNFDev"`
|
||||
|
||||
// CKey
|
||||
CKey string `json:"_ckey"`
|
||||
|
||||
// Meta
|
||||
Meta []interface{} `json:"_meta"`
|
||||
|
||||
// Account ID
|
||||
AccountID uint64 `json:"accountId"`
|
||||
|
||||
|
||||
Reference in New Issue
Block a user