Compare commits

...

33 Commits

Author SHA1 Message Date
8a813abfcb v1.6.14 2024-03-22 12:11:46 +03:00
e7b30fb686 v1.6.12 2024-03-18 15:18:17 +03:00
cf11855fa3 v1.6.11 2024-01-22 14:08:06 +03:00
f111787976 v1.6.10 2023-12-14 17:52:12 +03:00
84c0248019 v1.6.8 2023-11-03 11:17:45 +03:00
4120cd2b1a v1.6.7 2023-10-25 17:37:18 +03:00
b666789c7d v1.6.6 2023-10-23 12:40:54 +03:00
b069c31745 v1.6.5 2023-10-11 12:18:27 +03:00
2953ef0a85 v1.6.4 2023-10-03 16:44:32 +03:00
50a4d5ade2 v1.6.3 2023-09-29 12:28:16 +03:00
1575b75fa6 v1.6.2 2023-09-28 19:34:23 +03:00
35fa4af0d6 v1.6.0 2023-09-28 15:37:28 +03:00
d3e6309ef8 v1.6.0-teta 2023-09-27 15:06:18 +03:00
78a4152471 v1.6.0-zeta 2023-09-25 19:11:33 +03:00
3e55195831 1.6.0-epsilon 2023-09-24 14:41:21 +03:00
9f5e76aee4 1.6.0-delta 2023-09-24 12:11:31 +03:00
df8b045e77 v1.5.8 2023-09-18 14:13:55 +03:00
4d9b8fc9d8 v1.5.7 2023-09-04 18:48:22 +03:00
e8270453cc 1.5.6 2023-08-30 13:54:30 +03:00
7de095302b v1.5.5 2023-08-25 13:53:43 +03:00
a3711057ba v1.5.4 2023-08-22 15:28:39 +03:00
1c59ca338a v1.5.3 2023-08-15 11:42:30 +03:00
f1529c9aac v1.5.2 2023-08-09 19:33:50 +03:00
040235f92f v1.5.1 2023-07-24 18:13:52 +03:00
4a152cb44c v1.5.0 2023-07-24 16:43:10 +03:00
c78b1348e3 v1.5.0 2023-07-24 15:13:04 +03:00
8f152a2f63 v1.5.0 2023-07-21 15:14:10 +03:00
0be4d8fb0c v1.5.0-epsilon 2023-07-13 18:32:21 +03:00
Никита Сорокин
5025a17ea4 v1.5.0-delta 2023-07-13 15:28:07 +03:00
7c787f6fce v1.5.0-gamma2 2023-07-07 12:40:03 +03:00
20fd7ab50c v1.5.0-gamma-qf 2023-06-30 11:24:26 +03:00
f50f71ab0d v1.5.0-gamma 2023-06-30 11:21:47 +03:00
29c7f143fe v1.4.7 2023-06-29 15:52:49 +03:00
867 changed files with 14405 additions and 7511 deletions

5
.gitignore vendored
View File

@@ -1,2 +1,5 @@
cmd/ cmd/
.idea/ .idea/
.vscode/
.fleet/
.DS_Store

View File

@@ -1,12 +1,5 @@
## Version 1.4.6 ## Version 1.6.14
### Bugfix ### Bugfix
- Fixed returning value type of VINS.NATRuleAdd() - Delete tag required from DeleteRequest field Permanently in cloudapi/k8s
- Fixed RuleID field type of VINS.NATRuleDel() request struct - Delete tag omitempty from DeleteDisksRequest and DisksDeleteRequest field Permanently in cloudapi/disks and cloudbroker/disks
- Added wrapper for requests to async methods
- - CloudAPI()/CloudBroker().Compute().CreateTemplate()
### Feature
- Added cloubroker/apiaccess group of endpoints support
- Added cloubroker/group group of endpoints support
- Added cloubroker/user group of endpoints support

153
README.md
View File

@@ -9,6 +9,8 @@ Decort SDK - это библиотека, написанная на языке G
- Версия 1.2.x Decort-SDK соответствует 3.8.5 версии платформы - Версия 1.2.x Decort-SDK соответствует 3.8.5 версии платформы
- Версия 1.3.x Decort-SDK соответствует 3.8.5 версии платформы - Версия 1.3.x Decort-SDK соответствует 3.8.5 версии платформы
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы - Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
## Оглавление ## Оглавление
@@ -61,12 +63,11 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов; - `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
- `BService` - управление группами виртуальных машин (computes); - `BService` - управление группами виртуальных машин (computes);
- `Compute` - управление виртуальными машинами (индивидуально); - `Compute` - управление виртуальными машинами (индивидуально);
- `ComputeCI` - управление конвейром для создания виртуальных машин;
- `Disks` - управление виртуальными дисками; - `Disks` - управление виртуальными дисками;
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ; - `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
- `FLIPgroup` - управление группами "плавающими" ip - адресами; - `FLIPgroup` - управление группами "плавающими" ip - адресами;
- `Image` - управление образами операционных систем; - `Image` - управление образами операционных систем;
- `K8CI` - управление конвейром для создания кластера; - `K8CI` - получение информации о конвейере для создания кластера;
- `K8S` - управление кластерами kubernetes; - `K8S` - управление кластерами kubernetes;
- `KVMPPC` - создание виртуальной машины Power PC (IBM); - `KVMPPC` - создание виртуальной машины Power PC (IBM);
- `KVMx86` - создание виртуальной машины x86; - `KVMx86` - создание виртуальной машины x86;
@@ -74,6 +75,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
- `Locations` - получение информации о grid площадки; - `Locations` - получение информации о grid площадки;
- `RG` - управление ресурсными группами аккаунта; - `RG` - управление ресурсными группами аккаунта;
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками; - `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
- `Stack` - получение информации о вычислительных узлах;
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера); - `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
- `VINS` - управление виртуальными изолированными сетями. - `VINS` - управление виртуальными изолированными сетями.
@@ -83,30 +85,39 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
Данная группа ручек позволяет выполнять следующие операции в платформе: Данная группа ручек позволяет выполнять следующие операции в платформе:
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов; - `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
- `APIAccess` - управление доступом к API и его объектам;
- `Backup` - управление резервным копированием;
- `Compute` - управление виртуальными машинами (индивидуально); - `Compute` - управление виртуальными машинами (индивидуально);
- `Disks` - управление виртуальными дисками; - `Disks` - управление виртуальными дисками;
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ; - `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
- `FLIPGroup` - управление группами с «плавающими» ip адресами;
- `Grid` - управление площадками; - `Grid` - управление площадками;
- `Group` - управление группами пользователей;
- `Image` - управление образами операционных систем; - `Image` - управление образами операционных систем;
- `K8CI` - управление конвейром для создания кластера; - `K8CI` - управление конвейром для создания кластера;
- `K8S` - управление кластерами kubernetes; - `K8S` - управление кластерами kubernetes;
- `KVMPPC` - создание виртуальной машины Power PC (IBM); - `KVMPPC` - создание виртуальной машины Power PC (IBM);
- `KVMx86` - создание виртуальной машины x86; - `KVMx86` - создание виртуальной машины x86;
- `LB` - управление балансировщиками нагрузки; - `LB` - управление балансировщиками нагрузки;
- `PCIDevice` - управление устройствами;
- `RG` - управление ресурсными группами аккаунта; - `RG` - управление ресурсными группами аккаунта;
- `SEP` - управление storage endpoint (sep); - `SEP` - управление storage endpoint (sep);
- `Stack` - получение информации о вычислительных узлах;
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера); - `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
- `User` - управление пользователями (индивидуально);
- `VGPU` - управление виртуальными графическими процессорами;
- `VINS` - управление виртуальными изолированными сетями. - `VINS` - управление виртуальными изолированными сетями.
## Работа с библиотекой ## Работа с библиотекой
Алгоритм работы с библиотекой выглядит следующим образом: Алгоритм работы с библиотекой выглядит следующим образом:
1. Настройка конфигурации клиента. 1. Выполнение одного из действий:
2. Парсинг конфигурации из файла. - настройка конфигурации клиента;
3. Создание клиента. - парсинг конфигурации из файла.
4. Создание структуры запроса. 2. Создание клиента.
5. Выполнение запроса. 3. Создание структуры запроса.
4. Выполнение запроса.
### Настройка конфигурации клиента ### Настройка конфигурации клиента
@@ -119,7 +130,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие | | DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 | | Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений | | Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true | | SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
| Token | string | Нет | JWT токен | | Token | string | Нет | JWT токен |
#### Пример конфигурации клиента #### Пример конфигурации клиента
@@ -230,7 +241,6 @@ func main() {
- `pkg/cloudapi/account` - для `Account` - `pkg/cloudapi/account` - для `Account`
- `pkg/cloudapi/bservice` - для `Basic Service` - `pkg/cloudapi/bservice` - для `Basic Service`
- `pkg/cloudapi/compute` - для `Compute` - `pkg/cloudapi/compute` - для `Compute`
- `pkg/cloudapi/computeci` - для `ComputeCI`
- `pkg/cloudapi/disks` - для `Disks` - `pkg/cloudapi/disks` - для `Disks`
- `pkg/cloudapi/extnet` - для `ExtNet` - `pkg/cloudapi/extnet` - для `ExtNet`
- `pkg/cloudapi/flipgroup` - для `FLIPGroup` - `pkg/cloudapi/flipgroup` - для `FLIPGroup`
@@ -242,24 +252,33 @@ func main() {
- `pkg/cloudapi/lb` - для `LB` - `pkg/cloudapi/lb` - для `LB`
- `pkg/cloudapi/locations` - для `Locations` - `pkg/cloudapi/locations` - для `Locations`
- `pkg/cloudapi/rg` - для `RG` - `pkg/cloudapi/rg` - для `RG`
- `pkg/cloudapi/sizes` - для `RG` - `pkg/cloudapi/sizes` - для `Sizes`
- `pkg/cloudapi/stack` - для `Stack`
- `pkg/cloudapi/tasks` - для `Tasks` - `pkg/cloudapi/tasks` - для `Tasks`
- `pkg/cloudapi/vins` - для `VINS` - `pkg/cloudapi/vins` - для `VINS`
- **cloudbroker**: - **cloudbroker**:
- `pkg/cloudbroker/account` - для `Account` - `pkg/cloudbroker/account` - для `Account`
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
- `pkg/cloudbroker/backup` - для `Backup`
- `pkg/cloudbroker/compute` - для `Compute` - `pkg/cloudbroker/compute` - для `Compute`
- `pkg/cloudbroker/disks` - для `Disks` - `pkg/cloudbroker/disks` - для `Disks`
- `pkg/cloudbroker/extnet` - для `ExtNet` - `pkg/cloudbroker/extnet` - для `ExtNet`
- `pkg/cloudbroker/flipgroup` - для `FLIPGroup`
- `pkg/cloudbroker/grid` - для `Grid` - `pkg/cloudbroker/grid` - для `Grid`
- `pkg/cloudbroker/group` - для `Group`
- `pkg/cloudbroker/image` - для `Image` - `pkg/cloudbroker/image` - для `Image`
- `pkg/cloudbroker/k8ci` - для `K8CI` - `pkg/cloudbroker/k8ci` - для `K8CI`
- `pkg/cloudbroker/k8s` - для `K8S` - `pkg/cloudbroker/k8s` - для `K8S`
- `pkg/cloudbroker/kvmppc` - для `KVMPPC` - `pkg/cloudbroker/kvmppc` - для `KVMPPC`
- `pkg/cloudbroker/kvmx86` - для `KVMX86` - `pkg/cloudbroker/kvmx86` - для `KVMX86`
- `pkg/cloudbroker/lb` - для `LB` - `pkg/cloudbroker/lb` - для `LB`
- `pkg/cloudbroker/pcidevice` - для `PCIDevice`
- `pkg/cloudbroker/rg` - для `RG` - `pkg/cloudbroker/rg` - для `RG`
- `pkg/cloudbroker/sep` - для `SEP` - `pkg/cloudbroker/sep` - для `SEP`
- `pkg/cloudbroker/stack` - для `Stack`
- `pkg/cloudbroker/tasks` - для `Tasks` - `pkg/cloudbroker/tasks` - для `Tasks`
- `pkg/cloudbroker/user` - для `User`
- `pkg/cloudbroker/vgpu` - для `VGPU`
- `pkg/cloudbroker/vins` - для `VINS` - `pkg/cloudbroker/vins` - для `VINS`
Все поля структуры имеют описание, в которых содержится: Все поля структуры имеют описание, в которых содержится:
@@ -396,7 +415,7 @@ func main() {
Чтобы выполнить запрос, необходимо: Чтобы выполнить запрос, необходимо:
1. Вызвать у клиента метод, отвечаеющий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, либо `.CloudBroker()`. Данные методы возвращаеют соответствующие структуры, с помощью которых можно соверать запросы. 1. Вызвать у клиента метод, отвечаеющий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, либо `.CloudBroker()`. Данные методы возвращаеют соответствующие структуры, с помощью которых можно совершать запросы.
2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия. 2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия.
Доступные методы для `.CloudAPI()`: Доступные методы для `.CloudAPI()`:
@@ -404,7 +423,6 @@ func main() {
- `.Account()` - для работы с `Account` - `.Account()` - для работы с `Account`
- `.BService()` - для работы с `BService` - `.BService()` - для работы с `BService`
- `.Compute()` - для работы с `Compute` - `.Compute()` - для работы с `Compute`
- `.ComputeCI()` - для работы с `ComputeCI`
- `.Disks()` - для работы с `Disks` - `.Disks()` - для работы с `Disks`
- `.ExtNet()` - для работы с `ExtNet` - `.ExtNet()` - для работы с `ExtNet`
- `.FLIPgroup()` - для работы с `FLIPGroup` - `.FLIPgroup()` - для работы с `FLIPGroup`
@@ -417,37 +435,46 @@ func main() {
- `.Locations()` - для работы с `Locations` - `.Locations()` - для работы с `Locations`
- `.RG()` - для работы с `RG` - `.RG()` - для работы с `RG`
- `.Sizes()` - для работы с `Sizes` - `.Sizes()` - для работы с `Sizes`
- `.Stack()` - для работы с `Stack`
- `.Tasks()` - для работы с `Tasks` - `.Tasks()` - для работы с `Tasks`
- `.VINS()` - для работы с `VINS` - `.VINS()` - для работы с `VINS`
Доступные методы для `.CloudBroker()`: Доступные методы для `.CloudBroker()`:
- `.Account()` - для работы с `Account` - `.Account()` - для работы с `Account`
- `.APIAccess()` - для работы с `APIAccess`
- `.Backup()` - для работы с `Backup`
- `.Compute()` - для работы с `Compute` - `.Compute()` - для работы с `Compute`
- `.Disks()` - для работы с `Disks` - `.Disks()` - для работы с `Disks`
- `.ExtNet()` - для работы с `ExtNet` - `.ExtNet()` - для работы с `ExtNet`
- `.FLIPGroup()` - для работы с `FLIPGroup`
- `.Grid()` - для работы с `Grid` - `.Grid()` - для работы с `Grid`
- `.Group()` - для работы с `Group`
- `.Image()` - для работы с `Image` - `.Image()` - для работы с `Image`
- `.K8CI()` - для работы с `K8CI` - `.K8CI()` - для работы с `K8CI`
- `.K8S()` - для работы с `K8S` - `.K8S()` - для работы с `K8S`
- `.KVMPPC()` - для работы с `KVMPPC` - `.KVMPPC()` - для работы с `KVMPPC`
- `.KVMx86()` - для работы с `KVMX86` - `.KVMx86()` - для работы с `KVMX86`
- `.LB()` - для работы с `LB` - `.LB()` - для работы с `LB`
- `.PCIDevice()` - для работы с `PCIDevice`
- `.RG()` - для работы с `RG` - `.RG()` - для работы с `RG`
- `.SEP()` - для работы с `SEP` - `.SEP()` - для работы с `SEP`
- `.Stack()` - для работы с `Stack`
- `.Tasks()` - для работы с `Tasks` - `.Tasks()` - для работы с `Tasks`
- `.User()` - для работы с `User`
- `.VGPU()` - для работы с `VGPU`
- `.VINS()` - для работы с `VINS` - `.VINS()` - для работы с `VINS`
3. Вызвать метод, отвечающий за выполнение запроса и передать в него: 3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
- контекст; - контекст;
- структуру запроса. - структуру запроса.
У кождой группы ручек API имеются свои доступные методы, которые определяются платформой. У каждой группы ручек API имеются свои доступные методы, которые определяются платформой.
4. Обработать результат и ошибки. 4. Обработать результат и ошибки.
Т.к. все вызовы методов идут последовательно, можно их объеденить в конвейер: Т.к. все вызовы методов идут последовательно, можно их объеденить в конвейер:
Общий вид вонвейра будет выглядеть так: Общий вид конвейера будет выглядеть так:
```go ```go
client.<API>.<группа>.<метод> client.<API>.<группа>.<метод>
@@ -500,6 +527,56 @@ func main() {
} }
``` ```
Для запросов Get и List реализованы запросы GetRaw и ListRaw, которые возвращают ответ не в виде соответствующей структуры, а в виде массива байт (JSON).
Выполнение таких запросов происходит аналогично.
#### Пример выполнения GetRaw и ListRaw запросов
```go
package main
import (
"log"
"fmt"
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
)
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)
// 1. Создание структуры запроса GetRequest на получение информации об аккаунте и выполнение GetRaw запроса с помощью конвейера
req1 := account.GetRequest{
AccountID: 123,
}
res1, err := client.CloudAPI().Account().GetRaw(context.Background(), req1)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(res1))
// 2. Создание структуры запроса ListRequest на получение информации об аккаунтах и выполнение ListRaw запроса с помощью конвейера
req2 := account.ListRequest{}
res2, err := client.CloudAPI().Account().ListRaw(context.Background(), req2)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(res2))
}
```
### Фильтрация ### Фильтрация
Для каждого `ListRequest` в SDK есть группа функций для фильтрации ответа платформы. Для того чтобы произвести фильтрацию по заданным полям, достаточно описать анонимную функцию (предикат) в `.FilterFunc()`, например: Для каждого `ListRequest` в SDK есть группа функций для фильтрации ответа платформы. Для того чтобы произвести фильтрацию по заданным полям, достаточно описать анонимную функцию (предикат) в `.FilterFunc()`, например:
@@ -689,6 +766,52 @@ func main() {
``` ```
### Получение списка уникальных идентификаторов (ID) объекта
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
```go
package main
import (
"log"
"fmt"
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
)
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)
// Создание структуры запроса GetRequest на получение информации о сервисе и выполнение запроса с помощью конвейера
req := bservice.GetRequest{
ServiceID: 123,
}
res, err := client.CloudAPI().BService().Get(context.Background(), req)
if err != nil {
log.Fatal(err)
}
// Получение списков ID ComputeIDs и GroupIDs экземпляра res типа RecordBasicService по полям Computes и Groups, соответственно
computeIDs := res.Computes.IDs()
groupIDs := res.Groups.IDs()
fmt.Println(computeIDs)
fmt.Println(groupIDs)
}
```
## Работа с legacy клиентом ## Работа с legacy клиентом
Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o. Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o.
@@ -704,7 +827,7 @@ func main() {
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие | | DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 | | Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений | | Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true | | SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
| Token | string | Нет | JWT токен | | Token | string | Нет | JWT токен |
#### Пример конфигурации legacy клиента #### Пример конфигурации legacy клиента

369
client.go
View File

@@ -1,24 +1,33 @@
package decortsdk package decortsdk
import ( import (
"bytes"
"context" "context"
"errors" "crypto/tls"
"fmt"
"io" "io"
"mime/multipart"
"net/http" "net/http"
"strconv"
"strings" "strings"
"sync"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi" "time"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
"github.com/google/go-querystring/query" "github.com/google/go-querystring/query"
"repository.basistech.ru/BASIS/decort-golang-sdk/config" "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"
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"
) )
// HTTP-client for platform // HTTP-client for platform
type DecortClient struct { type DecortClient struct {
decortURL string decortURL string
client *http.Client client *http.Client
cfg config.Config
expiryTime time.Time
mutex *sync.Mutex
} }
// Сlient builder // Сlient builder
@@ -27,9 +36,25 @@ func New(cfg config.Config) *DecortClient {
cfg.Retries = 5 cfg.Retries = 5
} }
var expiryTime time.Time
if cfg.Token != "" {
expiryTime = time.Now().AddDate(0, 0, 1)
}
return &DecortClient{ return &DecortClient{
decortURL: cfg.DecortURL, 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{},
} }
} }
@@ -45,31 +70,331 @@ func (dc *DecortClient) CloudBroker() *cloudbroker.CloudBroker {
// DecortApiCall method for sending requests to the platform // DecortApiCall method for sending requests to the platform
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) { func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
values, err := query.Values(params) k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
if err != nil { k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
return nil, err var body *bytes.Buffer
var ctype string
if okCa {
body, ctype = createK8sCloudApi(k8sCaCreateReq)
} else if okCb {
body, ctype = createK8sCloudBroker(k8sCbCreateReq)
} else {
values, err := query.Values(params)
if err != nil {
return nil, err
}
body = bytes.NewBufferString(values.Encode())
} }
body := strings.NewReader(values.Encode())
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, body) req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp, err := dc.client.Do(req) if err = dc.getToken(ctx); err != nil {
return nil, err
}
// perform request
var respBytes []byte
respBytes, err = dc.do(req, ctype)
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)
}
return nil
}
func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
if ctype != "" {
req.Header.Add("Content-Type", ctype)
} else {
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, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Body = io.NopCloser(bytes.NewBuffer(buf))
resp, err := dc.client.Do(req)
if err != nil || resp == nil {
return nil, err
}
defer resp.Body.Close() defer resp.Body.Close()
respBytes, err := io.ReadAll(resp.Body) // handle successful request
if err != nil { respBytes, _ := io.ReadAll(resp.Body)
return nil, err if resp.StatusCode == 200 {
return respBytes, nil
} }
if resp.StatusCode != 200 { // handle errors with status code other than 200
return nil, errors.New(string(respBytes)) err = fmt.Errorf("%s", respBytes)
} return nil, fmt.Errorf("could not execute request: %w", err)
}
return respBytes, nil
func createK8sCloudApi(req k8s_ca.CreateRequest) (*bytes.Buffer, string) {
reqBody := &bytes.Buffer{}
writer := multipart.NewWriter(reqBody)
if req.OidcCertificate != "" {
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
}
_ = writer.WriteField("name", req.Name)
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8SCIID, 10))
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
if req.MasterSEPID != 0 {
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
}
if req.MasterSEPPool != "" {
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
}
if req.WorkerSEPID != 0 {
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
}
if req.WorkerSEPPool != "" {
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
}
if req.Labels != nil {
for _, v := range req.Labels {
_ = writer.WriteField("labels", v)
}
}
if req.Taints != nil {
for _, v := range req.Taints {
_ = writer.WriteField("taints", v)
}
}
if req.Annotations != nil {
for _, v := range req.Annotations {
_ = writer.WriteField("annotations", v)
}
}
if req.MasterCPU != 0 {
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(req.MasterCPU), 10))
}
if req.MasterNum != 0 {
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(req.MasterNum), 10))
}
if req.MasterRAM != 0 {
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(req.MasterRAM), 10))
}
if req.MasterDisk != 0 {
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(req.MasterDisk), 10))
}
if req.WorkerCPU != 0 {
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(req.WorkerCPU), 10))
}
if req.WorkerNum != 0 {
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(req.WorkerNum), 10))
}
if req.WorkerRAM != 0 {
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(req.WorkerRAM), 10))
}
if req.WorkerDisk != 0 {
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(req.WorkerDisk), 10))
}
if req.ExtNetID != 0 {
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
}
if req.VinsId != 0 {
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
}
if !req.WithLB {
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
}
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
if req.AdditionalSANs != nil {
for _, v := range req.AdditionalSANs {
_ = writer.WriteField("additionalSANs", v)
}
}
if req.InitConfiguration != "" {
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
}
if req.ClusterConfiguration != "" {
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
}
if req.KubeletConfiguration != "" {
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
}
if req.KubeProxyConfiguration != "" {
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
}
if req.JoinConfiguration != "" {
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
}
if req.Description != "" {
_ = writer.WriteField("desc", req.Description)
}
if req.UserData != "" {
_ = writer.WriteField("userData", req.UserData)
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
ct := writer.FormDataContentType()
writer.Close()
return reqBody, ct
}
func createK8sCloudBroker(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
reqBody := &bytes.Buffer{}
writer := multipart.NewWriter(reqBody)
if req.OidcCertificate != "" {
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
}
_ = writer.WriteField("name", req.Name)
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8CIID, 10))
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
if req.MasterSEPID != 0 {
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
}
if req.MasterSEPPool != "" {
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
}
if req.WorkerSEPID != 0 {
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
}
if req.WorkerSEPPool != "" {
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
}
if req.Labels != nil {
for _, v := range req.Labels {
_ = writer.WriteField("labels", v)
}
}
if req.Taints != nil {
for _, v := range req.Taints {
_ = writer.WriteField("taints", v)
}
}
if req.Annotations != nil {
for _, v := range req.Annotations {
_ = writer.WriteField("annotations", v)
}
}
if req.MasterCPU != 0 {
_ = writer.WriteField("masterCpu", strconv.FormatUint(req.MasterCPU, 10))
}
if req.MasterNum != 0 {
_ = writer.WriteField("masterNum", strconv.FormatUint(req.MasterNum, 10))
}
if req.MasterRAM != 0 {
_ = writer.WriteField("masterRam", strconv.FormatUint(req.MasterRAM, 10))
}
if req.MasterDisk != 0 {
_ = writer.WriteField("masterDisk", strconv.FormatUint(req.MasterDisk, 10))
}
if req.WorkerCPU != 0 {
_ = writer.WriteField("workerCpu", strconv.FormatUint(req.WorkerCPU, 10))
}
if req.WorkerNum != 0 {
_ = writer.WriteField("workerNum", strconv.FormatUint(req.WorkerNum, 10))
}
if req.WorkerRAM != 0 {
_ = writer.WriteField("workerRam", strconv.FormatUint(req.WorkerRAM, 10))
}
if req.WorkerDisk != 0 {
_ = writer.WriteField("workerDisk", strconv.FormatUint(req.WorkerDisk, 10))
}
if req.ExtNetID != 0 {
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
}
if req.VinsId != 0 {
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
}
if !req.WithLB {
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
}
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
if req.AdditionalSANs != nil {
for _, v := range req.AdditionalSANs {
_ = writer.WriteField("additionalSANs", v)
}
}
if req.InitConfiguration != "" {
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
}
if req.ClusterConfiguration != "" {
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
}
if req.KubeletConfiguration != "" {
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
}
if req.KubeProxyConfiguration != "" {
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
}
if req.JoinConfiguration != "" {
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
}
if req.Description != "" {
_ = writer.WriteField("desc", req.Description)
}
if req.UserData != "" {
_ = writer.WriteField("userData", req.UserData)
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
ct := writer.FormDataContentType()
writer.Close()
return reqBody, ct
} }

View File

@@ -42,7 +42,7 @@ type Config struct {
// Required: false // Required: false
Retries uint64 `json:"retries" yaml:"retries"` Retries uint64 `json:"retries" yaml:"retries"`
// Skip verify, true by default // Skip verify
// Required: false // Required: false
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"` SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
@@ -72,9 +72,7 @@ func ParseConfigJSON(path string) (Config, error) {
err = validators.ValidateConfig(config) err = validators.ValidateConfig(config)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return Config{}, validators.ValidationErrors(validators.GetErrors(err))
return Config{}, validators.ValidationError(validationError)
}
} }
return config, nil return config, nil
@@ -96,9 +94,7 @@ func ParseConfigYAML(path string) (Config, error) {
err = validators.ValidateConfig(config) err = validators.ValidateConfig(config)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return Config{}, validators.ValidationErrors(validators.GetErrors(err))
return Config{}, validators.ValidationError(validationError)
}
} }
return config, nil return config, nil

View File

@@ -36,7 +36,7 @@ type LegacyConfig struct {
// Required: false // Required: false
Retries uint64 `json:"retries" yaml:"retries"` Retries uint64 `json:"retries" yaml:"retries"`
// Skip verify, true by default // Skip verify
// Required: false // Required: false
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"` SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
@@ -66,9 +66,7 @@ func ParseLegacyConfigJSON(path string) (LegacyConfig, error) {
err = validators.ValidateConfig(config) err = validators.ValidateConfig(config)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
return LegacyConfig{}, validators.ValidationError(validationError)
}
} }
return config, nil return config, nil
@@ -90,9 +88,7 @@ func ParseLegacyConfigYAML(path string) (LegacyConfig, error) {
err = validators.ValidateConfig(config) err = validators.ValidateConfig(config)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
return LegacyConfig{}, validators.ValidationError(validationError)
}
} }
return config, nil return config, nil

View File

@@ -23,7 +23,7 @@ func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
*d = Duration(tmp) *d = Duration(tmp)
return nil return nil
default: default:
return fmt.Errorf("Invalid duration %v", value) return fmt.Errorf("invalid duration %v", value)
} }
} }
@@ -41,7 +41,7 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
*d = Duration(tmp) *d = Duration(tmp)
return nil return nil
default: default:
return fmt.Errorf("Invalid duration %v", value) return fmt.Errorf("invalid duration %v", value)
} }
} }

View File

@@ -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(),
}
}

View File

@@ -1,32 +0,0 @@
package client
import (
"crypto/tls"
"net/http"
"net/url"
"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,
},
}
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,
},
Timeout: cfg.Timeout.Get(),
}
}

View File

@@ -1,70 +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
}
func (t *transportLegacy) RoundTrip(request *http.Request) (*http.Response, error) {
if t.token == "" {
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
}
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()
}
time.Sleep(time.Second * 5)
}
return nil, fmt.Errorf("could not execute request: %w", err)
}

View File

@@ -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)
}

View 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
}

View File

@@ -1,11 +1,19 @@
package validators package validators
import ( import (
"github.com/go-playground/validator/v10"
"regexp" "regexp"
"strings" "strings"
"github.com/go-playground/validator/v10"
) )
// computeDriverValidator is used to validate Driver field in kvmx86/kvmppc create.
func computeDriverValidator(fe validator.FieldLevel) bool {
fieldValue := fe.Field().String()
return StringInSlice(fieldValue, computeDriverValues)
}
// protoValidator is used to validate Proto fields. // protoValidator is used to validate Proto fields.
func protoValidator(fe validator.FieldLevel) bool { func protoValidator(fe validator.FieldLevel) bool {
fieldValue := fe.Field().String() fieldValue := fe.Field().String()
@@ -256,3 +264,11 @@ func strictLooseValidator(fe validator.FieldLevel) bool {
return StringInSlice(fieldValue, strictLooseValues) return StringInSlice(fieldValue, strictLooseValues)
} }
// name workerGroup must be more 3 symbol
func workerGroupNameValidator(fe validator.FieldLevel) bool {
fieldValue := fe.Field().String()
fieldValue = strings.Trim(fieldValue, " ")
return len(fieldValue) >= 3
}

View File

@@ -2,6 +2,7 @@ package validators
import ( import (
"errors" "errors"
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/multierror"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
) )
@@ -20,6 +21,14 @@ func ValidationError(fe validator.FieldError) error {
return errors.New(errorMessage(fe)) 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 //nolint:errorlint
func GetErrors(err error) validator.ValidationErrors { func GetErrors(err error) validator.ValidationErrors {
return err.(validator.ValidationErrors) return err.(validator.ValidationErrors)

View File

@@ -107,6 +107,12 @@ func errorMessage(fe validator.FieldError) string {
fe.Field(), fe.Field(),
joinValues(computeDataDisksValues)) joinValues(computeDataDisksValues))
case "computeDriver":
return fmt.Sprintf("%s %s must be one of the following: %s",
prefix,
fe.Field(),
joinValues(computeDriverValues))
// Disk Validators // Disk Validators
case "diskType": case "diskType":
return fmt.Sprintf("%s %s must be one of the following: %s", return fmt.Sprintf("%s %s must be one of the following: %s",
@@ -121,6 +127,12 @@ func errorMessage(fe validator.FieldError) string {
fe.Field(), fe.Field(),
joinValues(flipgroupClientTypeValues)) joinValues(flipgroupClientTypeValues))
// k8s Validators
case "workerGroupName":
return fmt.Sprintf("%s %s must be more 3 symbol",
prefix,
fe.Field())
// KVM_X86/KVM_PPC Validators // KVM_X86/KVM_PPC Validators
case "kvmNetType": case "kvmNetType":
return fmt.Sprintf("%s %s must be one of the following: %s", return fmt.Sprintf("%s %s must be one of the following: %s",

View File

@@ -30,6 +30,11 @@ func registerAllValidators(validate *validator.Validate) error {
return err return err
} }
err = validate.RegisterValidation("computeDriver", computeDriverValidator)
if err != nil {
return err
}
err = validate.RegisterValidation("accessType", accessTypeValidator) err = validate.RegisterValidation("accessType", accessTypeValidator)
if err != nil { if err != nil {
return err return err
@@ -175,5 +180,10 @@ func registerAllValidators(validate *validator.Validate) error {
return err return err
} }
err = validate.RegisterValidation("workerGroupName", workerGroupNameValidator)
if err != nil {
return err
}
return nil return nil
} }

View File

@@ -6,7 +6,7 @@ var (
resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"} resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"}
protoValues = []string{"tcp", "udp"} protoValues = []string{"tcp", "udp"}
accountCUTypeValues = []string{"CU_M", "CU_C", "CU_D", "CU_S", "CU_A", "CU_NO", "CU_I", "CU_NP"} accountCUTypeValues = []string{"CU_M", "CU_C", "CU_D", "CU_DM", "CU_S", "CU_A", "CU_NO", "CU_I", "CU_NP"}
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"} bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
@@ -17,6 +17,7 @@ var (
computeNetTypeValues = []string{"EXTNET", "VINS"} computeNetTypeValues = []string{"EXTNET", "VINS"}
computeOrderValues = []string{"cdrom", "network", "hd"} computeOrderValues = []string{"cdrom", "network", "hd"}
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"} computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
computeDriverValues = []string{"KVM_X86", "SVA_KVM_X86"}
diskTypeValues = []string{"B", "T", "D"} diskTypeValues = []string{"B", "T", "D"}
@@ -38,7 +39,7 @@ var (
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"} sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
networkPluginValues = []string{"flannel", "weawenet", "calico"} networkPluginValues = []string{"flannel", "weavenet", "calico"}
strictLooseValues = []string{"strict", "loose"} strictLooseValues = []string{"strict", "loose"}

View File

@@ -1,23 +1,34 @@
package decortsdk package decortsdk
import ( import (
"bytes"
"context" "context"
"errors" "crypto/tls"
"fmt"
"io" "io"
"mime/multipart"
"net/http" "net/http"
"net/url"
"strconv"
"strings" "strings"
"sync"
"time"
"github.com/google/go-querystring/query" "github.com/google/go-querystring/query"
"repository.basistech.ru/BASIS/decort-golang-sdk/config" "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/cloudapi"
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
k8s_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
) )
// Legacy HTTP-client for platform // Legacy HTTP-client for platform
type LegacyDecortClient struct { type LegacyDecortClient struct {
decortURL string decortURL string
client *http.Client client *http.Client
cfg config.LegacyConfig
expiryTime time.Time
mutex *sync.Mutex
} }
// Legacy client builder // Legacy client builder
@@ -26,9 +37,25 @@ func NewLegacy(cfg config.LegacyConfig) *LegacyDecortClient {
cfg.Retries = 5 cfg.Retries = 5
} }
var expiryTime time.Time
if cfg.Token != "" {
expiryTime = time.Now().AddDate(0, 0, 1)
}
return &LegacyDecortClient{ return &LegacyDecortClient{
decortURL: cfg.DecortURL, 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{},
} }
} }
@@ -44,31 +71,335 @@ func (ldc *LegacyDecortClient) CloudBroker() *cloudbroker.CloudBroker {
// DecortApiCall method for sending requests to the platform // DecortApiCall method for sending requests to the platform
func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) { func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
values, err := query.Values(params) if err := ldc.getToken(ctx); err != nil {
if err != nil {
return nil, err return nil, err
} }
body := strings.NewReader(values.Encode()) k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
var body *bytes.Buffer
var ctype string
if okCa {
body, ctype = createK8sCloudApiLegacy(k8sCaCreateReq, ldc.cfg.Token)
} else if okCb {
body, ctype = createK8sCloudBrokerLegacy(k8sCbCreateReq, ldc.cfg.Token)
} 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+"/restmachine"+url, body) req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+"/restmachine"+url, body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp, err := ldc.client.Do(req) // perform request
var respBytes []byte
respBytes, err = ldc.do(req, ctype)
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)
}
return nil
}
func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
if ctype != "" {
req.Header.Add("Content-Type", ctype)
} else {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}
req.Header.Set("Accept", "application/json")
buf, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Body.Close()
req.Body = io.NopCloser(bytes.NewBuffer(buf))
resp, err := ldc.client.Do(req)
if err != nil || resp == nil {
return nil, err
}
defer resp.Body.Close() defer resp.Body.Close()
// handle successful request
respBytes, err := io.ReadAll(resp.Body) respBytes, err := io.ReadAll(resp.Body)
if err != nil { if err!= nil {
return nil, err return nil, err
} }
if resp.StatusCode == 200 {
if resp.StatusCode != 200 { return respBytes, nil
return nil, errors.New(string(respBytes))
} }
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 createK8sCloudApiLegacy(req k8s_ca.CreateRequest, token string) (*bytes.Buffer, string) {
reqBody := &bytes.Buffer{}
writer := multipart.NewWriter(reqBody)
if req.OidcCertificate != "" {
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
}
_ = writer.WriteField("name", req.Name)
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8SCIID, 10))
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
if req.MasterSEPID != 0 {
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
}
if req.MasterSEPPool != "" {
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
}
if req.WorkerSEPID != 0 {
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
}
if req.WorkerSEPPool != "" {
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
}
if req.Labels != nil {
for _, v := range req.Labels {
_ = writer.WriteField("labels", v)
}
}
if req.Taints != nil {
for _, v := range req.Taints {
_ = writer.WriteField("taints", v)
}
}
if req.Annotations != nil {
for _, v := range req.Annotations {
_ = writer.WriteField("annotations", v)
}
}
if req.MasterCPU != 0 {
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(req.MasterCPU), 10))
}
if req.MasterNum != 0 {
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(req.MasterNum), 10))
}
if req.MasterRAM != 0 {
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(req.MasterRAM), 10))
}
if req.MasterDisk != 0 {
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(req.MasterDisk), 10))
}
if req.WorkerCPU != 0 {
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(req.WorkerCPU), 10))
}
if req.WorkerNum != 0 {
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(req.WorkerNum), 10))
}
if req.WorkerRAM != 0 {
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(req.WorkerRAM), 10))
}
if req.WorkerDisk != 0 {
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(req.WorkerDisk), 10))
}
if req.ExtNetID != 0 {
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
}
if req.VinsId != 0 {
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
}
if !req.WithLB {
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
}
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
if req.AdditionalSANs != nil {
for _, v := range req.AdditionalSANs {
_ = writer.WriteField("additionalSANs", v)
}
}
if req.InitConfiguration != "" {
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
}
if req.ClusterConfiguration != "" {
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
}
if req.KubeletConfiguration != "" {
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
}
if req.KubeProxyConfiguration != "" {
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
}
if req.JoinConfiguration != "" {
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
}
if req.Description != "" {
_ = writer.WriteField("desc", req.Description)
}
if req.UserData != "" {
_ = writer.WriteField("userData", req.UserData)
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
_ = writer.WriteField("authkey", token)
ct := writer.FormDataContentType()
writer.Close()
return reqBody, ct
}
func createK8sCloudBrokerLegacy(req k8s_cb.CreateRequest, token string) (*bytes.Buffer, string) {
reqBody := &bytes.Buffer{}
writer := multipart.NewWriter(reqBody)
if req.OidcCertificate != "" {
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
}
_ = writer.WriteField("name", req.Name)
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8CIID, 10))
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
if req.MasterSEPID != 0 {
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
}
if req.MasterSEPPool != "" {
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
}
if req.WorkerSEPID != 0 {
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
}
if req.WorkerSEPPool != "" {
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
}
if req.Labels != nil {
for _, v := range req.Labels {
_ = writer.WriteField("labels", v)
}
}
if req.Taints != nil {
for _, v := range req.Taints {
_ = writer.WriteField("taints", v)
}
}
if req.Annotations != nil {
for _, v := range req.Annotations {
_ = writer.WriteField("annotations", v)
}
}
if req.MasterCPU != 0 {
_ = writer.WriteField("masterCpu", strconv.FormatUint(req.MasterCPU, 10))
}
if req.MasterNum != 0 {
_ = writer.WriteField("masterNum", strconv.FormatUint(req.MasterNum, 10))
}
if req.MasterRAM != 0 {
_ = writer.WriteField("masterRam", strconv.FormatUint(req.MasterRAM, 10))
}
if req.MasterDisk != 0 {
_ = writer.WriteField("masterDisk", strconv.FormatUint(req.MasterDisk, 10))
}
if req.WorkerCPU != 0 {
_ = writer.WriteField("workerCpu", strconv.FormatUint(req.WorkerCPU, 10))
}
if req.WorkerNum != 0 {
_ = writer.WriteField("workerNum", strconv.FormatUint(req.WorkerNum, 10))
}
if req.WorkerRAM != 0 {
_ = writer.WriteField("workerRam", strconv.FormatUint(req.WorkerRAM, 10))
}
if req.WorkerDisk != 0 {
_ = writer.WriteField("workerDisk", strconv.FormatUint(req.WorkerDisk, 10))
}
if req.ExtNetID != 0 {
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
}
if req.VinsId != 0 {
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
}
if !req.WithLB {
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
}
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
if req.AdditionalSANs != nil {
for _, v := range req.AdditionalSANs {
_ = writer.WriteField("additionalSANs", v)
}
}
if req.InitConfiguration != "" {
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
}
if req.ClusterConfiguration != "" {
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
}
if req.KubeletConfiguration != "" {
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
}
if req.KubeProxyConfiguration != "" {
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
}
if req.JoinConfiguration != "" {
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
}
if req.Description != "" {
_ = writer.WriteField("desc", req.Description)
}
if req.UserData != "" {
_ = writer.WriteField("userData", req.UserData)
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
_ = writer.WriteField("authkey", token)
ct := writer.FormDataContentType()
writer.Close()
return reqBody, ct
} }

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AddUserRequest struct {
// ID of account to add to // ID of account to add to
// Required: true // Required: true
@@ -30,9 +30,7 @@ type AddUserRequest struct {
func (a Account) AddUser(ctx context.Context, req AddUserRequest) (bool, error) { func (a Account) AddUser(ctx context.Context, req AddUserRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/addUser" url := "/cloudapi/account/addUser"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AuditsRequest struct {
// ID of the account // ID of the account
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AuditsRequest struct {
func (a Account) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) { func (a Account) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/audits" url := "/cloudapi/account/audits"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for creating account // CreateRequest struct for creating account
type CreateRequest struct { type CreateRequest struct {
// Display name // Display name
// Required: true // Required: true
@@ -56,9 +56,7 @@ type CreateRequest struct {
func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) { func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/create" url := "/cloudapi/account/create"

View File

@@ -7,7 +7,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for delete account // DeleteRequest struct to delete account
type DeleteRequest struct { type DeleteRequest struct {
// ID of account to delete // ID of account to delete
// Required: true // Required: true
@@ -22,9 +22,7 @@ type DeleteRequest struct {
func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) { func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/delete" url := "/cloudapi/account/delete"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type DeleteUserRequest struct {
// ID of the account // ID of the account
// Required: true // Required: true
@@ -20,16 +20,14 @@ type DeleteUserRequest struct {
// Recursively revoke access rights from owned cloudspaces and vmachines // Recursively revoke access rights from owned cloudspaces and vmachines
// Required: false // Required: false
RecursiveDelete bool `url:"recursivedelete,omitempty" json:"recursivedelete,omitempty"` RecursiveDelete bool `url:"recursivedelete" json:"recursivedelete"`
} }
// DeleteUser revokes user access from the account // DeleteUser revokes user access from the account
func (a Account) DeleteUser(ctx context.Context, req DeleteUserRequest) (bool, error) { func (a Account) DeleteUser(ctx context.Context, req DeleteUserRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/deleteUser" url := "/cloudapi/account/deleteUser"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type DisableEnableRequest struct {
// ID of account // ID of account
// Required: true // Required: true
@@ -19,9 +19,7 @@ type DisableEnableRequest struct {
func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, error) { func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/disable" url := "/cloudapi/account/disable"
@@ -43,9 +41,7 @@ func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, e
func (a Account) Enable(ctx context.Context, req DisableEnableRequest) (bool, error) { func (a Account) Enable(ctx context.Context, req DisableEnableRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/enable" url := "/cloudapi/account/enable"

View File

@@ -48,21 +48,23 @@ func (la ListAccounts) FilterByUserGroupID(userGroupID string) ListAccounts {
func (la ListAccounts) FilterFunc(predicate func(ItemAccount) bool) ListAccounts { func (la ListAccounts) FilterFunc(predicate func(ItemAccount) bool) ListAccounts {
var result ListAccounts var result ListAccounts
for _, acc := range la { for _, acc := range la.Data {
if predicate(acc) { if predicate(acc) {
result = append(result, acc) result.Data = append(result.Data, acc)
} }
} }
result.EntryCount = uint64(len(result.Data))
return result return result
} }
// FindOne returns first found ItemAccount. // FindOne returns first found ItemAccount.
// If none was found, returns an empty struct. // If none was found, returns an empty struct.
func (la ListAccounts) FindOne() ItemAccount { func (la ListAccounts) FindOne() ItemAccount {
if len(la) == 0 { if len(la.Data) == 0 {
return ItemAccount{} return ItemAccount{}
} }
return la[0] return la.Data[0]
} }

View File

@@ -5,68 +5,71 @@ import (
) )
var accounts = ListAccounts{ var accounts = ListAccounts{
ItemAccount{ Data: []ItemAccount{
ACL: []RecordACL{ {
{ ACL: []RecordACL{
IsExplicit: true, {
GUID: "", IsExplicit: true,
Rights: "CXDRAU", GUID: "",
Status: "CONFIRMED", Rights: "CXDRAU",
Type: "U", Status: "CONFIRMED",
UgroupID: "timofey_tkachev_1@decs3o", Type: "U",
UgroupID: "timofey_tkachev_1@decs3o",
},
}, },
CreatedTime: 1676645275,
DeletedTime: 0,
ID: 132846,
Name: "std",
Status: "CONFIRMED",
UpdatedTime: 1676645275,
}, },
CreatedTime: 1676645275, {
DeletedTime: 0, ACL: []RecordACL{
ID: 132846, {
Name: "std", IsExplicit: true,
Status: "CONFIRMED", GUID: "",
UpdatedTime: 1676645275, Rights: "CXDRAU",
}, Status: "CONFIRMED",
ItemAccount{ Type: "U",
ACL: []RecordACL{ UgroupID: "not_really_timofey_tkachev_1@decs3o",
{ },
IsExplicit: true,
GUID: "",
Rights: "CXDRAU",
Status: "CONFIRMED",
Type: "U",
UgroupID: "not_really_timofey_tkachev_1@decs3o",
}, },
CreatedTime: 1676878820,
DeletedTime: 0,
ID: 132847,
Name: "std_2",
Status: "CONFIRMED",
UpdatedTime: 1676645275,
}, },
CreatedTime: 1676878820, {
DeletedTime: 0, ACL: []RecordACL{
ID: 132847, {
Name: "std_2", IsExplicit: true,
Status: "CONFIRMED", GUID: "",
UpdatedTime: 1676645275, Rights: "CXDRAU",
}, Status: "CONFIRMED",
ItemAccount{ Type: "U",
ACL: []RecordACL{ UgroupID: "timofey_tkachev_1@decs3o",
{ },
IsExplicit: true, {
GUID: "", IsExplicit: true,
Rights: "CXDRAU", GUID: "",
Status: "CONFIRMED", Rights: "CXDRAU",
Type: "U", Status: "CONFIRMED",
UgroupID: "timofey_tkachev_1@decs3o", Type: "U",
}, UgroupID: "second_account@decs3o",
{ },
IsExplicit: true,
GUID: "",
Rights: "CXDRAU",
Status: "CONFIRMED",
Type: "U",
UgroupID: "second_account@decs3o",
}, },
CreatedTime: 1676883850,
DeletedTime: 1676883899,
ID: 132848,
Name: "std_broker",
Status: "DELETED",
UpdatedTime: 1676878820,
}, },
CreatedTime: 1676883850,
DeletedTime: 1676883899,
ID: 132848,
Name: "std_broker",
Status: "DELETED",
UpdatedTime: 1676878820,
}, },
EntryCount: 3,
} }
func TestFilterByID(t *testing.T) { func TestFilterByID(t *testing.T) {
@@ -100,11 +103,11 @@ func TestFilterByName(t *testing.T) {
func TestFilterByStatus(t *testing.T) { func TestFilterByStatus(t *testing.T) {
actual := accounts.FilterByStatus("CONFIRMED") actual := accounts.FilterByStatus("CONFIRMED")
if len(actual) != 2 { if len(actual.Data) != 2 {
t.Fatal("Expected 2 elements in slice, found: ", len(actual)) t.Fatal("Expected 2 elements in slice, found: ", len(actual.Data))
} }
for _, item := range actual { for _, item := range actual.Data {
if item.Status != "CONFIRMED" { if item.Status != "CONFIRMED" {
t.Fatal("expected CONFIRMED, found: ", item.Status) t.Fatal("expected CONFIRMED, found: ", item.Status)
} }
@@ -116,7 +119,7 @@ func TestFilterFunc(t *testing.T) {
return ia.DeletedTime == 0 return ia.DeletedTime == 0
}) })
for _, item := range actual { for _, item := range actual.Data {
if item.DeletedTime != 0 { if item.DeletedTime != 0 {
t.Fatal("Expected DeletedTime = 0, found: ", item.DeletedTime) t.Fatal("Expected DeletedTime = 0, found: ", item.DeletedTime)
} }
@@ -126,21 +129,21 @@ func TestFilterFunc(t *testing.T) {
func TestSortingByCreatedTime(t *testing.T) { func TestSortingByCreatedTime(t *testing.T) {
actual := accounts.SortByCreatedTime(false) actual := accounts.SortByCreatedTime(false)
if actual[0].Name != "std" { if actual.Data[0].Name != "std" {
t.Fatal("Expected account std as earliest, found: ", actual[0].Name) t.Fatal("Expected account std as earliest, found: ", actual.Data[0].Name)
} }
actual = accounts.SortByCreatedTime(true) actual = accounts.SortByCreatedTime(true)
if actual[0].Name != "std_broker" { if actual.Data[0].Name != "std_broker" {
t.Fatal("Expected account std_broker as latest, found: ", actual[0].Name) t.Fatal("Expected account std_broker as latest, found: ", actual.Data[0].Name)
} }
} }
func TestFilterEmpty(t *testing.T) { func TestFilterEmpty(t *testing.T) {
actual := accounts.FilterByID(0) actual := accounts.FilterByID(0)
if len(actual) != 0 { if len(actual.Data) != 0 {
t.Fatal("Expected 0 found, actual: ", len(actual)) t.Fatal("Expected 0 found, actual: ", len(actual.Data))
} }
} }

View File

@@ -8,25 +8,16 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for get information about account // GetRequest struct to get information about account
type GetRequest struct { type GetRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
} }
// Get gets account details // Get gets account details as a RecordAccount struct
func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error) { func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error) {
err := validators.ValidateRequest(req) res, err := a.GetRaw(ctx, req)
if err != nil {
for _, validationError := range validators.GetErrors(err) {
return nil, validators.ValidationError(validationError)
}
}
url := "/cloudapi/account/get"
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -41,3 +32,16 @@ func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error
return &info, nil return &info, nil
} }
// GetRaw gets account details as an array of bytes
func (a Account) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
err := validators.ValidateRequest(req)
if err != nil {
return nil, validators.ValidationErrors(validators.GetErrors(err))
}
url := "/cloudapi/account/get"
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
return res, err
}

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GetConsumedAccountUnitsRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -20,13 +20,12 @@ type GetConsumedAccountUnitsRequest struct {
// - CU_M: consumed memory in MB // - CU_M: consumed memory in MB
// - CU_C: number of cpu cores // - CU_C: number of cpu cores
// - CU_D: consumed vdisk storage in GB // - CU_D: consumed vdisk storage in GB
// - CU_DM: consumed max vdisk storage in GB
// - CU_I: number of public IPs // - CU_I: number of public IPs
func (a Account) GetConsumedAccountUnits(ctx context.Context, req GetConsumedAccountUnitsRequest) (*ResourceLimits, error) { func (a Account) GetConsumedAccountUnits(ctx context.Context, req GetConsumedAccountUnitsRequest) (*ResourceLimits, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/getConsumedAccountUnits" url := "/cloudapi/account/getConsumedAccountUnits"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GetConsumedCloudUnitsByTypeRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -26,6 +26,7 @@ type GetConsumedCloudUnitsByTypeRequest struct {
// - CU_M: returns consumed memory in MB // - CU_M: returns consumed memory in MB
// - CU_C: returns number of virtual cpu cores // - CU_C: returns number of virtual cpu cores
// - CU_D: returns consumed virtual disk storage in GB // - CU_D: returns consumed virtual disk storage in GB
// - CU_DM: returns consumed max virtual disk storage in GB
// - CU_S: returns consumed primary storage (NAS) in TB // - CU_S: returns consumed primary storage (NAS) in TB
// - CU_A: returns consumed secondary storage (Archive) in TB // - CU_A: returns consumed secondary storage (Archive) in TB
// - CU_NO: returns sent/received network transfer in operator in GB // - CU_NO: returns sent/received network transfer in operator in GB
@@ -34,9 +35,7 @@ type GetConsumedCloudUnitsByTypeRequest struct {
func (a Account) GetConsumedCloudUnitsByType(ctx context.Context, req GetConsumedCloudUnitsByTypeRequest) (float64, error) { func (a Account) GetConsumedCloudUnitsByType(ctx context.Context, req GetConsumedCloudUnitsByTypeRequest) (float64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/getConsumedCloudUnitsByType" url := "/cloudapi/account/getConsumedCloudUnitsByType"

View File

@@ -7,7 +7,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for download the resources tracking files for an account // GetConsumptionRequest struct to download the resources tracking files for an account
type GetConsumptionRequest struct { type GetConsumptionRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -26,9 +26,7 @@ type GetConsumptionRequest struct {
func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) { func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return "", validators.ValidationErrors(validators.GetErrors(err))
return "", validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/getConsumption" url := "/cloudapi/account/getConsumption"
@@ -46,9 +44,7 @@ func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest)
func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) { func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return "", validators.ValidationErrors(validators.GetErrors(err))
return "", validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/getConsumption" url := "/cloudapi/account/getConsumption"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GetReservedAccountUnitsRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -21,13 +21,12 @@ type GetReservedAccountUnitsRequest struct {
// - CU_M: reserved memory in MB // - CU_M: reserved memory in MB
// - CU_C: number of cpu cores // - CU_C: number of cpu cores
// - CU_D: reserved vdisk storage in GB // - CU_D: reserved vdisk storage in GB
// - CU_DM: reserved max vdisk storage in GB
// - CU_I: number of public IPs // - CU_I: number of public IPs
func (a Account) GetReservedAccountUnits(ctx context.Context, req GetReservedAccountUnitsRequest) (*ResourceLimits, error) { func (a Account) GetReservedAccountUnits(ctx context.Context, req GetReservedAccountUnitsRequest) (*ResourceLimits, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/getReservedAccountUnits" url := "/cloudapi/account/getReservedAccountUnits"

View File

@@ -0,0 +1,40 @@
package account
import (
"context"
"encoding/json"
"net/http"
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
)
// GetResourceConsumptionRequest struct to get resource consumption
type GetResourceConsumptionRequest struct {
// ID an account
// Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
}
// GetResourceConsumption show amount of consumed and reserved resources (cpu, ram, disk) by specific account
func (a Account) GetResourceConsumption(ctx context.Context, req GetResourceConsumptionRequest) (*RecordResourceConsumption, error) {
err := validators.ValidateRequest(req)
if err != nil {
return nil, validators.ValidationErrors(validators.GetErrors(err))
}
url := "/cloudapi/account/getResourceConsumption"
info := RecordResourceConsumption{}
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
err = json.Unmarshal(res, &info)
if err != nil {
return nil, err
}
return &info, nil
}

View 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
}

View File

@@ -6,22 +6,36 @@ import (
"net/http" "net/http"
) )
// Request struct for get list of accounts // ListRequest struct to get list of accounts
type ListRequest struct { 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 access control list
// Required: false
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
// Find by status
// Required: false
Status string `url:"status,omitempty" json:"status,omitempty"`
// Page number // Page number
// Required: false // Required: false
Page uint64 `url:"page" json:"page"` Page uint64 `url:"page,omitempty" json:"page,omitempty"`
// Page size // Page size
// Required: false // Required: false
Size uint64 `url:"size" json:"size"` Size uint64 `url:"size,omitempty" json:"size,omitempty"`
} }
// List gets list all accounts the user has access to // 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) { func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
url := "/cloudapi/account/list" res, err := a.ListRaw(ctx, req)
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -33,5 +47,13 @@ func (a Account) List(ctx context.Context, req ListRequest) (ListAccounts, error
return nil, err return nil, err
} }
return list, nil return &list, nil
}
// 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) {
url := "/cloudapi/account/list"
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
return res, err
} }

View File

@@ -8,20 +8,58 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListComputesRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// Find by compute id
// Required: false
ComputeID uint64 `url:"computeId,omitempty" json:"computeId,omitempty"`
// Find by name
// Required: false
Name string `url:"name,omitempty" json:"name,omitempty"`
// Find by resource group name
// Required: false
RGName string `url:"rgName,omitempty" json:"rgName,omitempty"`
// Find by resource group id
// Required: false
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
// Find by tech status
// Required: false
TechStatus string `url:"techStatus,omitempty" json:"techStatus,omitempty"`
// Find by ip address
// Required: false
IPAddress string `url:"ipAddress,omitempty" json:"ipAddress,omitempty"`
// Find by external network name
// Required: false
ExtNetName string `url:"extNetName,omitempty" json:"extNetName,omitempty"`
// Find by external network id
// Required: false
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,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"`
} }
// ListComputes gets list all compute instances under specified account, accessible by the user // ListComputes gets list all compute instances under specified account, accessible by the user
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (ListComputes, error) { func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listComputes" url := "/cloudapi/account/listComputes"
@@ -38,5 +76,5 @@ func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (Lis
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -6,19 +6,31 @@ import (
"net/http" "net/http"
) )
// Request struct for get list deleted accounts // ListDeletedRequest struct to get a list of deleted accounts
type ListDeletedRequest struct { type ListDeletedRequest struct {
// Page number // Page number
// Required: false // Required: false
Page uint64 `url:"page" json:"page"` Page uint64 `url:"page,omitempty" json:"page,omitempty"`
// Page size // Page size
// Required: false // Required: false
Size uint64 `url:"size" json:"size"` Size uint64 `url:"size,omitempty" json:"size,omitempty"`
// 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 access control list
// Required: false
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
} }
// 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) { func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
url := "/cloudapi/account/listDeleted" url := "/cloudapi/account/listDeleted"
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req) res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
@@ -33,5 +45,5 @@ func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (ListA
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -8,20 +8,42 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListDisksRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// Find by disk id
// Required: false
DiskID uint64 `url:"diskId,omitempty" json:"diskId,omitempty"`
// Find by name
// Required: false
Name string `url:"name,omitempty" json:"name,omitempty"`
// Find by max size disk
// Required: false
DiskMaxSize uint64 `url:"diskMaxSize,omitempty" json:"diskMaxSize,omitempty"`
// Type of the disks
// Required: false
Type string `url:"type,omitempty" json:"type,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"`
} }
// ListDisks gets list all currently unattached disks under specified account // ListDisks gets list all currently unattached disks under specified account
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (ListDisks, error) { func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listDisks" url := "/cloudapi/account/listDisks"
@@ -38,5 +60,5 @@ func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (ListDisks
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -8,20 +8,50 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListFLIPGroupsRequest struct {
// ID an account // ID of the account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// 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 external network id
// Required: false
ExtNetID uint64 `url:"extnetId,omitempty" json:"extnetId,omitempty"`
// Find by IP
// Required: false
ByIP string `url:"byIp,omitempty" json:"byIp,omitempty"`
// Find by flipGroup Id
// Required: false
FLIPGroupID uint64 `url:"flipGroupId,omitempty" json:"flipGroupId,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"`
} }
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user // ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (ListFLIPGroups, error) { func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listFlipGroups" url := "/cloudapi/account/listFlipGroups"
@@ -38,5 +68,5 @@ func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest)
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -0,0 +1,26 @@
package account
import (
"context"
"encoding/json"
"net/http"
)
// ListResourceConsumption show data list amount of consumed and reserved resources (cpu, ram, disk) by specific accounts
func (a Account) ListResourceConsumption(ctx context.Context) (*ListResourceConsumption, error) {
url := "/cloudapi/account/listResourceConsumption"
info := ListResourceConsumption{}
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, nil)
if err != nil {
return nil, err
}
err = json.Unmarshal(res, &info)
if err != nil {
return nil, err
}
return &info, nil
}

View File

@@ -8,20 +8,46 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListRGRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// Page number
// Required: false
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
// Page size
// Required: false
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
// Find by resource group id
// Required: false
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
// 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 VM ID
// Required: false
VMID uint64 `url:"vmId,omitempty" json:"vmId,omitempty"`
// Find by status
// Required: false
Status string `url:"status,omitempty" json:"status,omitempty"`
} }
// 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) { func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listRG" url := "/cloudapi/account/listRG"
@@ -38,5 +64,5 @@ func (a Account) ListRG(ctx context.Context, req ListRGRequest) (ListRG, error)
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -8,24 +8,42 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListTemplatesRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// Include deleted images // Include deleted images
// Required: false // Required: false
IncludeDeleted bool `url:"includedeleted" json:"includedeleted"` IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
// Find by image id
// Required: false
ImageID uint64 `url:"imageId,omitempty" json:"imageId,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"`
// Page number
// Required: false
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
// Page size
// Required: false
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) { func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listTemplates" url := "/cloudapi/account/listTemplates"
@@ -42,5 +60,5 @@ func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (L
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -8,20 +8,42 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type ListVINSRequest struct {
// ID an account // ID an account
// Required: true // Required: true
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"` AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
// Find by VINS ID
// Required: false
VINSID uint64 `url:"vins,omitempty" json:"vinsId,omitempty"`
// Find by name
// Required: false
Name string `url:"name,omitempty" json:"name,omitempty"`
// Find by resource group id
// Required: false
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
// Find by external network ip
// Required: false
ExtIP string `url:"extIp,omitempty" json:"extIp,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"`
} }
// 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) { func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/listVins" url := "/cloudapi/account/listVins"
@@ -38,5 +60,5 @@ func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (ListVINS, e
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -32,6 +32,9 @@ type ResourceLimits struct {
// Disk size, GB // Disk size, GB
CUD float64 `json:"CU_D"` CUD float64 `json:"CU_D"`
// Max disk size, GB
CUDM float64 `json:"CU_DM"`
// Number of public IP addresses // Number of public IP addresses
CUI float64 `json:"CU_I"` CUI float64 `json:"CU_I"`
@@ -70,7 +73,11 @@ type ItemAccount struct {
} }
// List of accounts // List of accounts
type ListAccounts []ItemAccount type ListAccounts struct {
Data []ItemAccount `json:"data"`
EntryCount uint64 `json:"entryCount"`
}
// Resources used // Resources used
type Resource struct { type Resource struct {
@@ -81,7 +88,7 @@ type Resource struct {
DiskSize float64 `json:"disksize"` DiskSize float64 `json:"disksize"`
// Max disk size // Max disk size
DiskSizeMax uint64 `json:"disksizemax"` DiskSizeMax float64 `json:"disksizemax"`
// Number of External IPs // Number of External IPs
ExtIPs int64 `json:"extips"` ExtIPs int64 `json:"extips"`
@@ -105,16 +112,33 @@ type DiskUsage struct {
DiskSize float64 `json:"disksize"` DiskSize float64 `json:"disksize"`
// Disk size max // Disk size max
DiskSizeMax uint64 `json:"disksizemax"` DiskSizeMax float64 `json:"disksizemax"`
}
// Information about resource consumption
type RecordResourceConsumption struct {
ItemResourceConsumption
// Resource limits
ResourceLimits ResourceLimits `json:"resourceLimits"`
} }
// Information about resources // Information about resources
type Resources struct { type ItemResourceConsumption struct {
// Current information about resources // Current information about resources
Current Resource `json:"Current"` Consumed Resource `json:"consumed"`
// Reserved information about resources // Reserved information about resources
Reserved Resource `json:"Reserved"` Reserved Resource `json:"reserved"`
// Account ID
AccountID uint64 `json:"id"`
}
type ListResourceConsumption struct {
Data []ItemResourceConsumption `json:"data"`
EntryCount uint64 `json:"entryCount"`
} }
// Information about computes // Information about computes
@@ -140,9 +164,6 @@ type RecordAccount struct {
// DCLocation // DCLocation
DCLocation string `json:"DCLocation"` DCLocation string `json:"DCLocation"`
// Resources
Resources Resources `json:"Resources"`
// CKey // CKey
CKey string `json:"_ckey"` CKey string `json:"_ckey"`
@@ -286,7 +307,13 @@ type ItemCompute struct {
} }
// List of computes // List of computes
type ListComputes []ItemCompute type ListComputes struct {
// Data
Data []ItemCompute `json:"data"`
// Entry count
EntryCount uint64 `json:"entryCount"`
}
// Main information about disk // Main information about disk
type ItemDisk struct { type ItemDisk struct {
@@ -313,7 +340,13 @@ type ItemDisk struct {
} }
// List of disks // List of disks
type ListDisks []ItemDisk type ListDisks struct {
// Data
Data []ItemDisk `json:"data"`
// Entry count
EntryCount uint64 `json:"entryCount"`
}
// Main information about VINS // Main information about VINS
type ItemVINS struct { type ItemVINS struct {
@@ -370,7 +403,13 @@ type ItemVINS struct {
} }
// List of VINS // List of VINS
type ListVINS []ItemVINS type ListVINS struct {
// Data
Data []ItemVINS `json:"data"`
// Entry count
EntryCount uint64 `json:"entryCount"`
}
// Main info about audit // Main info about audit
type ItemAudit struct { type ItemAudit struct {
@@ -484,7 +523,13 @@ type ItemRG struct {
} }
// List of Resource groups // List of Resource groups
type ListRG []ItemRG type ListRG struct {
// Data
Data []ItemRG `json:"data"`
// Enrtry count
EntryCount uint64 `json:"entryCount"`
}
// Main information about template // Main information about template
type ItemTemplate struct { type ItemTemplate struct {
@@ -520,7 +565,13 @@ type ItemTemplate struct {
} }
// List of templates // List of templates
type ListTemplates []ItemTemplate type ListTemplates struct {
// Data
Data []ItemTemplate `json:"data"`
// Entry count
EntryCount uint64 `json:"entryCount"`
}
// Main information about FLIPGroup // Main information about FLIPGroup
type ItemFLIPGroup struct { type ItemFLIPGroup struct {
@@ -589,4 +640,10 @@ type ItemFLIPGroup struct {
} }
// List of FLIPGroups // List of FLIPGroups
type ListFLIPGroups []ItemFLIPGroup type ListFLIPGroups struct {
// Data
Data []ItemFLIPGroup `json:"data"`
// Entry count
EntryCount uint64 `json:"entryCount"`
}

View File

@@ -6,7 +6,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type RestoreRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -17,9 +17,7 @@ type RestoreRequest struct {
func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) { func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/restore" url := "/cloudapi/account/restore"

View File

@@ -12,7 +12,7 @@ import (
// - First argument -> prefix // - First argument -> prefix
// - Second argument -> indent // - Second argument -> indent
func (la ListAccounts) Serialize(params ...string) (serialization.Serialized, error) { func (la ListAccounts) Serialize(params ...string) (serialization.Serialized, error) {
if len(la) == 0 { if len(la.Data) == 0 {
return []byte{}, nil return []byte{}, nil
} }

View File

@@ -6,16 +6,16 @@ import "sort"
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (la ListAccounts) SortByCreatedTime(inverse bool) ListAccounts { func (la ListAccounts) SortByCreatedTime(inverse bool) ListAccounts {
if len(la) < 2 { if len(la.Data) < 2 {
return la return la
} }
sort.Slice(la, func(i, j int) bool { sort.Slice(la.Data, func(i, j int) bool {
if inverse { if inverse {
return la[i].CreatedTime > la[j].CreatedTime return la.Data[i].CreatedTime > la.Data[j].CreatedTime
} }
return la[i].CreatedTime < la[j].CreatedTime return la.Data[i].CreatedTime < la.Data[j].CreatedTime
}) })
return la return la
@@ -25,16 +25,16 @@ func (la ListAccounts) SortByCreatedTime(inverse bool) ListAccounts {
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (la ListAccounts) SortByUpdatedTime(inverse bool) ListAccounts { func (la ListAccounts) SortByUpdatedTime(inverse bool) ListAccounts {
if len(la) < 2 { if len(la.Data) < 2 {
return la return la
} }
sort.Slice(la, func(i, j int) bool { sort.Slice(la.Data, func(i, j int) bool {
if inverse { if inverse {
return la[i].UpdatedTime > la[j].UpdatedTime return la.Data[i].UpdatedTime > la.Data[j].UpdatedTime
} }
return la[i].UpdatedTime < la[j].UpdatedTime return la.Data[i].UpdatedTime < la.Data[j].UpdatedTime
}) })
return la return la
@@ -44,16 +44,16 @@ func (la ListAccounts) SortByUpdatedTime(inverse bool) ListAccounts {
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (la ListAccounts) SortByDeletedTime(inverse bool) ListAccounts { func (la ListAccounts) SortByDeletedTime(inverse bool) ListAccounts {
if len(la) < 2 { if len(la.Data) < 2 {
return la return la
} }
sort.Slice(la, func(i, j int) bool { sort.Slice(la.Data, func(i, j int) bool {
if inverse { if inverse {
return la[i].DeletedTime > la[j].DeletedTime return la.Data[i].DeletedTime > la.Data[j].DeletedTime
} }
return la[i].DeletedTime < la[j].DeletedTime return la.Data[i].DeletedTime < la.Data[j].DeletedTime
}) })
return la return la

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for updaate account // UpdateRequest struct to update account
type UpdateRequest struct { type UpdateRequest struct {
// ID an account // ID an account
// Required: true // Required: true
@@ -51,9 +51,7 @@ type UpdateRequest struct {
func (a Account) Update(ctx context.Context, req UpdateRequest) (bool, error) { func (a Account) Update(ctx context.Context, req UpdateRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/update" url := "/cloudapi/account/update"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type UpdateUserRequest struct {
// ID of the account // ID of the account
// Required: true // Required: true
@@ -30,9 +30,7 @@ type UpdateUserRequest struct {
func (a Account) UpdateUser(ctx context.Context, req UpdateUserRequest) (bool, error) { func (a Account) UpdateUser(ctx context.Context, req UpdateUserRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/account/updateUser" url := "/cloudapi/account/updateUser"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for BasicService // CreateRequest struct for BasicService
type CreateRequest struct { type CreateRequest struct {
// Name of the service // Name of the service
// Required: true // Required: true
@@ -31,9 +31,7 @@ type CreateRequest struct {
func (b BService) Create(ctx context.Context, req CreateRequest) (uint64, error) { func (b BService) Create(ctx context.Context, req CreateRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/create" url := "/cloudapi/bservice/create"

View File

@@ -8,11 +8,11 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for delete basic service // DeleteRequest struct to delete basic service
type DeleteRequest struct { type DeleteRequest struct {
// ID of the BasicService to be delete // ID of the BasicService to be delete
// Required: true // 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 // If set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately
// Required: false // Required: false
@@ -23,9 +23,7 @@ type DeleteRequest struct {
func (b BService) Delete(ctx context.Context, req DeleteRequest) (bool, error) { func (b BService) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/delete" url := "/cloudapi/bservice/delete"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for disable service // DisableRequest struct for disable service
type DisableRequest struct { type DisableRequest struct {
// ID of the service to disable // ID of the service to disable
// Required: true // Required: true
@@ -21,12 +21,10 @@ type DisableRequest struct {
func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error) { func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/delete" url := "/cloudapi/bservice/disable"
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req) res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil { if err != nil {

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for disable service // EnableRequest struct to disable service
type EnableRequest struct { type EnableRequest struct {
// ID of the service to enable // ID of the service to enable
// Required: true // Required: true
@@ -22,9 +22,7 @@ type EnableRequest struct {
func (b BService) Enable(ctx context.Context, req EnableRequest) (bool, error) { func (b BService) Enable(ctx context.Context, req EnableRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/enable" url := "/cloudapi/bservice/enable"

View File

@@ -49,21 +49,23 @@ func (lbs ListBasicServices) FilterByTechStatus(techStatus string) ListBasicServ
func (lbs ListBasicServices) FilterFunc(predicate func(ItemBasicService) bool) ListBasicServices { func (lbs ListBasicServices) FilterFunc(predicate func(ItemBasicService) bool) ListBasicServices {
var result ListBasicServices var result ListBasicServices
for _, item := range lbs { for _, item := range lbs.Data {
if predicate(item) { if predicate(item) {
result = append(result, item) result.Data = append(result.Data, item)
} }
} }
result.EntryCount = uint64(len(lbs.Data))
return result return result
} }
// FindOne returns first found ItemBasicService // FindOne returns first found ItemBasicService
// If none was found, returns an empty struct. // If none was found, returns an empty struct.
func (lbs ListBasicServices) FindOne() ItemBasicService { func (lbs ListBasicServices) FindOne() ItemBasicService {
if len(lbs) == 0 { if lbs.EntryCount == 0 {
return ItemBasicService{} return ItemBasicService{}
} }
return lbs[0] return lbs.Data[0]
} }

View File

@@ -3,78 +3,81 @@ package bservice
import "testing" import "testing"
var bservices = ListBasicServices{ var bservices = ListBasicServices{
{ Data: []ItemBasicService{
AccountID: 1, {
AccountName: "std_1", AccountID: 1,
BaseDomain: "", AccountName: "std_1",
CreatedBy: "sample_user_1@decs3o", BaseDomain: "",
CreatedTime: 1677743675, CreatedBy: "sample_user_1@decs3o",
DeletedBy: "", CreatedTime: 1677743675,
DeletedTime: 0, DeletedBy: "",
GID: 212, DeletedTime: 0,
Groups: []uint64{}, GID: 212,
GUID: 1, Groups: []uint64{},
ID: 1, GUID: 1,
Name: "bservice_1", ID: 1,
ParentSrvID: 0, Name: "bservice_1",
ParentSrvType: "", ParentSrvID: 0,
RGID: 7971, ParentSrvType: "",
RGName: "rg_1", RGID: 7971,
SSHUser: "", RGName: "rg_1",
Status: "CREATED", SSHUser: "",
TechStatus: "STOPPED", Status: "CREATED",
UpdatedBy: "", TechStatus: "STOPPED",
UpdatedTime: 0, UpdatedBy: "",
UserManaged: true, UpdatedTime: 0,
}, UserManaged: true,
{ },
AccountID: 2, {
AccountName: "std_2", AccountID: 2,
BaseDomain: "", AccountName: "std_2",
CreatedBy: "sample_user_1@decs3o", BaseDomain: "",
CreatedTime: 1677743736, CreatedBy: "sample_user_1@decs3o",
DeletedBy: "", CreatedTime: 1677743736,
DeletedTime: 0, DeletedBy: "",
GID: 212, DeletedTime: 0,
Groups: []uint64{}, GID: 212,
GUID: 2, Groups: []uint64{},
ID: 2, GUID: 2,
Name: "bservice_2", ID: 2,
ParentSrvID: 0, Name: "bservice_2",
ParentSrvType: "", ParentSrvID: 0,
RGID: 7972, ParentSrvType: "",
RGName: "rg_2", RGID: 7972,
SSHUser: "", RGName: "rg_2",
Status: "CREATED", SSHUser: "",
TechStatus: "STOPPED", Status: "CREATED",
UpdatedBy: "", TechStatus: "STOPPED",
UpdatedTime: 0, UpdatedBy: "",
UserManaged: true, UpdatedTime: 0,
}, UserManaged: true,
{ },
AccountID: 3, {
AccountName: "std_3", AccountID: 3,
BaseDomain: "", AccountName: "std_3",
CreatedBy: "sample_user_2@decs3o", BaseDomain: "",
CreatedTime: 1677743830, CreatedBy: "sample_user_2@decs3o",
DeletedBy: "", CreatedTime: 1677743830,
DeletedTime: 0, DeletedBy: "",
GID: 212, DeletedTime: 0,
Groups: []uint64{}, GID: 212,
GUID: 3, Groups: []uint64{},
ID: 3, GUID: 3,
Name: "bservice_3", ID: 3,
ParentSrvID: 0, Name: "bservice_3",
ParentSrvType: "", ParentSrvID: 0,
RGID: 7973, ParentSrvType: "",
RGName: "rg_3", RGID: 7973,
SSHUser: "", RGName: "rg_3",
Status: "ENABLED", SSHUser: "",
TechStatus: "STARTED", Status: "ENABLED",
UpdatedBy: "", TechStatus: "STARTED",
UpdatedTime: 0, UpdatedBy: "",
UserManaged: true, UpdatedTime: 0,
UserManaged: true,
},
}, },
EntryCount: 3,
} }
func TestFilterByID(t *testing.T) { func TestFilterByID(t *testing.T) {
@@ -104,11 +107,11 @@ func TestFilterByRGID(t *testing.T) {
func TestFilterByStatus(t *testing.T) { func TestFilterByStatus(t *testing.T) {
actual := bservices.FilterByStatus("CREATED") actual := bservices.FilterByStatus("CREATED")
if len(actual) != 2 { if len(actual.Data) != 2 {
t.Fatal("expected 2 found, actual: ", len(actual)) t.Fatal("expected 2 found, actual: ", len(actual.Data))
} }
for _, item := range actual { for _, item := range actual.Data {
if item.Status != "CREATED" { if item.Status != "CREATED" {
t.Fatal("expected Status 'CREATED', found: ", item.Status) t.Fatal("expected Status 'CREATED', found: ", item.Status)
} }
@@ -118,11 +121,11 @@ func TestFilterByStatus(t *testing.T) {
func TestFilterByTechStatus(t *testing.T) { func TestFilterByTechStatus(t *testing.T) {
actual := bservices.FilterByTechStatus("STOPPED") actual := bservices.FilterByTechStatus("STOPPED")
if len(actual) != 2 { if len(actual.Data) != 2 {
t.Fatal("expected 2 found, actual: ", len(actual)) t.Fatal("expected 2 found, actual: ", len(actual.Data))
} }
for _, item := range actual { for _, item := range actual.Data {
if item.TechStatus != "STOPPED" { if item.TechStatus != "STOPPED" {
t.Fatal("expected TechStatus 'STOPPED', found: ", item.TechStatus) t.Fatal("expected TechStatus 'STOPPED', found: ", item.TechStatus)
} }
@@ -134,8 +137,8 @@ func TestFilterFunc(t *testing.T) {
return ibs.CreatedBy == "sample_user_2@decs3o" return ibs.CreatedBy == "sample_user_2@decs3o"
}) })
if len(actual) > 1 { if len(actual.Data) > 1 {
t.Fatal("expected 1 found, actual: ", len(actual)) t.Fatal("expected 1 found, actual: ", len(actual.Data))
} }
if actual.FindOne().CreatedBy != "sample_user_2@decs3o" { if actual.FindOne().CreatedBy != "sample_user_2@decs3o" {
@@ -146,7 +149,7 @@ func TestFilterFunc(t *testing.T) {
func TestSortByCreatedTime(t *testing.T) { func TestSortByCreatedTime(t *testing.T) {
actual := bservices.SortByCreatedTime(true) actual := bservices.SortByCreatedTime(true)
if actual[0].CreatedTime != 1677743830 || actual[2].CreatedTime != 1677743675 { if actual.Data[0].CreatedTime != 1677743830 || actual.Data[2].CreatedTime != 1677743675 {
t.Fatal("expected descending order, found ascending") t.Fatal("expected descending order, found ascending")
} }
} }

View File

@@ -8,35 +8,39 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for get detailed information about service // GetRequest struct to get detailed information about service
type GetRequest struct { type GetRequest struct {
// ID of the service to query information // ID of the service to query information
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
} }
// Get gets detailed specifications for the BasicService. // Get gets detailed specifications for the BasicService as a RecordBasicService struct
func (b BService) Get(ctx context.Context, req GetRequest) (*RecordBasicService, error) { func (b BService) Get(ctx context.Context, req GetRequest) (*RecordBasicService, error) {
err := validators.ValidateRequest(req) res, err := b.GetRaw(ctx, req)
if err != nil {
for _, validationError := range validators.GetErrors(err) {
return nil, validators.ValidationError(validationError)
}
}
url := "/cloudapi/bservice/get"
bsRaw, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info := RecordBasicService{} info := RecordBasicService{}
err = json.Unmarshal(bsRaw, &info) err = json.Unmarshal(res, &info)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &info, nil return &info, nil
} }
// GetRaw gets detailed specifications for the BasicService as an array of bytes
func (b BService) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
err := validators.ValidateRequest(req)
if err != nil {
return nil, validators.ValidationErrors(validators.GetErrors(err))
}
url := "/cloudapi/bservice/get"
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
return res, err
}

View File

@@ -8,42 +8,42 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupAddRequest struct {
// ID of the Basic Service to add a group to // ID of the Basic Service to add a group to
// Required: true // 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 // Name of the Compute Group to add
// Required: true // 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 // Computes number. Defines how many computes must be there in the group
// Required: true // 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 // Compute CPU number. All computes in the group have the same CPU count
// Required: true // 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 // Compute RAM volume in MB. All computes in the group have the same RAM volume
// Required: true // Required: true
RAM uint64 `url:"ram" json:"ram" validate:"required"` RAM uint64 `url:"ram" json:"ram" validate:"required"`
// Compute boot disk size in GB // Compute boot disk size in GB
// Required: true // 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 // OS image ID to create computes from
// Required: true // Required: true
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"` ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
// Compute driver // Compute driver
// should be one of: // should be one of:
// - KVM_X86 // - KVM_X86
// - KVM_PPC // - KVM_PPC
// Required: true // Required: true
Driver string `url:"driver" json:"driver" validate:"driver"` Driver string `url:"driver" json:"driver" validate:"driver"`
// Storage endpoint provider ID // Storage endpoint provider ID
// Required: false // Required: false
@@ -68,6 +68,10 @@ type GroupAddRequest struct {
// Time of Compute Group readiness // Time of Compute Group readiness
// Required: false // Required: false
TimeoutStart uint64 `url:"timeoutStart,omitempty" json:"timeoutStart,omitempty"` TimeoutStart uint64 `url:"timeoutStart,omitempty" json:"timeoutStart,omitempty"`
// Meta data for working group computes, format YAML "user_data": 1111
// Required: false
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
} }
// GroupAdd creates new Compute Group within BasicService. // GroupAdd creates new Compute Group within BasicService.
@@ -76,9 +80,7 @@ type GroupAddRequest struct {
func (b BService) GroupAdd(ctx context.Context, req GroupAddRequest) (uint64, error) { func (b BService) GroupAdd(ctx context.Context, req GroupAddRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupAdd" url := "/cloudapi/bservice/groupAdd"

View File

@@ -8,11 +8,11 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for remove group compute // GroupComputeRemoveRequest struct to remove group compute
type GroupComputeRemoveRequest struct { type GroupComputeRemoveRequest struct {
// ID of the Basic Service // ID of the Basic Service
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
// ID of the Compute GROUP // ID of the Compute GROUP
// Required: true // Required: true
@@ -27,9 +27,7 @@ type GroupComputeRemoveRequest struct {
func (b BService) GroupComputeRemove(ctx context.Context, req GroupComputeRemoveRequest) (bool, error) { func (b BService) GroupComputeRemove(ctx context.Context, req GroupComputeRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupComputeRemove" url := "/cloudapi/bservice/groupComputeRemove"

View File

@@ -8,11 +8,11 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupGetRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
// ID of the Compute Group // ID of the Compute Group
// Required: true // Required: true
@@ -23,9 +23,7 @@ type GroupGetRequest struct {
func (b BService) GroupGet(ctx context.Context, req GroupGetRequest) (*RecordGroup, error) { func (b BService) GroupGet(ctx context.Context, req GroupGetRequest) (*RecordGroup, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupGet" url := "/cloudapi/bservice/groupGet"

View File

@@ -8,12 +8,11 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for add parent Compute Group relation emove parent Compute Group // GroupParentAddRequest struct to add parent Compute Group relation to the specified Compute Group
// relation to the specified Compute Group
type GroupParentAddRequest struct { type GroupParentAddRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
// ID of the Compute Group // ID of the Compute Group
// Required: true // Required: true
@@ -28,9 +27,7 @@ type GroupParentAddRequest struct {
func (b BService) GroupParentAdd(ctx context.Context, req GroupParentAddRequest) (bool, error) { func (b BService) GroupParentAdd(ctx context.Context, req GroupParentAddRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupParentAdd" url := "/cloudapi/bservice/groupParentAdd"

View File

@@ -8,30 +8,28 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for remove parent Compute Group // GroupParentRemoveRequest struct to remove parent Compute Group
// relation to the specified Compute Group // relation from the specified Compute Group
type GroupParentRemoveRequest struct { type GroupParentRemoveRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
// ID of the Compute Group // ID of the Compute Group
// Required: true // Required: true
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"` CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
// ID of the parent Compute Group // ID of the parent Compute Group
// to remove from the current Compute Group // to remove from the current Compute Group
// Required: true // 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 // GroupParentRemove removes parent Compute Group relation to the specified Compute Group
func (b BService) GroupParentRemove(ctx context.Context, req GroupParentRemoveRequest) (bool, error) { func (b BService) GroupParentRemove(ctx context.Context, req GroupParentRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupParentRemove" url := "/cloudapi/bservice/groupParentRemove"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupRemoveRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
@@ -23,9 +23,7 @@ type GroupRemoveRequest struct {
func (b BService) GroupRemove(ctx context.Context, req GroupRemoveRequest) (bool, error) { func (b BService) GroupRemove(ctx context.Context, req GroupRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupRemove" url := "/cloudapi/bservice/groupRemove"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for resize the group // GroupResizeRequest struct to resize the group
type GroupResizeRequest struct { type GroupResizeRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
@@ -34,9 +34,7 @@ type GroupResizeRequest struct {
func (b BService) GroupResize(ctx context.Context, req GroupResizeRequest) (uint64, error) { func (b BService) GroupResize(ctx context.Context, req GroupResizeRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupResize" url := "/cloudapi/bservice/groupResize"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupStartRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
@@ -23,9 +23,7 @@ type GroupStartRequest struct {
func (b BService) GroupStart(ctx context.Context, req GroupStartRequest) (bool, error) { func (b BService) GroupStart(ctx context.Context, req GroupStartRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupStart" url := "/cloudapi/bservice/groupStart"

View File

@@ -8,15 +8,15 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupStopRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // 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 // ID of the Compute Group to stop
// Required: true // Required: true
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"` CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
// Force stop Compute Group // Force stop Compute Group
// Required: false // Required: false
@@ -27,9 +27,7 @@ type GroupStopRequest struct {
func (b BService) GroupStop(ctx context.Context, req GroupStopRequest) (bool, error) { func (b BService) GroupStop(ctx context.Context, req GroupStopRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupStop" url := "/cloudapi/bservice/groupStop"

View File

@@ -8,15 +8,15 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupUpdateRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"` ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
// ID of the Compute Group // ID of the Compute Group
// Required: true // 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 // Specify non-empty string to update Compute Group name
// Required: false // Required: false
@@ -47,9 +47,7 @@ type GroupUpdateRequest struct {
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) { func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupUpdate" url := "/cloudapi/bservice/groupUpdate"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type GroupUpdateExtNetRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
@@ -27,9 +27,7 @@ type GroupUpdateExtNetRequest struct {
func (b BService) GroupUpdateExtNet(ctx context.Context, req GroupUpdateExtNetRequest) (bool, error) { func (b BService) GroupUpdateExtNet(ctx context.Context, req GroupUpdateExtNetRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupUpdateExtnet" url := "/cloudapi/bservice/groupUpdateExtnet"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for update VINS settings // GroupUpdateVINSRequest struct to update VINS settings
type GroupUpdateVINSRequest struct { type GroupUpdateVINSRequest struct {
// ID of the Basic Service of Compute Group // ID of the Basic Service of Compute Group
// Required: true // Required: true
@@ -27,9 +27,7 @@ type GroupUpdateVINSRequest struct {
func (b BService) GroupUpdateVINS(ctx context.Context, req GroupUpdateVINSRequest) (bool, error) { func (b BService) GroupUpdateVINS(ctx context.Context, req GroupUpdateVINSRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/groupUpdateVins" url := "/cloudapi/bservice/groupUpdateVins"

View 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
}

View File

@@ -6,16 +6,40 @@ import (
"net/http" "net/http"
) )
// Request struct for get list/deleted list BasicService instances // ListRequest struct to get list of BasicService instances
type ListRequest struct { 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"`
// ID of the account to query for BasicService instances // ID of the account to query for BasicService instances
// Required: false // Required: false
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"` AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
// Find by resource group name
// Required: false
RGName string `url:"rgName,omitempty" json:"rgName,omitempty"`
// ID of the resource group to query for BasicService instances // ID of the resource group to query for BasicService instances
// Required: false // Required: false
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"` RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
// Find by tech status
// Required: false
TechStatus string `url:"techStatus,omitempty" json:"techStatus,omitempty"`
// Find by status
// Required: false
Status string `url:"status,omitempty" json:"status,omitempty"`
// Find by account name
// Required: false
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
// Page number // Page number
// Required: false // Required: false
Page uint64 `url:"page,omitempty" json:"page,omitempty"` Page uint64 `url:"page,omitempty" json:"page,omitempty"`
@@ -25,40 +49,27 @@ type ListRequest struct {
Size uint64 `url:"size,omitempty" json:"size,omitempty"` Size uint64 `url:"size,omitempty" json:"size,omitempty"`
} }
// List gets list BasicService instances associated with the specified Resource Group // 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) { func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
res, err := b.ListRaw(ctx, req)
if err != nil {
return nil, err
}
list := ListBasicServices{}
err = json.Unmarshal(res, &list)
if err != nil {
return nil, err
}
return &list, nil
}
// 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) {
url := "/cloudapi/bservice/list" url := "/cloudapi/bservice/list"
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req) res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil { return res, err
return nil, err
}
list := ListBasicServices{}
err = json.Unmarshal(res, &list)
if err != nil {
return nil, err
}
return list, nil
}
// ListDeleted gets list deleted BasicService instances associated with the specified Resource Group
func (b BService) ListDeleted(ctx context.Context, req ListRequest) (ListBasicServices, error) {
url := "/cloudapi/bservice/listDeleted"
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
list := ListBasicServices{}
err = json.Unmarshal(res, &list)
if err != nil {
return nil, err
}
return list, nil
} }

View File

@@ -0,0 +1,45 @@
package bservice
import (
"context"
"encoding/json"
"net/http"
)
// ListDeletedRequest struct to get list of deleted BasicService instances
type ListDeletedRequest struct {
// ID of the account to query for BasicService instances
// Required: false
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
// ID of the resource group to query for BasicService instances
// Required: false
RGID uint64 `url:"rgId,omitempty" json:"rgId,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"`
}
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
url := "/cloudapi/bservice/listDeleted"
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
list := ListBasicServices{}
err = json.Unmarshal(res, &list)
if err != nil {
return nil, err
}
return &list, nil
}

View File

@@ -169,6 +169,15 @@ type ItemSnapshot struct {
} }
// List of Snapshots // List of Snapshots
type ListInfoSnapshots struct {
// Data
Data ListSnapshots `json:"data"`
// EntryCount
EntryCount uint64 `json:"entryCount"`
}
// List of Snapshots inside RecordBasicService
type ListSnapshots []ItemSnapshot type ListSnapshots []ItemSnapshot
// Main information about Group // Main information about Group
@@ -373,4 +382,8 @@ type ItemBasicService struct {
} }
// List of BasicServices // List of BasicServices
type ListBasicServices []ItemBasicService type ListBasicServices struct {
Data []ItemBasicService `json:"data"`
EntryCount uint64 `json:"entryCount"`
}

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for restores BasicService instance // RestoreRequest struct to restore BasicService instance
type RestoreRequest struct { type RestoreRequest struct {
// ID of the BasicService to be restored // ID of the BasicService to be restored
// Required: true // Required: true
@@ -19,9 +19,7 @@ type RestoreRequest struct {
func (b BService) Restore(ctx context.Context, req RestoreRequest) (bool, error) { func (b BService) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/restore" url := "/cloudapi/bservice/restore"

View File

@@ -12,7 +12,7 @@ import (
// - First argument -> prefix // - First argument -> prefix
// - Second argument -> indent // - Second argument -> indent
func (lbs ListBasicServices) Serialize(params ...string) (serialization.Serialized, error) { func (lbs ListBasicServices) Serialize(params ...string) (serialization.Serialized, error) {
if len(lbs) == 0 { if lbs.EntryCount == 0 {
return []byte{}, nil return []byte{}, nil
} }

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for create snapshot // SnapshotCreateRequest struct to create snapshot
type SnapshotCreateRequest struct { type SnapshotCreateRequest struct {
// ID of the Basic Service // ID of the Basic Service
// Required: true // Required: true
@@ -23,9 +23,7 @@ type SnapshotCreateRequest struct {
func (b BService) SnapshotCreate(ctx context.Context, req SnapshotCreateRequest) (bool, error) { func (b BService) SnapshotCreate(ctx context.Context, req SnapshotCreateRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/snapshotCreate" url := "/cloudapi/bservice/snapshotCreate"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for delete snapshot // SnapshotDeleteRequest struct to delete snapshot
type SnapshotDeleteRequest struct { type SnapshotDeleteRequest struct {
// ID of the Basic Service // ID of the Basic Service
// Required: true // Required: true
@@ -23,9 +23,7 @@ type SnapshotDeleteRequest struct {
func (b BService) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) { func (b BService) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/snapshotDelete" url := "/cloudapi/bservice/snapshotDelete"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type SnapshotListRequest struct {
// ID of the Basic Service // ID of the Basic Service
// Required: true // Required: true
@@ -16,12 +16,10 @@ type SnapshotListRequest struct {
} }
// SnapshotList gets list existing snapshots of the Basic Service // 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) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/snapshotList" url := "/cloudapi/bservice/snapshotList"
@@ -31,12 +29,12 @@ func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (Li
return nil, err return nil, err
} }
list := ListSnapshots{} list := ListInfoSnapshots{}
err = json.Unmarshal(res, &list) err = json.Unmarshal(res, &list)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return list, nil return &list, nil
} }

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for rollback snapshot // SnapshotRollbackRequest struct to rollback snapshot
type SnapshotRollbackRequest struct { type SnapshotRollbackRequest struct {
// ID of the Basic Service // ID of the Basic Service
// Required: true // Required: true
@@ -23,9 +23,7 @@ type SnapshotRollbackRequest struct {
func (b BService) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) { func (b BService) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/snapshotRollback" url := "/cloudapi/bservice/snapshotRollback"

View File

@@ -6,16 +6,16 @@ import "sort"
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (lbs ListBasicServices) SortByCreatedTime(inverse bool) ListBasicServices { func (lbs ListBasicServices) SortByCreatedTime(inverse bool) ListBasicServices {
if len(lbs) < 2 { if lbs.EntryCount < 2 {
return lbs return lbs
} }
sort.Slice(lbs, func(i, j int) bool { sort.Slice(lbs.Data, func(i, j int) bool {
if inverse { if inverse {
return lbs[i].CreatedTime > lbs[j].CreatedTime return lbs.Data[i].CreatedTime > lbs.Data[j].CreatedTime
} }
return lbs[i].CreatedTime < lbs[j].CreatedTime return lbs.Data[i].CreatedTime < lbs.Data[j].CreatedTime
}) })
return lbs return lbs
@@ -25,16 +25,16 @@ func (lbs ListBasicServices) SortByCreatedTime(inverse bool) ListBasicServices {
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (lbs ListBasicServices) SortByUpdatedTime(inverse bool) ListBasicServices { func (lbs ListBasicServices) SortByUpdatedTime(inverse bool) ListBasicServices {
if len(lbs) < 2 { if lbs.EntryCount < 2 {
return lbs return lbs
} }
sort.Slice(lbs, func(i, j int) bool { sort.Slice(lbs.Data, func(i, j int) bool {
if inverse { if inverse {
return lbs[i].UpdatedTime > lbs[j].UpdatedTime return lbs.Data[i].UpdatedTime > lbs.Data[j].UpdatedTime
} }
return lbs[i].UpdatedTime < lbs[j].UpdatedTime return lbs.Data[i].UpdatedTime < lbs.Data[j].UpdatedTime
}) })
return lbs return lbs
@@ -44,16 +44,16 @@ func (lbs ListBasicServices) SortByUpdatedTime(inverse bool) ListBasicServices {
// //
// If inverse param is set to true, the order is reversed. // If inverse param is set to true, the order is reversed.
func (lbs ListBasicServices) SortByDeletedTime(inverse bool) ListBasicServices { func (lbs ListBasicServices) SortByDeletedTime(inverse bool) ListBasicServices {
if len(lbs) < 2 { if lbs.EntryCount < 2 {
return lbs return lbs
} }
sort.Slice(lbs, func(i, j int) bool { sort.Slice(lbs.Data, func(i, j int) bool {
if inverse { if inverse {
return lbs[i].DeletedTime > lbs[j].DeletedTime return lbs.Data[i].DeletedTime > lbs.Data[j].DeletedTime
} }
return lbs[i].DeletedTime < lbs[j].DeletedTime return lbs.Data[i].DeletedTime < lbs.Data[j].DeletedTime
}) })
return lbs return lbs

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for start service // StartRequest struct to start service
type StartRequest struct { type StartRequest struct {
// ID of the service to start // ID of the service to start
// Required: true // Required: true
@@ -21,9 +21,7 @@ type StartRequest struct {
func (b BService) Start(ctx context.Context, req StartRequest) (bool, error) { func (b BService) Start(ctx context.Context, req StartRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/start" url := "/cloudapi/bservice/start"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for stop service // StopRequest struct to stop service
type StopRequest struct { type StopRequest struct {
// ID of the service to stop // ID of the service to stop
// Required: true // Required: true
@@ -21,9 +21,7 @@ type StopRequest struct {
func (b BService) Stop(ctx context.Context, req StopRequest) (bool, error) { func (b BService) Stop(ctx context.Context, req StopRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/bservice/stop" url := "/cloudapi/bservice/stop"

View File

@@ -7,7 +7,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AffinityGroupCheckStartRequest struct {
// ID of the resource group // ID of the resource group
// Required: true // Required: true
@@ -22,9 +22,7 @@ type AffinityGroupCheckStartRequest struct {
func (c Compute) AffinityGroupCheckStart(ctx context.Context, req AffinityGroupCheckStartRequest) (string, error) { func (c Compute) AffinityGroupCheckStart(ctx context.Context, req AffinityGroupCheckStartRequest) (string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return "", validators.ValidationErrors(validators.GetErrors(err))
return "", validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityGroupCheckStart" url := "/cloudapi/compute/affinityGroupCheckStart"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AffinityLabelRemoveRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AffinityLabelRemoveRequest struct {
func (c Compute) AffinityLabelRemove(ctx context.Context, req AffinityLabelRemoveRequest) (bool, error) { func (c Compute) AffinityLabelRemove(ctx context.Context, req AffinityLabelRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityLabelRemove" url := "/cloudapi/compute/affinityLabelRemove"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AffinityLabelSetRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -23,9 +23,7 @@ type AffinityLabelSetRequest struct {
func (c Compute) AffinityLabelSet(ctx context.Context, req AffinityLabelSetRequest) (bool, error) { func (c Compute) AffinityLabelSet(ctx context.Context, req AffinityLabelSetRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityLabelSet" url := "/cloudapi/compute/affinityLabelSet"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AffinityRelationsRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AffinityRelationsRequest struct {
func (c Compute) AffinityRelations(ctx context.Context, req AffinityRelationsRequest) (*RecordAffinityRelations, error) { func (c Compute) AffinityRelations(ctx context.Context, req AffinityRelationsRequest) (*RecordAffinityRelations, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityRelations" url := "/cloudapi/compute/affinityRelations"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for add affinity rule // AffinityRuleAddRequest struct to add affinity rule
type AffinityRuleAddRequest struct { type AffinityRuleAddRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -38,17 +38,15 @@ type AffinityRuleAddRequest struct {
Key string `url:"key" json:"key" validate:"required"` Key string `url:"key" json:"key" validate:"required"`
// Value that must match the key to be taken into account when analyzing this rule // Value that must match the key to be taken into account when analyzing this rule
// Required: true // Required: false
Value string `url:"value" json:"value" validate:"required"` Value string `url:"value" json:"value"`
} }
// AffinityRuleAdd add affinity rule // AffinityRuleAdd add affinity rule
func (c Compute) AffinityRuleAdd(ctx context.Context, req AffinityRuleAddRequest) (bool, error) { func (c Compute) AffinityRuleAdd(ctx context.Context, req AffinityRuleAddRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityRuleAdd" url := "/cloudapi/compute/affinityRuleAdd"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for remove affinity rule // AffinityRuleRemoveRequest struct to remove affinity rule
type AffinityRuleRemoveRequest struct { type AffinityRuleRemoveRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -38,17 +38,15 @@ type AffinityRuleRemoveRequest struct {
Key string `url:"key" json:"key" validate:"required"` Key string `url:"key" json:"key" validate:"required"`
// Value that must match the key to be taken into account when analyzing this rule // Value that must match the key to be taken into account when analyzing this rule
// Required: true // Required: false
Value string `url:"value" json:"value" validate:"required"` Value string `url:"value" json:"value"`
} }
// AffinityRuleRemove remove affinity rule // AffinityRuleRemove remove affinity rule
func (c Compute) AffinityRuleRemove(ctx context.Context, req AffinityRuleRemoveRequest) (bool, error) { func (c Compute) AffinityRuleRemove(ctx context.Context, req AffinityRuleRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityRuleRemove" url := "/cloudapi/compute/affinityRuleRemove"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for clear affinity rules // AffinityRulesClearRequest struct to clear affinity rules
type AffinityRulesClearRequest struct { type AffinityRulesClearRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AffinityRulesClearRequest struct {
func (c Compute) AffinityRulesClear(ctx context.Context, req AffinityRulesClearRequest) (bool, error) { func (c Compute) AffinityRulesClear(ctx context.Context, req AffinityRulesClearRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/affinityRulesClear" url := "/cloudapi/compute/affinityRulesClear"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AntiAffinityRuleAddRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -38,17 +38,15 @@ type AntiAffinityRuleAddRequest struct {
Key string `url:"key" json:"key" validate:"required"` Key string `url:"key" json:"key" validate:"required"`
// Value that must match the key to be taken into account when analyzing this rule // Value that must match the key to be taken into account when analyzing this rule
// Required: true // Required: false
Value string `url:"value" json:"value" validate:"required"` Value string `url:"value" json:"value"`
} }
// AntiAffinityRuleAdd add anti affinity rule // AntiAffinityRuleAdd add anti affinity rule
func (c Compute) AntiAffinityRuleAdd(ctx context.Context, req AntiAffinityRuleAddRequest) (bool, error) { func (c Compute) AntiAffinityRuleAdd(ctx context.Context, req AntiAffinityRuleAddRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/antiAffinityRuleAdd" url := "/cloudapi/compute/antiAffinityRuleAdd"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AntiAffinityRuleRemoveRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -38,17 +38,15 @@ type AntiAffinityRuleRemoveRequest struct {
Key string `url:"key" json:"key" validate:"required"` Key string `url:"key" json:"key" validate:"required"`
// Value that must match the key to be taken into account when analyzing this rule // Value that must match the key to be taken into account when analyzing this rule
// Required: true // Required: false
Value string `url:"value" json:"value" validate:"required"` Value string `url:"value" json:"value"`
} }
// AntiAffinityRuleRemove remove anti affinity rule // AntiAffinityRuleRemove remove anti affinity rule
func (c Compute) AntiAffinityRuleRemove(ctx context.Context, req AntiAffinityRuleRemoveRequest) (bool, error) { func (c Compute) AntiAffinityRuleRemove(ctx context.Context, req AntiAffinityRuleRemoveRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/antiAffinityRuleRemove" url := "/cloudapi/compute/antiAffinityRuleRemove"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AntiAffinityRulesClearRequest struct {
// ID of the compute instance // ID of the compute instance
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AntiAffinityRulesClearRequest struct {
func (c Compute) AntiAffinityRulesClear(ctx context.Context, req AntiAffinityRulesClearRequest) (bool, error) { func (c Compute) AntiAffinityRulesClear(ctx context.Context, req AntiAffinityRulesClearRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/antiAffinityRulesClear" url := "/cloudapi/compute/antiAffinityRulesClear"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type AttachGPURequest struct {
// Identifier compute // Identifier compute
// Required: true // Required: true
@@ -23,9 +23,7 @@ type AttachGPURequest struct {
func (c Compute) AttachGPU(ctx context.Context, req AttachGPURequest) (uint64, error) { func (c Compute) AttachGPU(ctx context.Context, req AttachGPURequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/attachGpu" url := "/cloudapi/compute/attachGpu"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for atttach PCI device // AttachPCIDeviceRequest struct to attach PCI device
type AttachPCIDeviceRequest struct { type AttachPCIDeviceRequest struct {
// Identifier compute // Identifier compute
// Required: true // Required: true
@@ -23,9 +23,7 @@ type AttachPCIDeviceRequest struct {
func (c Compute) AttachPCIDevice(ctx context.Context, req AttachPCIDeviceRequest) (bool, error) { func (c Compute) AttachPCIDevice(ctx context.Context, req AttachPCIDeviceRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/attachPciDevice" url := "/cloudapi/compute/attachPciDevice"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for get audit records // AuditsRequest struct to get audit records
type AuditsRequest struct { type AuditsRequest struct {
// ID of the compute // ID of the compute
// Required: true // Required: true
@@ -19,9 +19,7 @@ type AuditsRequest struct {
func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) { func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/audits" url := "/cloudapi/compute/audits"

View File

@@ -7,7 +7,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for getting boot order // BootOrderGetRequest struct to get boot order
type BootOrderGetRequest struct { type BootOrderGetRequest struct {
// Compute ID // Compute ID
// Required: true // Required: true
@@ -18,9 +18,7 @@ type BootOrderGetRequest struct {
func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) { func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/bootOrderGet" url := "/cloudapi/compute/bootOrderGet"

View File

@@ -7,7 +7,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for setting boot order // BootOrderSetRequest struct to set boot order
type BootOrderSetRequest struct { type BootOrderSetRequest struct {
// ID of compute instance // ID of compute instance
// Required: true // Required: true
@@ -26,9 +26,7 @@ type BootOrderSetRequest struct {
func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) { func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return nil, validators.ValidationErrors(validators.GetErrors(err))
return nil, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/bootOrderSet" url := "/cloudapi/compute/bootOrderSet"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for eject CD image // CDEjectRequest struct to eject CD image
type CDEjectRequest struct { type CDEjectRequest struct {
// ID of compute instance // ID of compute instance
// Required: true // Required: true
@@ -19,9 +19,7 @@ type CDEjectRequest struct {
func (c Compute) CDEject(ctx context.Context, req CDEjectRequest) (bool, error) { func (c Compute) CDEject(ctx context.Context, req CDEjectRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/cdEject" url := "/cloudapi/compute/cdEject"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "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 { type CDInsertRequest struct {
// ID of compute instance // ID of compute instance
// Required: true // Required: true
@@ -23,9 +23,7 @@ type CDInsertRequest struct {
func (c Compute) CDInsert(ctx context.Context, req CDInsertRequest) (bool, error) { func (c Compute) CDInsert(ctx context.Context, req CDInsertRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/cdInsert" url := "/cloudapi/compute/cdInsert"

View File

@@ -7,7 +7,7 @@ import (
"strconv" "strconv"
) )
// Request struct for changing link state // ChangeLinkStateRequest struct to change link state
type ChangeLinkStateRequest struct { type ChangeLinkStateRequest struct {
// Compute ID // Compute ID
// Required: true // Required: true
@@ -27,9 +27,7 @@ type ChangeLinkStateRequest struct {
func (c Compute) ChangeLinkState(ctx context.Context, req ChangeLinkStateRequest) (bool, error) { func (c Compute) ChangeLinkState(ctx context.Context, req ChangeLinkStateRequest) (bool, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return false, validators.ValidationErrors(validators.GetErrors(err))
return false, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/changeLinkState" url := "/cloudapi/compute/changeLinkState"

View File

@@ -8,7 +8,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for clone compute instance // CloneRequest struct to clone compute instance
type CloneRequest struct { type CloneRequest struct {
// ID of compute instance // ID of compute instance
// Required: true // Required: true
@@ -31,9 +31,7 @@ type CloneRequest struct {
func (c Compute) Clone(ctx context.Context, req CloneRequest) (uint64, error) { func (c Compute) Clone(ctx context.Context, req CloneRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
url := "/cloudapi/compute/clone" url := "/cloudapi/compute/clone"

View File

@@ -9,7 +9,7 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators" "repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
) )
// Request struct for create template // CreateTemplateRequest struct to create template
type CreateTemplateRequest struct { type CreateTemplateRequest struct {
// ID of the compute to create template from // ID of the compute to create template from
// Required: true // Required: true
@@ -30,9 +30,7 @@ type wrapperCreateTemplateRequest struct {
func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (uint64, error) { func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (uint64, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return 0, validators.ValidationErrors(validators.GetErrors(err))
return 0, validators.ValidationError(validationError)
}
} }
reqWrapped := wrapperCreateTemplateRequest{ reqWrapped := wrapperCreateTemplateRequest{
@@ -59,9 +57,7 @@ func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest)
func (c Compute) CreateTemplateAsync(ctx context.Context, req CreateTemplateRequest) (string, error) { func (c Compute) CreateTemplateAsync(ctx context.Context, req CreateTemplateRequest) (string, error) {
err := validators.ValidateRequest(req) err := validators.ValidateRequest(req)
if err != nil { if err != nil {
for _, validationError := range validators.GetErrors(err) { return "", validators.ValidationErrors(validators.GetErrors(err))
return "", validators.ValidationError(validationError)
}
} }
reqWrapped := wrapperCreateTemplateRequest{ reqWrapped := wrapperCreateTemplateRequest{

Some files were not shown because too many files have changed in this diff Show More