Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fda016d011 | |||
| 082f577e17 | |||
| 78a4152471 | |||
| 3e55195831 | |||
| 9f5e76aee4 | |||
| df8b045e77 | |||
| 4d9b8fc9d8 | |||
| e8270453cc | |||
| 7de095302b | |||
| a3711057ba | |||
| 1c59ca338a | |||
| f1529c9aac | |||
| 040235f92f | |||
| 4a152cb44c | |||
| c78b1348e3 | |||
| 8f152a2f63 | |||
| 0be4d8fb0c | |||
|
|
5025a17ea4 | ||
| 7c787f6fce | |||
| 20fd7ab50c | |||
| f50f71ab0d | |||
| 29c7f143fe | |||
| 264538f492 | |||
| c06a3198f6 | |||
| c9e4ae6afe | |||
| 2a1593f45f | |||
| 190f24dac1 | |||
| 256dba5134 | |||
| b7137683ab | |||
| 10e3e19892 | |||
| aaf0857ff0 | |||
| 7d6cda7119 | |||
| 84b64b7d80 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -1 +1,5 @@
|
|||||||
cmd/
|
cmd/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
.fleet/
|
||||||
|
.DS_Store
|
||||||
|
|||||||
19
CHANGELOG.md
19
CHANGELOG.md
@@ -1,12 +1,7 @@
|
|||||||
## Version 1.2.1
|
## Version 1.5.11
|
||||||
|
|
||||||
### Bug fixes
|
### Bugfix
|
||||||
|
- Fix unhandled error in do() method for client and legacy-client
|
||||||
#### Legacy Client
|
|
||||||
|
|
||||||
- Fixed password and username encoding
|
|
||||||
- Fixed request params absence in HTTP Transport
|
|
||||||
|
|
||||||
#### All
|
|
||||||
|
|
||||||
- Updated module to new repository
|
|
||||||
|
|||||||
235
README.md
235
README.md
@@ -7,6 +7,9 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- Версия 1.0.x Decort-SDK соответствует 3.8.4 версии платформы
|
- Версия 1.0.x Decort-SDK соответствует 3.8.4 версии платформы
|
||||||
- Версия 1.1.x Decort-SDK соответствует 3.8.5 версии платформы
|
- Версия 1.1.x Decort-SDK соответствует 3.8.5 версии платформы
|
||||||
- Версия 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.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
||||||
|
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
||||||
|
|
||||||
## Оглавление
|
## Оглавление
|
||||||
|
|
||||||
@@ -16,6 +19,10 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- [Cloudbroker](#cloudbroker)
|
- [Cloudbroker](#cloudbroker)
|
||||||
- [Работа с библиотекой](#работа-с-библиотекой)
|
- [Работа с библиотекой](#работа-с-библиотекой)
|
||||||
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
||||||
|
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
||||||
|
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
||||||
|
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
||||||
|
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
||||||
- [Создание клиента](#создание-клиента)
|
- [Создание клиента](#создание-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
@@ -24,6 +31,10 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- [Сериализация](#сериализация)
|
- [Сериализация](#сериализация)
|
||||||
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
||||||
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
||||||
|
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
||||||
|
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
||||||
|
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
||||||
|
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
||||||
- [Создание legacy клиента](#создание-legacy-клиента)
|
- [Создание legacy клиента](#создание-legacy-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
@@ -51,12 +62,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;
|
||||||
@@ -73,26 +83,36 @@ 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. Создание клиента.
|
2. Создание клиента.
|
||||||
3. Создание структуры запроса.
|
3. Создание структуры запроса.
|
||||||
4. Выполнение запроса.
|
4. Выполнение запроса.
|
||||||
@@ -107,15 +127,17 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
||||||
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||||
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true |
|
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||||
|
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||||
| Token | string | Нет | JWT токен |
|
| Token | string | Нет | JWT токен |
|
||||||
|
|
||||||
Пример кода:
|
#### Пример конфигурации клиента
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main(){
|
func main(){
|
||||||
// Настройка конфигурации
|
// Настройка конфигурации
|
||||||
cfg := config.Config{
|
cfg := config.Config{
|
||||||
@@ -125,9 +147,54 @@ func main(){
|
|||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg.SetTimeout(5 * time.Minute)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Парсинг конфигурации из файла
|
||||||
|
|
||||||
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
||||||
|
<br>
|
||||||
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Парсинг конфигурации из JSON-файла
|
||||||
|
cfg := config.ParseConfigJSON("<PATH>")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример JSON конфигурации
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"appId": "<APP_ID>",
|
||||||
|
"appSecret": "<APP_SECRET>",
|
||||||
|
"ssoUrl": "https://sso.digitalenergy.online",
|
||||||
|
"decortUrl": "https://mr4.digitalenergy.online",
|
||||||
|
"retries": 5,
|
||||||
|
"timeout": "5m",
|
||||||
|
"sslSkipVerify": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример YAML конфигурации
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
appId: <APP_ID>
|
||||||
|
appSecret: <APP_SECRET>
|
||||||
|
ssoUrl: https://sso.digitalenergy.online
|
||||||
|
decortUrl: https://mr4.digitalenergy.online
|
||||||
|
retries: 5
|
||||||
|
timeout: 5m
|
||||||
|
sslSkipVerify: false
|
||||||
|
```
|
||||||
|
|
||||||
### Создание клиента
|
### Создание клиента
|
||||||
|
|
||||||
Создание клиента происходит с помощью функции-строителя `New` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
Создание клиента происходит с помощью функции-строителя `New` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
||||||
@@ -138,8 +205,8 @@ func main(){
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -152,6 +219,8 @@ func main() {
|
|||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
client := decort.New(cfg)
|
client := decort.New(cfg)
|
||||||
}
|
}
|
||||||
@@ -170,7 +239,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`
|
||||||
@@ -187,19 +255,27 @@ func main() {
|
|||||||
- `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`
|
||||||
|
|
||||||
Все поля структуры имеют описание, в которых содержится:
|
Все поля структуры имеют описание, в которых содержится:
|
||||||
@@ -302,9 +378,9 @@ type CreateRequest struct {
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
"github.com/rudecs/decort-sdk/pkg/cloudapi/kvmx86"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/kvmx86"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -344,7 +420,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`
|
||||||
@@ -363,19 +438,27 @@ func main() {
|
|||||||
Доступные методы для `.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. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||||
@@ -387,7 +470,7 @@ func main() {
|
|||||||
4. Обработать результат и ошибки.
|
4. Обработать результат и ошибки.
|
||||||
|
|
||||||
Т.к. все вызовы методов идут последовательно, можно их объеденить в конвейер:
|
Т.к. все вызовы методов идут последовательно, можно их объеденить в конвейер:
|
||||||
Общий вид вонвейра будет выглядеть так:
|
Общий вид конвейера будет выглядеть так:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
client.<API>.<группа>.<метод>
|
client.<API>.<группа>.<метод>
|
||||||
@@ -402,9 +485,9 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
"github.com/rudecs/decort-sdk/pkg/cloudapi/kvmx86"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/kvmx86"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -484,6 +567,52 @@ filtered := resp.
|
|||||||
// ....
|
// ....
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Также у `compute`, `disks`, и `lb` присутствуют специфические функции фильтрации, отправляющие дополнительные запросы. В качестве параметров принимают:
|
||||||
|
- context.Context - контекст для доп. запроса
|
||||||
|
- id (или другое поле, по которому производится фильтрация)
|
||||||
|
- interfaces.Caller - DECORT-клиент для запроса
|
||||||
|
|
||||||
|
Так как эти функции возвращают не только результирующий слайс, но и возможную ошибку - конвейер придется прервать для обработки ошибки.
|
||||||
|
|
||||||
|
|
||||||
|
#### Использование на примере `compute.FilterByK8SID`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func main() {
|
||||||
|
// Чтение конфигурации из файла
|
||||||
|
cfg := config.ParseConfigJSON("<PATH>")
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
client := decort.New(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса compute/list
|
||||||
|
req := compute.ListRequest{}
|
||||||
|
|
||||||
|
// Запрос
|
||||||
|
resp, err := client.CloudAPI().Compute().List(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Фильтрация по id кластера.
|
||||||
|
// Первый аргумент - контекст
|
||||||
|
// Второй - ID кластера
|
||||||
|
// Третий - DECORT-клиент
|
||||||
|
filtered, err := resp.FilterByK8SID(context.Background(), <k8sID>, client)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err) // Возможная ошибка запроса
|
||||||
|
}
|
||||||
|
|
||||||
|
// Доп. фильтрация и сортировка результата - worker ноды кластера
|
||||||
|
workers := filtered.FilterByK8SWorkers().SortByCreatedTime(false)
|
||||||
|
|
||||||
|
// Доп. фильтрация и сортировка результата - master ноды кластера
|
||||||
|
masters := filtered.FilterByK8SMasters().SortByCreatedTime(true)
|
||||||
|
|
||||||
|
// ....
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Сортировка
|
### Сортировка
|
||||||
|
|
||||||
Функции сортировки так же могут быть объединены в конвейер:
|
Функции сортировки так же могут быть объединены в конвейер:
|
||||||
@@ -536,9 +665,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
"github.com/rudecs/decort-sdk/pkg/cloudbroker/compute"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/compute"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -549,6 +678,8 @@ func main() {
|
|||||||
DecortURL: "<DECORT_URL>",
|
DecortURL: "<DECORT_URL>",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
client := decort.New(cfg)
|
client := decort.New(cfg)
|
||||||
@@ -595,26 +726,69 @@ func main() {
|
|||||||
| Password | string | Да | пароль legacy пользователя |
|
| Password | string | Да | пароль legacy пользователя |
|
||||||
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||||
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата, по умолчанию - true |
|
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||||
|
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||||
| Token | string | Нет | JWT токен |
|
| Token | string | Нет | JWT токен |
|
||||||
|
|
||||||
Пример кода:
|
#### Пример конфигурации legacy клиента
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main(){
|
func main(){
|
||||||
// Настройка конфигурации
|
// Настройка конфигурации
|
||||||
legacyCfg := config.LegacyConfig{
|
legacyCfg := config.LegacyConfig{
|
||||||
Username: "<USERNAME>",
|
Username: "<USERNAME>",
|
||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Парсинг legacy конфигурации из файла
|
||||||
|
|
||||||
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseLegacyConfigJSON` (или `ParseLegacyConfigYAML`) из пакета config.
|
||||||
|
<br>
|
||||||
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Парсинг конфигурации из YAML-файла
|
||||||
|
legacyCfg := config.ParseLegacyConfigYAML("<PATH>")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример legacy JSON конфигурации
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "<USERNAME>",
|
||||||
|
"password": "<PASSWORD>",
|
||||||
|
"decortUrl": "https://mr4.digitalenergy.online",
|
||||||
|
"retries": 5,
|
||||||
|
"timeout": "5m",
|
||||||
|
"sslSkipVerify": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример legacy YAML конфигурации
|
||||||
|
```yaml
|
||||||
|
username: <USERNAME>
|
||||||
|
password: <PASSWORD>
|
||||||
|
decortUrl: https://mr4.digitalenergy.online
|
||||||
|
retries: 5
|
||||||
|
timeout: 5m
|
||||||
|
sslSkipVerify: true
|
||||||
|
```
|
||||||
### Создание legacy клиента
|
### Создание legacy клиента
|
||||||
|
|
||||||
Создание клиента происходит с помощью функции-строителя `NewLegacy` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
Создание клиента происходит с помощью функции-строителя `NewLegacy` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
||||||
@@ -625,8 +799,8 @@ func main(){
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -638,6 +812,8 @@ func main() {
|
|||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(cfg)
|
legacyClient := decort.NewLegacy(cfg)
|
||||||
}
|
}
|
||||||
@@ -651,8 +827,8 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
decort "github.com/rudecs/decort-sdk"
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -685,4 +861,3 @@ func main() {
|
|||||||
|
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
}
|
}
|
||||||
```
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ Also the library have structures for responses.
|
|||||||
## Install
|
## Install
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go get -u github.com/rudecs/decort-sdk
|
go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
||||||
```
|
```
|
||||||
|
|
||||||
## API List
|
## API List
|
||||||
@@ -29,8 +29,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
"github.com/rudecs/decort-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
"github.com/rudecs/decort-sdk/pkg/cloudapi/kvmx86"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/kvmx86"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|||||||
99
client.go
99
client.go
@@ -1,24 +1,31 @@
|
|||||||
package decortsdk
|
package decortsdk
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 +34,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{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +79,11 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := dc.client.Do(req)
|
if err = dc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := dc.do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -73,3 +100,65 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
|||||||
|
|
||||||
return respBytes, nil
|
return respBytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (dc *DecortClient) getToken(ctx context.Context) error {
|
||||||
|
dc.mutex.Lock()
|
||||||
|
defer dc.mutex.Unlock()
|
||||||
|
|
||||||
|
if dc.cfg.Token == "" || time.Now().After(dc.expiryTime) {
|
||||||
|
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
dc.cfg.SSOURL = strings.TrimSuffix(dc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", dc.cfg.SSOURL+"/v1/oauth/access_token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := string(tokenBytes)
|
||||||
|
|
||||||
|
dc.cfg.Token = token
|
||||||
|
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dc *DecortClient) do(req *http.Request) (*http.Response, error) {
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
|
// var resp *http.Response
|
||||||
|
// var err error
|
||||||
|
buf, _ := io.ReadAll(req.Body)
|
||||||
|
|
||||||
|
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||||
|
// req = req.Clone(req.Context())
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,39 +1,105 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
// Configuration for creating request to platform
|
// Configuration for creating request to platform
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// JWT platform token
|
// JWT platform token
|
||||||
// Required: false
|
// Required: false
|
||||||
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
||||||
Token string
|
Token string `json:"token" yaml:"token"`
|
||||||
|
|
||||||
// Application (client) identifier for authorization
|
// Application (client) identifier for authorization
|
||||||
// in the cloud platform controller in oauth2 mode.
|
// in the cloud platform controller in oauth2 mode.
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
|
// Example: "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
|
||||||
AppID string
|
AppID string `json:"appId" yaml:"appId" validate:"required"`
|
||||||
|
|
||||||
// Application (client) secret code for authorization
|
// Application (client) secret code for authorization
|
||||||
// in the cloud platform controller in oauth2 mode.
|
// in the cloud platform controller in oauth2 mode.
|
||||||
// Example: "frvet09rvesfis0c9erv9fsov0vsdfi09ovds0f"
|
// Example: "frvet09rvesfis0c9erv9fsov0vsdfi09ovds0f"
|
||||||
AppSecret string
|
AppSecret string `json:"appSecret" yaml:"appSecret" validate:"required"`
|
||||||
|
|
||||||
// Platform authentication service address
|
// Platform authentication service address
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "https://sso.digitalenergy.online"
|
// Example: "https://sso.digitalenergy.online"
|
||||||
SSOURL string
|
SSOURL string `json:"ssoUrl" yaml:"ssoUrl" validate:"url"`
|
||||||
|
|
||||||
// The address of the platform on which the actions are planned
|
// The address of the platform on which the actions are planned
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "https://mr4.digitalenergy.online"
|
// Example: "https://mr4.digitalenergy.online"
|
||||||
DecortURL string
|
DecortURL string `json:"decortUrl" yaml:"decortUrl" validate:"url"`
|
||||||
|
|
||||||
// Amount platform request attempts
|
// Amount platform request attempts
|
||||||
// Default value: 5
|
// Default value: 5
|
||||||
// Required: false
|
// Required: false
|
||||||
Retries uint64
|
Retries uint64 `json:"retries" yaml:"retries"`
|
||||||
|
|
||||||
// Skip verify, true by default
|
// Skip verify, true by default
|
||||||
// Required: false
|
// Required: false
|
||||||
SSLSkipVerify bool
|
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||||
|
|
||||||
|
// HTTP client timeout, unlimited if left empty
|
||||||
|
// Required: false
|
||||||
|
Timeout Duration `json:"timeout" yaml:"timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTimeout is used to set HTTP client timeout.
|
||||||
|
func (c *Config) SetTimeout(dur time.Duration) {
|
||||||
|
c.Timeout = Duration(dur)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseConfigJSON parses Config from specified JSON-formatted file.
|
||||||
|
func ParseConfigJSON(path string) (Config, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config Config
|
||||||
|
|
||||||
|
err = json.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return Config{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseConfigYAML parses Config from specified YAML-formatted file.
|
||||||
|
func ParseConfigYAML(path string) (Config, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config Config
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return Config{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +1,99 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
// Legacy client configuration
|
// Legacy client configuration
|
||||||
type LegacyConfig struct {
|
type LegacyConfig struct {
|
||||||
// ServiceAccount username
|
// ServiceAccount username
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example : "osh_mikoev"
|
// Example : "osh_mikoev"
|
||||||
Username string
|
Username string `json:"username" yaml:"username" validate:"required"`
|
||||||
|
|
||||||
// ServiceAccount password
|
// ServiceAccount password
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "[1o>hYkjnJr)HI78q7t&#%8Lm"
|
// Example: "[1o>hYkjnJr)HI78q7t&#%8Lm"
|
||||||
Password string
|
Password string `json:"password" yaml:"password" validate:"required"`
|
||||||
|
|
||||||
// Platform token
|
// Platform token
|
||||||
// Required: false
|
// Required: false
|
||||||
// Example: "158e76424b0d4810b6086hgbhj928fc4a6bc06e"
|
// Example: "158e76424b0d4810b6086hgbhj928fc4a6bc06e"
|
||||||
Token string
|
Token string `json:"token" yaml:"token"`
|
||||||
|
|
||||||
// Address of the platform on which the actions are planned
|
// Address of the platform on which the actions are planned
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "https://mr4.digitalenergy.online"
|
// Example: "https://mr4.digitalenergy.online"
|
||||||
DecortURL string
|
DecortURL string `json:"decortUrl" yaml:"decortUrl" validate:"url"`
|
||||||
|
|
||||||
// Amount platform request attempts
|
// Amount platform request attempts
|
||||||
// Default value: 5
|
// Default value: 5
|
||||||
// Required: false
|
// Required: false
|
||||||
Retries uint64
|
Retries uint64 `json:"retries" yaml:"retries"`
|
||||||
|
|
||||||
// Skip verify, true by default
|
// Skip verify, true by default
|
||||||
// Required: false
|
// Required: false
|
||||||
SSLSkipVerify bool
|
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||||
|
|
||||||
|
// HTTP client timeout, unlimited if left empty
|
||||||
|
// Required: false
|
||||||
|
Timeout Duration `json:"timeout" yaml:"timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTimeout is used to set HTTP client timeout.
|
||||||
|
func (c *LegacyConfig) SetTimeout(dur time.Duration) {
|
||||||
|
c.Timeout = Duration(dur)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLegacyConfigJSON parses LegacyConfig from specified JSON-formatted file.
|
||||||
|
func ParseLegacyConfigJSON(path string) (LegacyConfig, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return LegacyConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config LegacyConfig
|
||||||
|
|
||||||
|
err = json.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return LegacyConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLegacyConfigYAML parses LegacyConfig from specified YAML-formatted file.
|
||||||
|
func ParseLegacyConfigYAML(path string) (LegacyConfig, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return LegacyConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config LegacyConfig
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return LegacyConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|||||||
50
config/timeouts.go
Normal file
50
config/timeouts.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Duration is a wrapper around time.Duration (used for better user experience)
|
||||||
|
type Duration time.Duration
|
||||||
|
|
||||||
|
func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
|
var v interface{}
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch value := v.(type) {
|
||||||
|
case string:
|
||||||
|
tmp, err := time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*d = Duration(tmp)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("Invalid duration %v", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Duration) UnmarshalJSON(b []byte) error {
|
||||||
|
var v interface{}
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch value := v.(type) {
|
||||||
|
case string:
|
||||||
|
tmp, err := time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*d = Duration(tmp)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("Invalid duration %v", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Duration) Get() time.Duration {
|
||||||
|
return time.Duration(*d)
|
||||||
|
}
|
||||||
2
go.mod
2
go.mod
@@ -5,11 +5,13 @@ go 1.20
|
|||||||
require (
|
require (
|
||||||
github.com/go-playground/validator/v10 v10.11.2
|
github.com/go-playground/validator/v10 v10.11.2
|
||||||
github.com/google/go-querystring v1.1.0
|
github.com/google/go-querystring v1.1.0
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
github.com/leodido/go-urn v1.2.1 // indirect
|
github.com/leodido/go-urn v1.2.1 // indirect
|
||||||
golang.org/x/crypto v0.5.0 // indirect
|
golang.org/x/crypto v0.5.0 // indirect
|
||||||
golang.org/x/sys v0.4.0 // indirect
|
golang.org/x/sys v0.4.0 // indirect
|
||||||
|
|||||||
7
go.sum
7
go.sum
@@ -1,3 +1,4 @@
|
|||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
@@ -11,10 +12,14 @@ github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
|
|||||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
@@ -26,5 +31,7 @@ golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
|||||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -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: 5 * time.Minute,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package client
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewLegacyHttpClient creates legacy HTTP Client
|
|
||||||
func NewLegacyHttpClient(cfg config.LegacyConfig) *http.Client {
|
|
||||||
transCfg := &http.Transport{
|
|
||||||
TLSClientConfig: &tls.Config{
|
|
||||||
//nolint:gosec
|
|
||||||
InsecureSkipVerify: cfg.SSLSkipVerify,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
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: 5 * time.Minute,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -1,67 +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)
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,55 @@
|
|||||||
package validators
|
package validators
|
||||||
|
|
||||||
import "github.com/go-playground/validator/v10"
|
import (
|
||||||
|
"regexp"
|
||||||
|
"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.
|
||||||
|
func protoValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, protoValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// accessTypeValidator is used to validate AccessType fields.
|
||||||
|
func accessTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, accessTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resTypesValidator is used to validate ResTypes fields.
|
||||||
|
func resTypesValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldSlice, ok := fe.Field().Interface().([]string)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range fieldSlice {
|
||||||
|
if !StringInSlice(value, resTypesValues) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// driverValidator is used to validate Driver fields.
|
||||||
|
func driverValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, driverValues)
|
||||||
|
}
|
||||||
|
|
||||||
// accountCUTypeValidator is used to validate CUType field.
|
// accountCUTypeValidator is used to validate CUType field.
|
||||||
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
||||||
@@ -9,20 +58,6 @@ func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
|||||||
return StringInSlice(fieldValue, accountCUTypeValues)
|
return StringInSlice(fieldValue, accountCUTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// accountAccessTypeValidator is used to validate AccessType field.
|
|
||||||
func accountAccessTypeValidator(fe validator.FieldLevel) bool {
|
|
||||||
fieldValue := fe.Field().String()
|
|
||||||
|
|
||||||
return StringInSlice(fieldValue, accountAccessTypeValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bserviceDriverValidator is used to validate Driver field.
|
|
||||||
func bserviceDriverValidator(fe validator.FieldLevel) bool {
|
|
||||||
fieldValue := fe.Field().String()
|
|
||||||
|
|
||||||
return StringInSlice(fieldValue, bserviceDriverValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bserviceModeValidator is used to validate Mode field.
|
// bserviceModeValidator is used to validate Mode field.
|
||||||
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
@@ -65,11 +100,76 @@ func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
|||||||
return StringInSlice(fieldValue, computeNetTypeValues)
|
return StringInSlice(fieldValue, computeNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeProtoValidator is used to validate Proto field.
|
// computeOrderValidator is used to validate Order field.
|
||||||
func computeProtoValidator(fe validator.FieldLevel) bool {
|
func computeOrderValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldSlice, ok := fe.Field().Interface().([]string)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range fieldSlice {
|
||||||
|
if !StringInSlice(value, computeOrderValues) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// computeDataDisksValidator is used to validate DataDisks field.
|
||||||
|
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeProtoValues)
|
return StringInSlice(fieldValue, computeDataDisksValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// diskTypeValidator is used to validate Type field.
|
||||||
|
func diskTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, diskTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// flipgroupClientTypeValidator is used to validate ClientType field.
|
||||||
|
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, flipgroupClientTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// kvmNetTypeValidator is used to validate NetType field.
|
||||||
|
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, kvmNetTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// lbAlgorithmValidator is used to validate Algorithm field.
|
||||||
|
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, lbAlgorithmValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rgDefNetValidator is used to validate DefNet field.
|
||||||
|
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, rgDefNetValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rgNetTypeValidator is used to validate NetType field.
|
||||||
|
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, rgNetTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// vinsTypeValidator is used to validate Type field.
|
||||||
|
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, vinsTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageBootTypeValidator is used to validate BootType field.
|
// imageBootTypeValidator is used to validate BootType field.
|
||||||
@@ -108,3 +208,67 @@ func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
|||||||
|
|
||||||
return StringInSlice(fieldValue, imageArchitectureValues)
|
return StringInSlice(fieldValue, imageArchitectureValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sepFieldTypeValidator is used to validate FieldType field.
|
||||||
|
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, sepFieldTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// hwPathValidator is used to validate HWPath field.
|
||||||
|
func hwPathValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
ok, _ := regexp.MatchString(`^\b[0-9a-f]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}.\d{1}$`, fieldValue)
|
||||||
|
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// networkPluginValidator is used to validate NetworkPlugin field
|
||||||
|
func networkPluginValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, networkPluginValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// networkPluginsValidator is used to validate NetworkPlugins field
|
||||||
|
func networkPluginsValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldSlice, ok := fe.Field().Interface().([]string)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range fieldSlice {
|
||||||
|
item = strings.ToLower(item)
|
||||||
|
|
||||||
|
if !StringInSlice(item, networkPluginValues) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func interfaceStateValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
return StringInSlice(fieldValue, interfaceStateValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func strictLooseValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ func ValidateRequest(req interface{}) error {
|
|||||||
return validate.Struct(req)
|
return validate.Struct(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ValidateConfig(cfg interface{}) error {
|
||||||
|
validate := getDecortValidator()
|
||||||
|
return validate.Struct(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
func ValidationError(fe validator.FieldError) error {
|
func ValidationError(fe validator.FieldError) error {
|
||||||
return errors.New(errorMessage(fe))
|
return errors.New(errorMessage(fe))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
|
|
||||||
switch fe.Tag() {
|
switch fe.Tag() {
|
||||||
|
|
||||||
// Default Validators
|
// Common Validators
|
||||||
case "required":
|
case "required":
|
||||||
return fmt.Sprintf("%s %s is required", prefix, fe.Field())
|
return fmt.Sprintf("%s %s is required", prefix, fe.Field())
|
||||||
case "gt":
|
case "gt":
|
||||||
@@ -26,13 +26,31 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
case "email":
|
case "email":
|
||||||
return fmt.Sprintf("%s %s: unexpected E-Mail format", prefix, fe.Field())
|
return fmt.Sprintf("%s %s: unexpected E-Mail format", prefix, fe.Field())
|
||||||
|
|
||||||
// Account Validators
|
case "driver":
|
||||||
case "accountAccessType":
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
return fmt.Sprintf("%s %s must be one of the followng: %s",
|
|
||||||
prefix,
|
prefix,
|
||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(accountAccessTypeValues))
|
joinValues(driverValues))
|
||||||
|
|
||||||
|
case "accessType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(accessTypeValues))
|
||||||
|
|
||||||
|
case "resTypes":
|
||||||
|
return fmt.Sprintf("%s %s can contain only the following values: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(resTypesValues))
|
||||||
|
|
||||||
|
case "proto":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(protoValues))
|
||||||
|
|
||||||
|
// Account Validators
|
||||||
case "accountCUType":
|
case "accountCUType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
@@ -40,12 +58,6 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
joinValues(accountCUTypeValues))
|
joinValues(accountCUTypeValues))
|
||||||
|
|
||||||
// BService Validators
|
// BService Validators
|
||||||
case "bserviceDriver":
|
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
|
||||||
prefix,
|
|
||||||
fe.Field(),
|
|
||||||
joinValues(bserviceDriverValues))
|
|
||||||
|
|
||||||
case "bserviceMode":
|
case "bserviceMode":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
@@ -83,14 +95,80 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(computeNetTypeValues))
|
joinValues(computeNetTypeValues))
|
||||||
|
|
||||||
case "computeProto":
|
case "computeOrder":
|
||||||
|
return fmt.Sprintf("%s %s can contain only the following values: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(computeOrderValues))
|
||||||
|
|
||||||
|
case "computeDataDisks":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(computeProtoValues))
|
joinValues(computeDataDisksValues))
|
||||||
|
|
||||||
|
case "computeDriver":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(computeDriverValues))
|
||||||
|
|
||||||
|
// Disk Validators
|
||||||
|
case "diskType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(diskTypeValues))
|
||||||
|
|
||||||
|
// Flipgroup Validators
|
||||||
|
case "flipgroupClientType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(flipgroupClientTypeValues))
|
||||||
|
|
||||||
|
// k8s Validators
|
||||||
|
case "workerGroupName":
|
||||||
|
return fmt.Sprintf("%s %s must be more 3 symbol",
|
||||||
|
prefix,
|
||||||
|
fe.Field())
|
||||||
|
|
||||||
|
// KVM_X86/KVM_PPC Validators
|
||||||
|
case "kvmNetType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(kvmNetTypeValues))
|
||||||
|
|
||||||
|
// LB Validators
|
||||||
|
case "lbAlgorithm":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(lbAlgorithmValues))
|
||||||
|
|
||||||
|
// RG Validators
|
||||||
|
case "rgDefNet":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(rgDefNetValues))
|
||||||
|
|
||||||
|
case "rgNetType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(rgNetTypeValues))
|
||||||
|
|
||||||
|
// ViNS Validators
|
||||||
|
case "vinsType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(vinsTypeValues))
|
||||||
|
|
||||||
// Image Validators
|
// Image Validators
|
||||||
case "bootType":
|
case "imageBootType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
fe.Field(),
|
fe.Field(),
|
||||||
@@ -114,6 +192,43 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(imageArchitectureValues))
|
joinValues(imageArchitectureValues))
|
||||||
|
|
||||||
|
// SEP Validators
|
||||||
|
case "sepFieldType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(sepFieldTypeValues))
|
||||||
|
|
||||||
|
// HWPath Validators
|
||||||
|
case "hwPath":
|
||||||
|
return fmt.Sprintf("%s %s must be in format 0000:1f:2b.0",
|
||||||
|
prefix,
|
||||||
|
fe.Field())
|
||||||
|
|
||||||
|
// Network plugin Validators
|
||||||
|
case "networkPlugin":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(networkPluginValues))
|
||||||
|
|
||||||
|
case "networkPlugins":
|
||||||
|
return fmt.Sprintf("%s %s must contain only the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(networkPluginValues))
|
||||||
|
|
||||||
|
case "strict_loose":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(strictLooseValues))
|
||||||
|
|
||||||
|
case "interfaceState":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(interfaceStateValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
return fe.Error()
|
return fe.Error()
|
||||||
|
|||||||
@@ -7,34 +7,50 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
once sync.Once
|
once sync.Once
|
||||||
instance *DecortValidator
|
decortValidator = validator.New()
|
||||||
)
|
)
|
||||||
|
|
||||||
type DecortValidator struct {
|
|
||||||
decortValidator *validator.Validate
|
|
||||||
}
|
|
||||||
|
|
||||||
// getDecortValidator returns singleton instance of DecortValidator.
|
// getDecortValidator returns singleton instance of DecortValidator.
|
||||||
func getDecortValidator() *validator.Validate {
|
func getDecortValidator() *validator.Validate {
|
||||||
if instance == nil {
|
once.Do(func() {
|
||||||
once.Do(func() {
|
err := registerAllValidators(decortValidator)
|
||||||
instance = new(DecortValidator)
|
if err != nil {
|
||||||
instance.decortValidator = validator.New()
|
panic(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
err := registerAllValidators(instance.decortValidator)
|
return decortValidator
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return instance.decortValidator
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// registerAllValidators registers all custom validators in DecortValidator.
|
// registerAllValidators registers all custom validators in DecortValidator.
|
||||||
func registerAllValidators(validate *validator.Validate) error {
|
func registerAllValidators(validate *validator.Validate) error {
|
||||||
err := validate.RegisterValidation("bootType", imageBootTypeValidator)
|
err := validate.RegisterValidation("proto", protoValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("computeDriver", computeDriverValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("accessType", accessTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("resTypes", resTypesValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("driver", driverValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("imageBootType", imageBootTypeValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -54,21 +70,11 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("accountAccessType", accountAccessTypeValidator)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = validate.RegisterValidation("accountCUType", accountCUTypeValidator)
|
err = validate.RegisterValidation("accountCUType", accountCUTypeValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("bserviceDriver", bserviceDriverValidator)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = validate.RegisterValidation("bserviceMode", bserviceModeValidator)
|
err = validate.RegisterValidation("bserviceMode", bserviceModeValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -99,7 +105,82 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("computeProto", computeProtoValidator)
|
err = validate.RegisterValidation("computeOrder", computeOrderValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("computeDataDisks", computeDataDisksValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("diskType", diskTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("flipgroupClientType", flipgroupClientTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("kvmNetType", kvmNetTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("lbAlgorithm", lbAlgorithmValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("rgDefNet", rgDefNetValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("rgNetType", rgNetTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("vinsType", vinsTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("sepFieldType", sepFieldTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("hwPath", hwPathValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("networkPlugin", networkPluginValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("networkPlugins", networkPluginsValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("strict_loose", strictLooseValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("interfaceState", interfaceStateValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("workerGroupName", workerGroupNameValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,47 @@
|
|||||||
package validators
|
package validators
|
||||||
|
|
||||||
var (
|
var (
|
||||||
accountAccessTypeValues = []string{"R", "RCX", "ARCXDU"}
|
driverValues = []string{"KVM_X86", "KVM_PPC"}
|
||||||
accountCUTypeValues = []string{"CU_M", "CU_C", "CU_D", "CU_S", "CU_A", "CU_NO", "CU_I", "CU_NP"}
|
accessTypeValues = []string{"R", "RCX", "ARCXDU"}
|
||||||
|
resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"}
|
||||||
|
protoValues = []string{"tcp", "udp"}
|
||||||
|
|
||||||
bserviceDriverValues = []string{"KVM_X86, KVM_PPC"}
|
accountCUTypeValues = []string{"CU_M", "CU_C", "CU_D", "CU_DM", "CU_S", "CU_A", "CU_NO", "CU_I", "CU_NP"}
|
||||||
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
|
|
||||||
|
|
||||||
computeTopologyValues = []string{"compute", "node"}
|
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
|
||||||
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
|
||||||
computeModeValues = []string{"EQ", "EN", "ANY"}
|
computeTopologyValues = []string{"compute", "node"}
|
||||||
computeDiskTypeValues = []string{"D", "B"}
|
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
||||||
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
computeModeValues = []string{"EQ", "EN", "ANY"}
|
||||||
computeProtoValues = []string{"tcp", "udp"}
|
computeDiskTypeValues = []string{"D", "B"}
|
||||||
|
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
||||||
|
computeOrderValues = []string{"cdrom", "network", "hd"}
|
||||||
|
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
|
||||||
|
computeDriverValues = []string{"KVM_X86", "SVA_KVM_X86"}
|
||||||
|
|
||||||
|
diskTypeValues = []string{"B", "T", "D"}
|
||||||
|
|
||||||
|
flipgroupClientTypeValues = []string{"compute", "vins"}
|
||||||
|
|
||||||
|
kvmNetTypeValues = []string{"EXTNET", "VINS", "NONE"}
|
||||||
|
|
||||||
|
lbAlgorithmValues = []string{"roundrobin", "static-rr", "leastconn"}
|
||||||
|
|
||||||
|
rgDefNetValues = []string{"PRIVATE", "PUBLIC", "NONE"}
|
||||||
|
rgNetTypeValues = []string{"PUBLIC", "PRIVATE"}
|
||||||
|
|
||||||
|
vinsTypeValues = []string{"DHCP", "VIP", "EXCLUDE"}
|
||||||
|
|
||||||
imageBootTypeValues = []string{"uefi", "bios"}
|
imageBootTypeValues = []string{"uefi", "bios"}
|
||||||
imageTypeValues = []string{"windows", "linux", "other"}
|
imageTypeValues = []string{"windows", "linux", "other"}
|
||||||
imageDriversValues = []string{"KVM_X86"}
|
imageDriversValues = []string{"KVM_X86"}
|
||||||
imageArchitectureValues = []string{"X86_64", "PPC64_LE"}
|
imageArchitectureValues = []string{"X86_64", "PPC64_LE"}
|
||||||
|
|
||||||
|
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
||||||
|
|
||||||
|
networkPluginValues = []string{"flannel", "weawenet", "calico"}
|
||||||
|
|
||||||
|
strictLooseValues = []string{"strict", "loose"}
|
||||||
|
|
||||||
|
interfaceStateValues = []string{"on", "off"}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,23 +1,31 @@
|
|||||||
package decortsdk
|
package decortsdk
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"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"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 +34,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{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,13 +73,18 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
body := strings.NewReader(values.Encode())
|
if err = ldc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
body := strings.NewReader(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+"/restmachine"+url, body)
|
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)
|
resp, err := ldc.do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -72,3 +101,61 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
|
|||||||
|
|
||||||
return respBytes, nil
|
return respBytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
||||||
|
ldc.mutex.Lock()
|
||||||
|
defer ldc.mutex.Unlock()
|
||||||
|
|
||||||
|
if ldc.cfg.Token == "" || time.Now().After(ldc.expiryTime) {
|
||||||
|
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("unable to get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := string(tokenBytes)
|
||||||
|
ldc.cfg.Token = token
|
||||||
|
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ldc *LegacyDecortClient) do(req *http.Request) (*http.Response, error) {
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
|
// var resp *http.Response
|
||||||
|
// var err error
|
||||||
|
buf, _ := io.ReadAll(req.Body)
|
||||||
|
|
||||||
|
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||||
|
// req = req.Clone(req.Context())
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type AddUserRequest struct {
|
|||||||
// - 'RCX' for Write
|
// - 'RCX' for Write
|
||||||
// - 'ARCXDU' for Admin
|
// - 'ARCXDU' for Admin
|
||||||
// Required: true
|
// Required: true
|
||||||
AccessType string `url:"accesstype" json:"accesstype" validate:"required,accountAccessType"`
|
AccessType string `url:"accesstype" json:"accesstype" validate:"required,accessType"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddUser gives a user access rights.
|
// AddUser gives a user access rights.
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ type CreateRequest struct {
|
|||||||
|
|
||||||
// If true send emails when a user is granted access to resources
|
// If true send emails when a user is granted access to resources
|
||||||
// Required: false
|
// Required: false
|
||||||
SendAccessEmails bool `url:"sendAccessEmails,omitempty" json:"sendAccessEmails,omitempty"`
|
SendAccessEmails bool `url:"sendAccessEmails" json:"sendAccessEmails"`
|
||||||
|
|
||||||
// Limit (positive) or disable (0) GPU resources
|
// Limit (positive) or disable (0) GPU resources
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -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]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ 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)
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ 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)
|
||||||
|
|||||||
42
pkg/cloudapi/account/get_resource_consumption.go
Normal file
42
pkg/cloudapi/account/get_resource_consumption.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for getting 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 {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -8,17 +8,33 @@ import (
|
|||||||
|
|
||||||
// Request struct for get list of accounts
|
// Request struct for 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 list all accounts the user has access to
|
||||||
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"
|
url := "/cloudapi/account/list"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -33,5 +49,5 @@ func (a Account) List(ctx context.Context, req ListRequest) (ListAccounts, error
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,50 @@ 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +78,5 @@ func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (Lis
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,15 +10,27 @@ import (
|
|||||||
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 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,34 @@ 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +62,5 @@ func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (ListDisks
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,13 +10,45 @@ import (
|
|||||||
|
|
||||||
// Request struct for get list FLIPGroups
|
// Request struct for get list 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +70,5 @@ func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
26
pkg/cloudapi/account/list_resource_consumption.go
Normal file
26
pkg/cloudapi/account/list_resource_consumption.go
Normal 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
|
||||||
|
}
|
||||||
@@ -13,10 +13,38 @@ 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 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +66,5 @@ func (a Account) ListRG(ctx context.Context, req ListRGRequest) (ListRG, error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,15 +12,35 @@ import (
|
|||||||
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 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -42,5 +62,5 @@ func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (L
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,34 @@ 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 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) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +62,5 @@ func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (ListVINS, e
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -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"`
|
Current Resource `json:"Current"`
|
||||||
|
|
||||||
// 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"`
|
||||||
|
|
||||||
@@ -158,6 +179,12 @@ type RecordAccount struct {
|
|||||||
// Computes
|
// Computes
|
||||||
Computes Computes `json:"computes"`
|
Computes Computes `json:"computes"`
|
||||||
|
|
||||||
|
// CPU allocation parameter
|
||||||
|
CPUAllocationParameter string `json:"cpu_allocation_parameter"`
|
||||||
|
|
||||||
|
// CPU allocation ratio
|
||||||
|
CPUAllocationRatio float64 `json:"cpu_allocation_ratio"`
|
||||||
|
|
||||||
// Created by
|
// Created by
|
||||||
CreatedBy string `json:"createdBy"`
|
CreatedBy string `json:"createdBy"`
|
||||||
|
|
||||||
@@ -165,7 +192,7 @@ type RecordAccount struct {
|
|||||||
CreatedTime uint64 `json:"createdTime"`
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
// Deactivation time
|
// Deactivation time
|
||||||
DeactivationTime uint64 `json:"deactivationTime"`
|
DeactivationTime float64 `json:"deactivationTime"`
|
||||||
|
|
||||||
// Deleted by
|
// Deleted by
|
||||||
DeletedBy string `json:"deletedBy"`
|
DeletedBy string `json:"deletedBy"`
|
||||||
@@ -192,7 +219,7 @@ type RecordAccount struct {
|
|||||||
ResourceLimits ResourceLimits `json:"resourceLimits"`
|
ResourceLimits ResourceLimits `json:"resourceLimits"`
|
||||||
|
|
||||||
// Resource types
|
// Resource types
|
||||||
ResourceTypes []string `json:"resourceTypes"`
|
ResTypes []string `json:"resourceTypes"`
|
||||||
|
|
||||||
// Send access emails
|
// Send access emails
|
||||||
SendAccessEmails bool `json:"sendAccessEmails"`
|
SendAccessEmails bool `json:"sendAccessEmails"`
|
||||||
@@ -280,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 {
|
||||||
@@ -307,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 {
|
||||||
@@ -364,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 {
|
||||||
@@ -478,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 {
|
||||||
@@ -514,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 {
|
||||||
@@ -583,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"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ package account
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,15 +24,10 @@ func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error)
|
|||||||
|
|
||||||
url := "/cloudapi/account/restore"
|
url := "/cloudapi/account/restore"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
_, err = a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := strconv.ParseBool(string(res))
|
return true, nil
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -20,31 +20,31 @@ type UpdateRequest struct {
|
|||||||
|
|
||||||
// Max size of memory in MB
|
// Max size of memory in MB
|
||||||
// Required: false
|
// Required: false
|
||||||
MaxMemoryCapacity uint64 `url:"maxMemoryCapacity,omitempty" json:"maxMemoryCapacity,omitempty"`
|
MaxMemoryCapacity int64 `url:"maxMemoryCapacity,omitempty" json:"maxMemoryCapacity,omitempty"`
|
||||||
|
|
||||||
// Max size of aggregated vdisks in GB
|
// Max size of aggregated vdisks in GB
|
||||||
// Required: false
|
// Required: false
|
||||||
MaxVDiskCapacity uint64 `url:"maxVDiskCapacity,omitempty" json:"maxVDiskCapacity,omitempty"`
|
MaxVDiskCapacity int64 `url:"maxVDiskCapacity,omitempty" json:"maxVDiskCapacity,omitempty"`
|
||||||
|
|
||||||
// Max number of CPU cores
|
// Max number of CPU cores
|
||||||
// Required: false
|
// Required: false
|
||||||
MaxCPUCapacity uint64 `url:"maxCPUCapacity,omitempty" json:"maxCPUCapacity,omitempty"`
|
MaxCPUCapacity int64 `url:"maxCPUCapacity,omitempty" json:"maxCPUCapacity,omitempty"`
|
||||||
|
|
||||||
// Max sent/received network transfer peering
|
// Max sent/received network transfer peering
|
||||||
// Required: false
|
// Required: false
|
||||||
MaxNetworkPeerTransfer uint64 `url:"maxNetworkPeerTransfer,omitempty" json:"maxNetworkPeerTransfer,omitempty"`
|
MaxNetworkPeerTransfer int64 `url:"maxNetworkPeerTransfer,omitempty" json:"maxNetworkPeerTransfer,omitempty"`
|
||||||
|
|
||||||
// Max number of assigned public IPs
|
// Max number of assigned public IPs
|
||||||
// Required: false
|
// Required: false
|
||||||
MaxNumPublicIP uint64 `url:"maxNumPublicIP,omitempty" json:"maxNumPublicIP,omitempty"`
|
MaxNumPublicIP int64 `url:"maxNumPublicIP,omitempty" json:"maxNumPublicIP,omitempty"`
|
||||||
|
|
||||||
// If true send emails when a user is granted access to resources
|
// If true send emails when a user is granted access to resources
|
||||||
// Required: false
|
// Required: false
|
||||||
SendAccessEmails bool `url:"sendAccessEmails,omitempty" json:"sendAccessEmails,omitempty"`
|
SendAccessEmails bool `url:"sendAccessEmails" json:"sendAccessEmails"`
|
||||||
|
|
||||||
// Limit (positive) or disable (0) GPU resources
|
// Limit (positive) or disable (0) GPU resources
|
||||||
// Required: false
|
// Required: false
|
||||||
GPUUnits uint64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
GPUUnits int64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update updates an account name and resource types and limits
|
// Update updates an account name and resource types and limits
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type UpdateUserRequest struct {
|
|||||||
// - 'RCX' for Write
|
// - 'RCX' for Write
|
||||||
// - 'ARCXDU' for Admin
|
// - 'ARCXDU' for Admin
|
||||||
// Required: true
|
// Required: true
|
||||||
AccessType string `url:"accesstype" json:"accesstype" validate:"required,accountAccessType"`
|
AccessType string `url:"accesstype" json:"accesstype" validate:"required,accessType"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateUser updates user access rights
|
// UpdateUser updates user access rights
|
||||||
|
|||||||
@@ -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]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ type GroupAddRequest struct {
|
|||||||
// - KVM_X86
|
// - KVM_X86
|
||||||
// - KVM_PPC
|
// - KVM_PPC
|
||||||
// Required: true
|
// Required: true
|
||||||
Driver string `url:"driver" json:"driver" validate:"bserviceDriver"`
|
Driver string `url:"driver" json:"driver" validate:"driver"`
|
||||||
|
|
||||||
// Storage endpoint provider ID
|
// Storage endpoint provider ID
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -6,16 +6,40 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for get list/deleted list BasicService instances
|
// Request struct for get list 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"`
|
||||||
@@ -26,7 +50,7 @@ type ListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List gets list BasicService instances associated with the specified Resource Group
|
// List gets list BasicService instances associated with the specified Resource Group
|
||||||
func (b BService) List(ctx context.Context, req ListRequest) (ListBasicServices, error) {
|
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, 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)
|
||||||
@@ -41,24 +65,5 @@ func (b BService) List(ctx context.Context, req ListRequest) (ListBasicServices,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
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
|
|
||||||
}
|
}
|
||||||
|
|||||||
45
pkg/cloudapi/bservice/list_deleted.go
Normal file
45
pkg/cloudapi/bservice/list_deleted.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package bservice
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for 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 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
|
||||||
|
}
|
||||||
@@ -35,11 +35,8 @@ type RecordBasicService struct {
|
|||||||
// Grid ID
|
// Grid ID
|
||||||
GID uint64 `json:"gid"`
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
// List of Service Compute Group IDs
|
// List of Service Compute Groups
|
||||||
Groups []uint64 `json:"groups"`
|
Groups ListGroups `json:"groups"`
|
||||||
|
|
||||||
// List of compute groups by name
|
|
||||||
GroupsName []string `json:"groupsName"`
|
|
||||||
|
|
||||||
// GUID
|
// GUID
|
||||||
GUID uint64 `json:"guid"`
|
GUID uint64 `json:"guid"`
|
||||||
@@ -95,6 +92,12 @@ type RecordBasicService struct {
|
|||||||
|
|
||||||
// Main information about Compute
|
// Main information about Compute
|
||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
|
// Account ID
|
||||||
|
AccountID uint64
|
||||||
|
|
||||||
|
// Architecture
|
||||||
|
Architecture string `json:"arch"`
|
||||||
|
|
||||||
// Compute group ID
|
// Compute group ID
|
||||||
CompGroupID uint64 `json:"compgroupId"`
|
CompGroupID uint64 `json:"compgroupId"`
|
||||||
|
|
||||||
@@ -109,11 +112,47 @@ type ItemCompute struct {
|
|||||||
|
|
||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Resource group ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// StackID
|
||||||
|
StackID uint64 `json:"stackId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Tech status
|
||||||
|
TechStatus string `json:"techStatus"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of Computes
|
// List of Computes
|
||||||
type ListComputes []ItemCompute
|
type ListComputes []ItemCompute
|
||||||
|
|
||||||
|
// Main information about Group
|
||||||
|
type ItemGroup struct {
|
||||||
|
// Amount of computes
|
||||||
|
Computes uint64 `json:"computes"`
|
||||||
|
|
||||||
|
// Consistency
|
||||||
|
Consistency bool `json:"consistency"`
|
||||||
|
|
||||||
|
// Group ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Group name
|
||||||
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// TechStatus
|
||||||
|
TechStatus string `json:"techStatus"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of Groups
|
||||||
|
type ListGroups []ItemGroup
|
||||||
|
|
||||||
// Main information about Snapshot
|
// Main information about Snapshot
|
||||||
type ItemSnapshot struct {
|
type ItemSnapshot struct {
|
||||||
// GUID
|
// GUID
|
||||||
@@ -334,4 +373,8 @@ type ItemBasicService struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List of BasicServices
|
// List of BasicServices
|
||||||
type ListBasicServices []ItemBasicService
|
type ListBasicServices struct {
|
||||||
|
Data []ItemBasicService `json:"data"`
|
||||||
|
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
41
pkg/cloudapi/compute/boot_order_get.go
Normal file
41
pkg/cloudapi/compute/boot_order_get.go
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for getting boot order
|
||||||
|
type BootOrderGetRequest struct {
|
||||||
|
// Compute ID
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BootOrderGet gets actual compute boot order information
|
||||||
|
func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/bootOrderGet"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
orders := make([]string, 0)
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &orders)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return orders, nil
|
||||||
|
}
|
||||||
49
pkg/cloudapi/compute/boot_order_set.go
Normal file
49
pkg/cloudapi/compute/boot_order_set.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for setting boot order
|
||||||
|
type BootOrderSetRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// List of boot devices
|
||||||
|
// Should be one of:
|
||||||
|
// - cdrom
|
||||||
|
// - network
|
||||||
|
// - hd
|
||||||
|
// Required: true
|
||||||
|
Order []string `url:"order" json:"order" validate:"min=1,computeOrder"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BootOrderSet sets compute boot order
|
||||||
|
func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/bootOrderSet"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
orders := make([]string, 0)
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &orders)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return orders, nil
|
||||||
|
}
|
||||||
47
pkg/cloudapi/compute/change_link_state.go
Normal file
47
pkg/cloudapi/compute/change_link_state.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for changing link state
|
||||||
|
type ChangeLinkStateRequest struct {
|
||||||
|
// Compute ID
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Interface name or MAC address
|
||||||
|
// Required: true
|
||||||
|
Interface string `url:"interface" json:"interface" validate:"required"`
|
||||||
|
|
||||||
|
// Interface state
|
||||||
|
// Must be either "on" or "off"
|
||||||
|
// Required: true
|
||||||
|
State string `url:"state" json:"state" validate:"required,interfaceState"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeLinkState changes the status link virtual of compute
|
||||||
|
func (c Compute) ChangeLinkState(ctx context.Context, req ChangeLinkStateRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/changeLinkState"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -18,12 +18,12 @@ type CreateTemplateRequest struct {
|
|||||||
// Name to assign to the template being created
|
// Name to assign to the template being created
|
||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name" validate:"required"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
// Async API call
|
type wrapperCreateTemplateRequest struct {
|
||||||
// For async call use CreateTemplateAsync
|
CreateTemplateRequest
|
||||||
// For sync call use CreateTemplate
|
|
||||||
// Required: true
|
Async bool `url:"async"`
|
||||||
async bool `url:"async"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateTemplate create template from compute instance
|
// CreateTemplate create template from compute instance
|
||||||
@@ -35,11 +35,14 @@ func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.async = false
|
reqWrapped := wrapperCreateTemplateRequest{
|
||||||
|
CreateTemplateRequest: req,
|
||||||
|
Async: false,
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/createTemplate"
|
url := "/cloudapi/compute/createTemplate"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
@@ -61,11 +64,14 @@ func (c Compute) CreateTemplateAsync(ctx context.Context, req CreateTemplateRequ
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.async = true
|
reqWrapped := wrapperCreateTemplateRequest{
|
||||||
|
CreateTemplateRequest: req,
|
||||||
|
Async: true,
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/createTemplate"
|
url := "/cloudapi/compute/createTemplate"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
40
pkg/cloudapi/compute/delete_custom_fields.go
Normal file
40
pkg/cloudapi/compute/delete_custom_fields.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for deleting compute's custome fields
|
||||||
|
type DeleteCustomFieldsRequest struct {
|
||||||
|
// ID of the compute
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCustomFields deletes computes custom fields
|
||||||
|
func (c Compute) DeleteCustomFields(ctx context.Context, req DeleteCustomFieldsRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/deleteCustomFields"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -17,6 +17,10 @@ type DiskAttachRequest struct {
|
|||||||
// ID of the disk to attach
|
// ID of the disk to attach
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Type of the disk B;D
|
||||||
|
// Required: false
|
||||||
|
DiskType string `url:"diskType,omitempty" json:"diskType,omitempty" validate:"omitempty,computeDiskType"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DiskAttach attach disk to compute
|
// DiskAttach attach disk to compute
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ type DiskDelRequest struct {
|
|||||||
|
|
||||||
// False if disk is to be deleted to recycle bin
|
// False if disk is to be deleted to recycle bin
|
||||||
// Required: true
|
// Required: true
|
||||||
Permanently bool `url:"permanently" json:"permanently" validate:"required"`
|
Permanently bool `url:"permanently" json:"permanently"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DiskDel delete disk and detach from compute
|
// DiskDel delete disk and detach from compute
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
package compute
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
|
||||||
|
)
|
||||||
|
|
||||||
// FilterByID returns ListComputes with specified ID.
|
// FilterByID returns ListComputes with specified ID.
|
||||||
func (lc ListComputes) FilterByID(id uint64) ListComputes {
|
func (lc ListComputes) FilterByID(id uint64) ListComputes {
|
||||||
predicate := func(ic ItemCompute) bool {
|
predicate := func(ic ItemCompute) bool {
|
||||||
@@ -36,7 +44,7 @@ func (lc ListComputes) FilterByTechStatus(techStatus string) ListComputes {
|
|||||||
return lc.FilterFunc(predicate)
|
return lc.FilterFunc(predicate)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FilterByDiskID return ListComputes with specified DiskID.
|
// FilterByDiskID returns ListComputes with specified DiskID.
|
||||||
func (lc ListComputes) FilterByDiskID(diskID uint64) ListComputes {
|
func (lc ListComputes) FilterByDiskID(diskID uint64) ListComputes {
|
||||||
predicate := func(ic ItemCompute) bool {
|
predicate := func(ic ItemCompute) bool {
|
||||||
for _, disk := range ic.Disks {
|
for _, disk := range ic.Disks {
|
||||||
@@ -50,25 +58,113 @@ func (lc ListComputes) FilterByDiskID(diskID uint64) ListComputes {
|
|||||||
return lc.FilterFunc(predicate)
|
return lc.FilterFunc(predicate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FilterByK8SID returns master and worker nodes (ListComputes) inside specified K8S cluster.
|
||||||
|
func (lc ListComputes) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient interfaces.Caller) (*ListComputes, error) {
|
||||||
|
caller := k8s.New(decortClient)
|
||||||
|
|
||||||
|
req := k8s.GetRequest{
|
||||||
|
K8SID: k8sID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cluster, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
predicate := func(ic ItemCompute) bool {
|
||||||
|
for _, info := range cluster.K8SGroups.Masters.DetailedInfo {
|
||||||
|
if info.ID == ic.ID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, worker := range cluster.K8SGroups.Workers {
|
||||||
|
for _, info := range worker.DetailedInfo {
|
||||||
|
if info.ID == ic.ID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
res := lc.FilterFunc(predicate)
|
||||||
|
|
||||||
|
return &res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// K8SMasters is used to filter master nodes. Best used after FilterByK8SID function.
|
||||||
|
func (lc ListComputes) FilterByK8SMasters() ListComputes {
|
||||||
|
predicate := func(ic ItemCompute) bool {
|
||||||
|
for _, rule := range ic.AntiAffinityRules {
|
||||||
|
if rule.Value == "master" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return lc.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// K8SMasters is used to filter worker nodes. Best used after FilterByK8SID function.
|
||||||
|
func (lc ListComputes) FilterByK8SWorkers() ListComputes {
|
||||||
|
predicate := func(ic ItemCompute) bool {
|
||||||
|
for _, rule := range ic.AntiAffinityRules {
|
||||||
|
if rule.Value == "worker" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return lc.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByLBID returns ListComputes used by specified Load Balancer.
|
||||||
|
func (lc ListComputes) FilterByLBID(ctx context.Context, lbID uint64, decortClient interfaces.Caller) (*ListComputes, error) {
|
||||||
|
caller := lb.New(decortClient)
|
||||||
|
|
||||||
|
req := lb.GetRequest{
|
||||||
|
LBID: lbID,
|
||||||
|
}
|
||||||
|
|
||||||
|
foundLB, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
predicate := func(ic ItemCompute) bool {
|
||||||
|
return ic.ID == foundLB.PrimaryNode.ComputeID || ic.ID == foundLB.SecondaryNode.ComputeID
|
||||||
|
}
|
||||||
|
|
||||||
|
res := lc.FilterFunc(predicate)
|
||||||
|
|
||||||
|
return &res, nil
|
||||||
|
}
|
||||||
|
|
||||||
// FilterFunc allows filtering ListComputes based on a user-specified predicate.
|
// FilterFunc allows filtering ListComputes based on a user-specified predicate.
|
||||||
func (lc ListComputes) FilterFunc(predicate func(ItemCompute) bool) ListComputes {
|
func (lc ListComputes) FilterFunc(predicate func(ItemCompute) bool) ListComputes {
|
||||||
var result ListComputes
|
var result ListComputes
|
||||||
|
|
||||||
for _, item := range lc {
|
for _, item := range lc.Data {
|
||||||
if predicate(item) {
|
if predicate(item) {
|
||||||
result = append(result, item)
|
result.Data = append(result.Data, item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// FindOne returns first found ItemCompute
|
// FindOne returns first found ItemCompute
|
||||||
// If none was found, returns an empty struct.
|
// If none was found, returns an empty struct.
|
||||||
func (lc ListComputes) FindOne() ItemCompute {
|
func (lc ListComputes) FindOne() ItemCompute {
|
||||||
if len(lc) == 0 {
|
if len(lc.Data) == 0 {
|
||||||
return ItemCompute{}
|
return ItemCompute{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[0]
|
return lc.Data[0]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,239 +3,242 @@ package compute
|
|||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
var computes = ListComputes{
|
var computes = ListComputes{
|
||||||
ItemCompute{
|
Data: []ItemCompute{
|
||||||
ACL: []interface{}{},
|
{
|
||||||
AccountID: 132847,
|
ACL: ListACL{},
|
||||||
AccountName: "std_2",
|
AccountID: 132847,
|
||||||
AffinityLabel: "",
|
AccountName: "std_2",
|
||||||
AffinityRules: []ItemRule{
|
AffinityLabel: "",
|
||||||
{
|
AffinityRules: []ItemRule{
|
||||||
GUID: "",
|
{
|
||||||
Key: "aff_key",
|
GUID: "",
|
||||||
Mode: "ANY",
|
Key: "aff_key",
|
||||||
Policy: "RECOMMENDED",
|
Mode: "ANY",
|
||||||
Topology: "compute",
|
Policy: "RECOMMENDED",
|
||||||
Value: "aff_val",
|
Topology: "compute",
|
||||||
|
Value: "aff_val",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
AffinityWeight: 0,
|
||||||
AffinityWeight: 0,
|
AntiAffinityRules: []ItemRule{
|
||||||
AntiAffinityRules: []ItemRule{
|
{
|
||||||
{
|
GUID: "",
|
||||||
GUID: "",
|
Key: "antiaff_key",
|
||||||
Key: "antiaff_key",
|
Mode: "ANY",
|
||||||
Mode: "ANY",
|
Policy: "RECOMMENDED",
|
||||||
Policy: "RECOMMENDED",
|
Topology: "compute",
|
||||||
Topology: "compute",
|
Value: "antiaff_val",
|
||||||
Value: "antiaff_val",
|
},
|
||||||
},
|
},
|
||||||
},
|
Architecture: "X86_64",
|
||||||
Architecture: "X86_64",
|
BootOrder: []string{
|
||||||
BootOrder: []string{
|
"hd", "cdrom",
|
||||||
"hd", "cdrom",
|
|
||||||
},
|
|
||||||
BootDiskSize: 0,
|
|
||||||
CloneReference: 0,
|
|
||||||
Clones: []uint64{},
|
|
||||||
ComputeCIID: 0,
|
|
||||||
CPU: 4,
|
|
||||||
CreatedBy: "timofey_tkachev_1@decs3o",
|
|
||||||
CreatedTime: 1676975175,
|
|
||||||
CustomFields: map[string]interface{}{},
|
|
||||||
DeletedBy: "",
|
|
||||||
DeletedTime: 0,
|
|
||||||
Description: "",
|
|
||||||
Devices: nil,
|
|
||||||
Disks: []InfoDisk{
|
|
||||||
{
|
|
||||||
ID: 65191,
|
|
||||||
PCISlot: 6,
|
|
||||||
},
|
},
|
||||||
|
BootDiskSize: 0,
|
||||||
|
CloneReference: 0,
|
||||||
|
Clones: []uint64{},
|
||||||
|
ComputeCIID: 0,
|
||||||
|
CPU: 4,
|
||||||
|
CreatedBy: "timofey_tkachev_1@decs3o",
|
||||||
|
CreatedTime: 1676975175,
|
||||||
|
CustomFields: map[string]interface{}{},
|
||||||
|
DeletedBy: "",
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
Devices: nil,
|
||||||
|
Disks: []InfoDisk{
|
||||||
|
{
|
||||||
|
ID: 65191,
|
||||||
|
PCISlot: 6,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Driver: "KVM_X86",
|
||||||
|
GID: 212,
|
||||||
|
GUID: 48500,
|
||||||
|
ID: 48500,
|
||||||
|
ImageID: 9884,
|
||||||
|
Interfaces: []ItemVNFInterface{},
|
||||||
|
LockStatus: "UNLOCKED",
|
||||||
|
ManagerID: 0,
|
||||||
|
ManagerType: "",
|
||||||
|
MigrationJob: 0,
|
||||||
|
Milestones: 363500,
|
||||||
|
Name: "test",
|
||||||
|
Pinned: false,
|
||||||
|
RAM: 4096,
|
||||||
|
ReferenceID: "c7cb19ac-af4a-4067-852f-c5572949207e",
|
||||||
|
Registered: true,
|
||||||
|
ResName: "compute-48500",
|
||||||
|
RGID: 79724,
|
||||||
|
RGName: "std_broker2",
|
||||||
|
SnapSets: []ItemSnapSet{},
|
||||||
|
StatelessSepID: 0,
|
||||||
|
StatelessSepType: "",
|
||||||
|
Status: "ENABLED",
|
||||||
|
Tags: map[string]string{},
|
||||||
|
TechStatus: "STOPPED",
|
||||||
|
TotalDiskSize: 2,
|
||||||
|
UpdatedBy: "",
|
||||||
|
UpdatedTime: 1677058904,
|
||||||
|
UserManaged: true,
|
||||||
|
VGPUs: []uint64{},
|
||||||
|
VINSConnected: 0,
|
||||||
|
VirtualImageID: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ACL: ListACL{},
|
||||||
|
AccountID: 132848,
|
||||||
|
AccountName: "std_broker",
|
||||||
|
AffinityLabel: "",
|
||||||
|
AffinityRules: []ItemRule{},
|
||||||
|
AffinityWeight: 0,
|
||||||
|
AntiAffinityRules: []ItemRule{},
|
||||||
|
Architecture: "X86_64",
|
||||||
|
BootOrder: []string{
|
||||||
|
"hd", "cdrom",
|
||||||
|
},
|
||||||
|
BootDiskSize: 0,
|
||||||
|
CloneReference: 0,
|
||||||
|
Clones: []uint64{},
|
||||||
|
ComputeCIID: 0,
|
||||||
|
CPU: 6,
|
||||||
|
CreatedBy: "timofey_tkachev_1@decs3o",
|
||||||
|
CreatedTime: 1677579436,
|
||||||
|
CustomFields: map[string]interface{}{},
|
||||||
|
DeletedBy: "",
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
Devices: nil,
|
||||||
|
Disks: []InfoDisk{
|
||||||
|
{
|
||||||
|
ID: 65248,
|
||||||
|
PCISlot: 6,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Driver: "KVM_X86",
|
||||||
|
GID: 212,
|
||||||
|
GUID: 48556,
|
||||||
|
ID: 48556,
|
||||||
|
ImageID: 9884,
|
||||||
|
Interfaces: []ItemVNFInterface{},
|
||||||
|
LockStatus: "UNLOCKED",
|
||||||
|
ManagerID: 0,
|
||||||
|
ManagerType: "",
|
||||||
|
MigrationJob: 0,
|
||||||
|
Milestones: 363853,
|
||||||
|
Name: "compute_2",
|
||||||
|
Pinned: false,
|
||||||
|
RAM: 4096,
|
||||||
|
ReferenceID: "a542c449-5b1c-4f90-88c5-7bb5f8ae68ff",
|
||||||
|
Registered: true,
|
||||||
|
ResName: "compute-48556",
|
||||||
|
RGID: 79727,
|
||||||
|
RGName: "sdk_negative_fields_test",
|
||||||
|
SnapSets: []ItemSnapSet{},
|
||||||
|
StatelessSepID: 0,
|
||||||
|
StatelessSepType: "",
|
||||||
|
Status: "ENABLED",
|
||||||
|
Tags: map[string]string{},
|
||||||
|
TechStatus: "STARTED",
|
||||||
|
TotalDiskSize: 1,
|
||||||
|
UpdatedBy: "",
|
||||||
|
UpdatedTime: 1677579436,
|
||||||
|
UserManaged: true,
|
||||||
|
VGPUs: []uint64{},
|
||||||
|
VINSConnected: 0,
|
||||||
|
VirtualImageID: 0,
|
||||||
},
|
},
|
||||||
Driver: "KVM_X86",
|
|
||||||
GID: 212,
|
|
||||||
GUID: 48500,
|
|
||||||
ID: 48500,
|
|
||||||
ImageID: 9884,
|
|
||||||
Interfaces: []ItemVNFInterface{},
|
|
||||||
LockStatus: "UNLOCKED",
|
|
||||||
ManagerID: 0,
|
|
||||||
ManagerType: "",
|
|
||||||
MigrationJob: 0,
|
|
||||||
Milestones: 363500,
|
|
||||||
Name: "test",
|
|
||||||
Pinned: false,
|
|
||||||
RAM: 4096,
|
|
||||||
ReferenceID: "c7cb19ac-af4a-4067-852f-c5572949207e",
|
|
||||||
Registered: true,
|
|
||||||
ResName: "compute-48500",
|
|
||||||
RGID: 79724,
|
|
||||||
RGName: "std_broker2",
|
|
||||||
SnapSets: []ItemSnapSet{},
|
|
||||||
StatelessSepID: 0,
|
|
||||||
StatelessSepType: "",
|
|
||||||
Status: "ENABLED",
|
|
||||||
Tags: map[string]string{},
|
|
||||||
TechStatus: "STOPPED",
|
|
||||||
TotalDiskSize: 2,
|
|
||||||
UpdatedBy: "",
|
|
||||||
UpdatedTime: 1677058904,
|
|
||||||
UserManaged: true,
|
|
||||||
VGPUs: []uint64{},
|
|
||||||
VINSConnected: 0,
|
|
||||||
VirtualImageID: 0,
|
|
||||||
},
|
|
||||||
ItemCompute{
|
|
||||||
ACL: []interface{}{},
|
|
||||||
AccountID: 132848,
|
|
||||||
AccountName: "std_broker",
|
|
||||||
AffinityLabel: "",
|
|
||||||
AffinityRules: []ItemRule{},
|
|
||||||
AffinityWeight: 0,
|
|
||||||
AntiAffinityRules: []ItemRule{},
|
|
||||||
Architecture: "X86_64",
|
|
||||||
BootOrder: []string{
|
|
||||||
"hd", "cdrom",
|
|
||||||
},
|
|
||||||
BootDiskSize: 0,
|
|
||||||
CloneReference: 0,
|
|
||||||
Clones: []uint64{},
|
|
||||||
ComputeCIID: 0,
|
|
||||||
CPU: 6,
|
|
||||||
CreatedBy: "timofey_tkachev_1@decs3o",
|
|
||||||
CreatedTime: 1677579436,
|
|
||||||
CustomFields: map[string]interface{}{},
|
|
||||||
DeletedBy: "",
|
|
||||||
DeletedTime: 0,
|
|
||||||
Description: "",
|
|
||||||
Devices: nil,
|
|
||||||
Disks: []InfoDisk{
|
|
||||||
{
|
|
||||||
ID: 65248,
|
|
||||||
PCISlot: 6,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Driver: "KVM_X86",
|
|
||||||
GID: 212,
|
|
||||||
GUID: 48556,
|
|
||||||
ID: 48556,
|
|
||||||
ImageID: 9884,
|
|
||||||
Interfaces: []ItemVNFInterface{},
|
|
||||||
LockStatus: "UNLOCKED",
|
|
||||||
ManagerID: 0,
|
|
||||||
ManagerType: "",
|
|
||||||
MigrationJob: 0,
|
|
||||||
Milestones: 363853,
|
|
||||||
Name: "compute_2",
|
|
||||||
Pinned: false,
|
|
||||||
RAM: 4096,
|
|
||||||
ReferenceID: "a542c449-5b1c-4f90-88c5-7bb5f8ae68ff",
|
|
||||||
Registered: true,
|
|
||||||
ResName: "compute-48556",
|
|
||||||
RGID: 79727,
|
|
||||||
RGName: "sdk_negative_fields_test",
|
|
||||||
SnapSets: []ItemSnapSet{},
|
|
||||||
StatelessSepID: 0,
|
|
||||||
StatelessSepType: "",
|
|
||||||
Status: "ENABLED",
|
|
||||||
Tags: map[string]string{},
|
|
||||||
TechStatus: "STARTED",
|
|
||||||
TotalDiskSize: 1,
|
|
||||||
UpdatedBy: "",
|
|
||||||
UpdatedTime: 1677579436,
|
|
||||||
UserManaged: true,
|
|
||||||
VGPUs: []uint64{},
|
|
||||||
VINSConnected: 0,
|
|
||||||
VirtualImageID: 0,
|
|
||||||
},
|
},
|
||||||
|
EntryCount: 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByID(t *testing.T) {
|
func TestFilterByID(t *testing.T) {
|
||||||
actual := computes.FilterByID(48500).FindOne()
|
actual := computes.FilterByID(48500).FindOne()
|
||||||
|
|
||||||
if actual.ID != 48500 {
|
if actual.ID != 48500 {
|
||||||
t.Fatal("expected ID 48500, found: ", actual.ID)
|
t.Fatal("expected ID 48500, found: ", actual.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
actualEmpty := computes.FilterByID(0)
|
actualEmpty := computes.FilterByID(0)
|
||||||
|
|
||||||
if len(actualEmpty) != 0 {
|
if len(actualEmpty.Data) != 0 {
|
||||||
t.Fatal("expected empty, actual: ", len(actualEmpty))
|
t.Fatal("expected empty, actual: ", len(actualEmpty.Data))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByName(t *testing.T) {
|
func TestFilterByName(t *testing.T) {
|
||||||
actual := computes.FilterByName("test").FindOne()
|
actual := computes.FilterByName("test").FindOne()
|
||||||
|
|
||||||
if actual.Name != "test" {
|
if actual.Name != "test" {
|
||||||
t.Fatal("expected compute with name 'test', found: ", actual.Name)
|
t.Fatal("expected compute with name 'test', found: ", actual.Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByStatus(t *testing.T) {
|
func TestFilterByStatus(t *testing.T) {
|
||||||
actual := computes.FilterByStatus("ENABLED")
|
actual := computes.FilterByStatus("ENABLED")
|
||||||
|
|
||||||
for _, item := range actual {
|
for _, item := range actual.Data {
|
||||||
if item.Status != "ENABLED" {
|
if item.Status != "ENABLED" {
|
||||||
t.Fatal("expected ENABLED status, found: ", item.Status)
|
t.Fatal("expected ENABLED status, found: ", item.Status)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByTechStatus(t *testing.T) {
|
func TestFilterByTechStatus(t *testing.T) {
|
||||||
actual := computes.FilterByTechStatus("STARTED").FindOne()
|
actual := computes.FilterByTechStatus("STARTED").FindOne()
|
||||||
|
|
||||||
if actual.ID != 48556 {
|
if actual.ID != 48556 {
|
||||||
t.Fatal("expected 48556 with STARTED techStatus, found: ", actual.ID)
|
t.Fatal("expected 48556 with STARTED techStatus, found: ", actual.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByDiskID(t *testing.T) {
|
func TestFilterByDiskID(t *testing.T) {
|
||||||
actual := computes.FilterByDiskID(65248).FindOne()
|
actual := computes.FilterByDiskID(65248).FindOne()
|
||||||
|
|
||||||
if actual.ID != 48556 {
|
if actual.ID != 48556 {
|
||||||
t.Fatal("expected 48556 with DiskID 65248, found: ", actual.ID)
|
t.Fatal("expected 48556 with DiskID 65248, found: ", actual.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterFunc(t *testing.T) {
|
func TestFilterFunc(t *testing.T) {
|
||||||
actual := computes.FilterFunc(func(ic ItemCompute) bool {
|
actual := computes.FilterFunc(func(ic ItemCompute) bool {
|
||||||
return ic.Registered == true
|
return ic.Registered == true
|
||||||
})
|
})
|
||||||
|
|
||||||
if len(actual) != 2 {
|
if len(actual.Data) != 2 {
|
||||||
t.Fatal("expected 2 elements found, actual: ", len(actual))
|
t.Fatal("expected 2 elements found, actual: ", len(actual.Data))
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, item := range actual {
|
for _, item := range actual.Data {
|
||||||
if item.Registered != true {
|
if item.Registered != true {
|
||||||
t.Fatal("expected Registered to be true, actual: ", item.Registered)
|
t.Fatal("expected Registered to be true, actual: ", item.Registered)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSortingByCreatedTime(t *testing.T) {
|
func TestSortingByCreatedTime(t *testing.T) {
|
||||||
actual := computes.SortByCreatedTime(false)
|
actual := computes.SortByCreatedTime(false)
|
||||||
|
|
||||||
if actual[0].Name != "test" {
|
if actual.Data[0].Name != "test" {
|
||||||
t.Fatal("expected 'test', found: ", actual[0].Name)
|
t.Fatal("expected 'test', found: ", actual.Data[0].Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
actual = computes.SortByCreatedTime(true)
|
actual = computes.SortByCreatedTime(true)
|
||||||
if actual[0].Name != "compute_2" {
|
if actual.Data[0].Name != "compute_2" {
|
||||||
t.Fatal("expected 'compute_2', found: ", actual[0].Name)
|
t.Fatal("expected 'compute_2', found: ", actual.Data[0].Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSortingByCPU(t *testing.T) {
|
func TestSortingByCPU(t *testing.T) {
|
||||||
actual := computes.SortByCPU(false)
|
actual := computes.SortByCPU(false)
|
||||||
|
|
||||||
if actual[0].CPU != 4{
|
if actual.Data[0].CPU != 4 {
|
||||||
t.Fatal("expected 4 CPU cores, found: ", actual[0].CPU)
|
t.Fatal("expected 4 CPU cores, found: ", actual.Data[0].CPU)
|
||||||
}
|
}
|
||||||
|
|
||||||
actual = computes.SortByCPU(true)
|
actual = computes.SortByCPU(true)
|
||||||
|
|
||||||
if actual[0].CPU != 6 {
|
if actual.Data[0].CPU != 6 {
|
||||||
t.Fatal("expected 6 CPU cores, found: ", actual[0].CPU)
|
t.Fatal("expected 6 CPU cores, found: ", actual.Data[0].CPU)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
pkg/cloudapi/compute/get_custom_fields.go
Normal file
42
pkg/cloudapi/compute/get_custom_fields.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for getting Compute's customFields
|
||||||
|
type GetCustomFieldsRequest struct {
|
||||||
|
// Compute ID
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCustomFields gets Compute's customFields
|
||||||
|
func (c Compute) GetCustomFields(ctx context.Context, req GetCustomFieldsRequest) (interface{}, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/getCustomFields"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var info interface{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &info)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
@@ -8,6 +8,46 @@ import (
|
|||||||
|
|
||||||
// Request struct for get list available computes
|
// Request struct for get list available computes
|
||||||
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 account ID
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,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 status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,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"`
|
||||||
|
|
||||||
// Include deleted computes
|
// Include deleted computes
|
||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
@@ -23,7 +63,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of the available computes.
|
// List gets list of the available computes.
|
||||||
// Filtering based on status is possible
|
// Filtering based on status is possible
|
||||||
func (c Compute) List(ctx context.Context, req ListRequest) (ListComputes, error) {
|
func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, error) {
|
||||||
url := "/cloudapi/compute/list"
|
url := "/cloudapi/compute/list"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -38,5 +78,5 @@ func (c Compute) List(ctx context.Context, req ListRequest) (ListComputes, error
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,42 @@ import (
|
|||||||
|
|
||||||
// Request struct for get deleted computes list
|
// Request struct for get deleted computes list
|
||||||
type ListDeletedRequest struct {
|
type ListDeletedRequest 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 account ID
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,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
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -18,7 +54,7 @@ type ListDeletedRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListDeleted gets list all deleted computes
|
// ListDeleted gets list all deleted computes
|
||||||
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (ListComputes, error) {
|
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListComputes, error) {
|
||||||
url := "/cloudapi/compute/listDeleted"
|
url := "/cloudapi/compute/listDeleted"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -33,5 +69,5 @@ func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (ListC
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,34 @@ type ListPCIDeviceRequest struct {
|
|||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Find by resource group ID
|
||||||
|
// Required: false
|
||||||
|
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||||
|
|
||||||
|
// Find by device id
|
||||||
|
// Required: false
|
||||||
|
DevID uint64 `url:"devId,omitempty" json:"devId,omitempty"`
|
||||||
|
|
||||||
|
// Find by type
|
||||||
|
// Required: false
|
||||||
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListPCIDevice gets list PCI device
|
// ListPCIDevice gets list PCI device
|
||||||
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) ([]interface{}, error) {
|
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) (*ListPCIDevices, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, validationError := range validators.GetErrors(err) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -31,12 +55,12 @@ func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) ([
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := []interface{}{}
|
list := ListPCIDevices{}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,34 @@ type ListVGPURequest struct {
|
|||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Find by GPU id
|
||||||
|
// Required: false
|
||||||
|
GPUID uint64 `url:"gpuId,omitempty" json:"gpuId,omitempty"`
|
||||||
|
|
||||||
|
// Find by type
|
||||||
|
// Required: false
|
||||||
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
|
||||||
|
// Include deleted computes. If using field 'status', then includedeleted will be ignored
|
||||||
|
// Required: false
|
||||||
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListVGPU gets list vGPU
|
// ListVGPU gets list vGPU
|
||||||
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) ([]interface{}, error) {
|
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) (*ListVGPUs, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, validationError := range validators.GetErrors(err) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -24,19 +48,19 @@ func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) ([]interface
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/listVgpu"
|
url := "/cloudapi/compute/listVGpu"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := []interface{}{}
|
list := ListVGPUs{}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package compute
|
package compute
|
||||||
|
|
||||||
|
import "strconv"
|
||||||
|
|
||||||
// Access Control List
|
// Access Control List
|
||||||
type RecordACL struct {
|
type RecordACL struct {
|
||||||
// Account ACL list
|
// Account ACL list
|
||||||
@@ -12,10 +14,35 @@ type RecordACL struct {
|
|||||||
RGACL ListACL `json:"rgAcl"`
|
RGACL ListACL `json:"rgAcl"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ListUsers struct {
|
||||||
|
// Data
|
||||||
|
Data RecordACL `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Explicit bool
|
||||||
|
|
||||||
|
func (e *Explicit) UnmarshalJSON(b []byte) error {
|
||||||
|
if b[0] == '"' {
|
||||||
|
b = b[1 : len(b)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := strconv.ParseBool(string(b))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*e = Explicit(res)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// ACL information
|
// ACL information
|
||||||
type ItemACL struct {
|
type ItemACL struct {
|
||||||
// Explicit
|
// Explicit
|
||||||
Explicit bool `json:"explicit"`
|
Explicit Explicit `json:"explicit"`
|
||||||
|
|
||||||
// GUID
|
// GUID
|
||||||
GUID string `json:"guid"`
|
GUID string `json:"guid"`
|
||||||
@@ -70,7 +97,13 @@ type ItemSnapshot struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List of snapshots
|
// List of snapshots
|
||||||
type ListSnapShots []ItemSnapshot
|
type ListSnapShots struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemSnapshot `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about port forward
|
// Main information about port forward
|
||||||
type ItemPFW struct {
|
type ItemPFW struct {
|
||||||
@@ -97,7 +130,13 @@ type ItemPFW struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List port forwards
|
// List port forwards
|
||||||
type ListPFWs []ItemPFW
|
type ListPFWs struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemPFW `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about affinity relations
|
// Main information about affinity relations
|
||||||
type RecordAffinityRelations struct {
|
type RecordAffinityRelations struct {
|
||||||
@@ -131,6 +170,9 @@ type RecordNetAttach struct {
|
|||||||
// Default GW
|
// Default GW
|
||||||
DefGW string `json:"defGw"`
|
DefGW string `json:"defGw"`
|
||||||
|
|
||||||
|
// Enabled
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
|
||||||
// FLIPGroup ID
|
// FLIPGroup ID
|
||||||
FLIPGroupID uint64 `json:"flipgroupId"`
|
FLIPGroupID uint64 `json:"flipgroupId"`
|
||||||
|
|
||||||
@@ -159,7 +201,7 @@ type RecordNetAttach struct {
|
|||||||
NetType string `json:"netType"`
|
NetType string `json:"netType"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot uint64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
// QOS
|
// QOS
|
||||||
QOS QOS `json:"qos"`
|
QOS QOS `json:"qos"`
|
||||||
@@ -381,7 +423,7 @@ type RecordCompute struct {
|
|||||||
SnapSets ListSnapSets `json:"snapSets"`
|
SnapSets ListSnapSets `json:"snapSets"`
|
||||||
|
|
||||||
// Stateless SepID
|
// Stateless SepID
|
||||||
StatelessSepID uint64 `json:"statelessSepId"`
|
StatelessSepID int64 `json:"statelessSepId"`
|
||||||
|
|
||||||
// Stateless SepType
|
// Stateless SepType
|
||||||
StatelessSepType string `json:"statelessSepType"`
|
StatelessSepType string `json:"statelessSepType"`
|
||||||
@@ -464,6 +506,9 @@ type ItemVNFInterface struct {
|
|||||||
// Default GW
|
// Default GW
|
||||||
DefGW string `json:"defGw"`
|
DefGW string `json:"defGw"`
|
||||||
|
|
||||||
|
// Enabled
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
|
||||||
// FLIPGroup ID
|
// FLIPGroup ID
|
||||||
FLIPGroupID uint64 `json:"flipgroupId"`
|
FLIPGroupID uint64 `json:"flipgroupId"`
|
||||||
|
|
||||||
@@ -492,7 +537,7 @@ type ItemVNFInterface struct {
|
|||||||
NetType string `json:"netType"`
|
NetType string `json:"netType"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot uint64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
// QOS
|
// QOS
|
||||||
QOS QOS `json:"qos"`
|
QOS QOS `json:"qos"`
|
||||||
@@ -592,7 +637,7 @@ type ItemComputeDisk struct {
|
|||||||
Passwd string `json:"passwd"`
|
Passwd string `json:"passwd"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot uint64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
// Pool
|
// Pool
|
||||||
Pool string `json:"pool"`
|
Pool string `json:"pool"`
|
||||||
@@ -648,6 +693,9 @@ type SnapshotExtend struct {
|
|||||||
// Label
|
// Label
|
||||||
Label string `json:"label"`
|
Label string `json:"label"`
|
||||||
|
|
||||||
|
// Reference ID
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
@@ -709,8 +757,7 @@ type IOTune struct {
|
|||||||
// Main information about compute
|
// Main information about compute
|
||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
// Access Control List
|
// Access Control List
|
||||||
ACL []interface{} `json:"acl"`
|
ACL ListACL `json:"acl"`
|
||||||
|
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64 `json:"accountId"`
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
@@ -835,7 +882,7 @@ type ItemCompute struct {
|
|||||||
SnapSets ListSnapSets `json:"snapSets"`
|
SnapSets ListSnapSets `json:"snapSets"`
|
||||||
|
|
||||||
// Stateless SepID
|
// Stateless SepID
|
||||||
StatelessSepID uint64 `json:"statelessSepId"`
|
StatelessSepID int64 `json:"statelessSepId"`
|
||||||
|
|
||||||
// Stateless SepType
|
// Stateless SepType
|
||||||
StatelessSepType string `json:"statelessSepType"`
|
StatelessSepType string `json:"statelessSepType"`
|
||||||
@@ -877,8 +924,32 @@ type InfoDisk struct {
|
|||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
// PCISlot
|
// PCISlot
|
||||||
PCISlot uint64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List information about computes
|
// List information about computes
|
||||||
type ListComputes []ItemCompute
|
type ListComputes struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemCompute `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List VGPUs
|
||||||
|
type ListVGPUs struct {
|
||||||
|
// Data
|
||||||
|
Data []interface{} `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List PCI devices
|
||||||
|
type ListPCIDevices struct {
|
||||||
|
// Data
|
||||||
|
Data []interface{} `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,8 +19,9 @@ type PFWAddRequest struct {
|
|||||||
PublicPortStart uint64 `url:"publicPortStart" json:"publicPortStart" validate:"required"`
|
PublicPortStart uint64 `url:"publicPortStart" json:"publicPortStart" validate:"required"`
|
||||||
|
|
||||||
// End port number (inclusive) for the ranged rule
|
// End port number (inclusive) for the ranged rule
|
||||||
|
// Default value: -1
|
||||||
// Required: false
|
// Required: false
|
||||||
PublicPortEnd uint64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
PublicPortEnd int64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
||||||
|
|
||||||
// Internal base port number
|
// Internal base port number
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -29,7 +30,7 @@ type PFWAddRequest struct {
|
|||||||
// Network protocol
|
// Network protocol
|
||||||
// either "tcp" or "udp"
|
// either "tcp" or "udp"
|
||||||
// Required: true
|
// Required: true
|
||||||
Proto string `url:"proto" json:"proto" validate:"computeProto"`
|
Proto string `url:"proto" json:"proto" validate:"proto"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PFWAdd add port forward rule
|
// PFWAdd add port forward rule
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type PFWListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PFWList gets compute port forwards list
|
// PFWList gets compute port forwards list
|
||||||
func (c Compute) PFWList(ctx context.Context, req PFWListRequest) (ListPFWs, error) {
|
func (c Compute) PFWList(ctx context.Context, req PFWListRequest) (*ListPFWs, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, validationError := range validators.GetErrors(err) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +38,5 @@ func (c Compute) PFWList(ctx context.Context, req PFWListRequest) (ListPFWs, err
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,16 +17,16 @@ type ResizeRequest struct {
|
|||||||
// New CPU count.
|
// New CPU count.
|
||||||
// Pass 0 if no change to CPU count is required
|
// Pass 0 if no change to CPU count is required
|
||||||
// Required: false
|
// Required: false
|
||||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
CPU uint64 `url:"cpu,omitempty" json:"cpu,omitempty"`
|
||||||
|
|
||||||
// New RAM volume in MB.
|
// New RAM volume in MB.
|
||||||
// Pass 0 if no change to RAM volume is required
|
// Pass 0 if no change to RAM volume is required
|
||||||
// Required: false
|
// Required: false
|
||||||
CPU uint64 `url:"cpu,omitempty" json:"cpu,omitempty"`
|
RAM uint64 `url:"ram,omitempty" json:"ram,omitempty"`
|
||||||
|
|
||||||
// Force compute resize
|
// Force compute resize
|
||||||
// Required: false
|
// Required: false
|
||||||
RAM uint64 `url:"ram,omitempty" json:"ram,omitempty"`
|
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resize resize compute instance
|
// Resize resize compute instance
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
// - First argument -> prefix
|
// - First argument -> prefix
|
||||||
// - Second argument -> indent
|
// - Second argument -> indent
|
||||||
func (lc ListComputes) Serialize(params ...string) (serialization.Serialized, error) {
|
func (lc ListComputes) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
if len(lc) == 0 {
|
if lc.EntryCount == 0 {
|
||||||
return []byte{}, nil
|
return []byte{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
43
pkg/cloudapi/compute/set_custom_fields.go
Normal file
43
pkg/cloudapi/compute/set_custom_fields.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
// Request struct for setting customFields values for the Compute
|
||||||
|
type SetCustomFieldsRequest struct {
|
||||||
|
// ID of the compute
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Custom fields for Compute. Must be dict.
|
||||||
|
// Required: true
|
||||||
|
CustomFields string `url:"customFields" json:"customFields" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetCustomFields sets customFields values for the Compute
|
||||||
|
func (c Compute) SetCustomFields(ctx context.Context, req SetCustomFieldsRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/setCustomFields"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ type SnapshotListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SnapshotList gets list compute snapshots
|
// SnapshotList gets list compute snapshots
|
||||||
func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (ListSnapShots, error) {
|
func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (*ListSnapShots, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, validationError := range validators.GetErrors(err) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -38,5 +38,5 @@ func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (Lis
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 (lc ListComputes) SortByCPU(inverse bool) ListComputes {
|
func (lc ListComputes) SortByCPU(inverse bool) ListComputes {
|
||||||
if len(lc) < 2 {
|
if len(lc.Data) < 2 {
|
||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lc, func(i, j int) bool {
|
sort.Slice(lc.Data, func(i, j int) bool {
|
||||||
if inverse {
|
if inverse {
|
||||||
return lc[i].CPU > lc[j].CPU
|
return lc.Data[i].CPU > lc.Data[j].CPU
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[i].CPU < lc[j].CPU
|
return lc.Data[i].CPU < lc.Data[j].CPU
|
||||||
})
|
})
|
||||||
|
|
||||||
return lc
|
return lc
|
||||||
@@ -25,16 +25,16 @@ func (lc ListComputes) SortByCPU(inverse bool) ListComputes {
|
|||||||
//
|
//
|
||||||
// If inverse param is set to true, the order is reversed.
|
// If inverse param is set to true, the order is reversed.
|
||||||
func (lc ListComputes) SortByRAM(inverse bool) ListComputes {
|
func (lc ListComputes) SortByRAM(inverse bool) ListComputes {
|
||||||
if len(lc) < 2 {
|
if len(lc.Data) < 2 {
|
||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lc, func(i, j int) bool {
|
sort.Slice(lc.Data, func(i, j int) bool {
|
||||||
if inverse {
|
if inverse {
|
||||||
return lc[i].RAM > lc[j].RAM
|
return lc.Data[i].RAM > lc.Data[j].RAM
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[i].RAM < lc[j].RAM
|
return lc.Data[i].RAM < lc.Data[j].RAM
|
||||||
})
|
})
|
||||||
|
|
||||||
return lc
|
return lc
|
||||||
@@ -44,16 +44,16 @@ func (lc ListComputes) SortByRAM(inverse bool) ListComputes {
|
|||||||
//
|
//
|
||||||
// If inverse param is set to true, the order is reversed.
|
// If inverse param is set to true, the order is reversed.
|
||||||
func (lc ListComputes) SortByCreatedTime(inverse bool) ListComputes {
|
func (lc ListComputes) SortByCreatedTime(inverse bool) ListComputes {
|
||||||
if len(lc) < 2 {
|
if len(lc.Data) < 2 {
|
||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lc, func(i, j int) bool {
|
sort.Slice(lc.Data, func(i, j int) bool {
|
||||||
if inverse {
|
if inverse {
|
||||||
return lc[i].CreatedTime > lc[j].CreatedTime
|
return lc.Data[i].CreatedTime > lc.Data[j].CreatedTime
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[i].CreatedTime < lc[j].CreatedTime
|
return lc.Data[i].CreatedTime < lc.Data[j].CreatedTime
|
||||||
})
|
})
|
||||||
|
|
||||||
return lc
|
return lc
|
||||||
@@ -63,16 +63,16 @@ func (lc ListComputes) SortByCreatedTime(inverse bool) ListComputes {
|
|||||||
//
|
//
|
||||||
// If inverse param is set to true, the order is reversed.
|
// If inverse param is set to true, the order is reversed.
|
||||||
func (lc ListComputes) SortByUpdatedTime(inverse bool) ListComputes {
|
func (lc ListComputes) SortByUpdatedTime(inverse bool) ListComputes {
|
||||||
if len(lc) < 2 {
|
if len(lc.Data) < 2 {
|
||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lc, func(i, j int) bool {
|
sort.Slice(lc.Data, func(i, j int) bool {
|
||||||
if inverse {
|
if inverse {
|
||||||
return lc[i].UpdatedTime > lc[j].UpdatedTime
|
return lc.Data[i].UpdatedTime > lc.Data[j].UpdatedTime
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[i].UpdatedTime < lc[j].UpdatedTime
|
return lc.Data[i].UpdatedTime < lc.Data[j].UpdatedTime
|
||||||
})
|
})
|
||||||
|
|
||||||
return lc
|
return lc
|
||||||
@@ -82,16 +82,16 @@ func (lc ListComputes) SortByUpdatedTime(inverse bool) ListComputes {
|
|||||||
//
|
//
|
||||||
// If inverse param is set to true, the order is reversed.
|
// If inverse param is set to true, the order is reversed.
|
||||||
func (lc ListComputes) SortByDeletedTime(inverse bool) ListComputes {
|
func (lc ListComputes) SortByDeletedTime(inverse bool) ListComputes {
|
||||||
if len(lc) < 2 {
|
if len(lc.Data) < 2 {
|
||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lc, func(i, j int) bool {
|
sort.Slice(lc.Data, func(i, j int) bool {
|
||||||
if inverse {
|
if inverse {
|
||||||
return lc[i].DeletedTime > lc[j].DeletedTime
|
return lc.Data[i].DeletedTime > lc.Data[j].DeletedTime
|
||||||
}
|
}
|
||||||
|
|
||||||
return lc[i].DeletedTime < lc[j].DeletedTime
|
return lc.Data[i].DeletedTime < lc.Data[j].DeletedTime
|
||||||
})
|
})
|
||||||
|
|
||||||
return lc
|
return lc
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type UserGrantRequest struct {
|
|||||||
// - 'RCX' for Write
|
// - 'RCX' for Write
|
||||||
// - 'ARCXDU' for Admin
|
// - 'ARCXDU' for Admin
|
||||||
// Required: true
|
// Required: true
|
||||||
AccessType string `url:"accesstype" json:"accesstype" validate:"accountAccessType"`
|
AccessType string `url:"accesstype" json:"accesstype" validate:"accessType"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserGrant grant user access to the compute
|
// UserGrant grant user access to the compute
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type UserListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UserList gets users list for compute
|
// UserList gets users list for compute
|
||||||
func (c Compute) UserList(ctx context.Context, req UserListRequest) (*RecordACL, error) {
|
func (c Compute) UserList(ctx context.Context, req UserListRequest) (*ListUsers, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, validationError := range validators.GetErrors(err) {
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
@@ -31,7 +31,7 @@ func (c Compute) UserList(ctx context.Context, req UserListRequest) (*RecordACL,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := RecordACL{}
|
list := ListUsers{}
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
err = json.Unmarshal(res, &list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type UserUpdateRequest struct {
|
|||||||
// - 'RCX' for Write
|
// - 'RCX' for Write
|
||||||
// - 'ARCXDU' for Admin
|
// - 'ARCXDU' for Admin
|
||||||
// Required: true
|
// Required: true
|
||||||
AccessType string `url:"accesstype" json:"accesstype" validate:"accountAccessType"`
|
AccessType string `url:"accesstype" json:"accesstype" validate:"accessType"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserUpdate updates user access to the compute
|
// UserUpdate updates user access to the compute
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
package cloudapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/computeci"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Accessing the ComputeCI method group
|
|
||||||
func (ca *CloudAPI) ComputeCI() *computeci.ComputeCI {
|
|
||||||
return computeci.New(ca.client)
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
// API Actor for managing ComputeCI. This actor is a final API for admin to manage ComputeCI
|
|
||||||
package computeci
|
|
||||||
|
|
||||||
import (
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Structure for creating request to computeci
|
|
||||||
type ComputeCI struct {
|
|
||||||
client interfaces.Caller
|
|
||||||
}
|
|
||||||
|
|
||||||
// Builder for computeci endpoints
|
|
||||||
func New(client interfaces.Caller) *ComputeCI {
|
|
||||||
return &ComputeCI{
|
|
||||||
client,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
package computeci
|
|
||||||
|
|
||||||
// FilterByID returns ListComputeCI with specified ID.
|
|
||||||
func (lci ListComputeCI) FilterByID(id uint64) ListComputeCI {
|
|
||||||
predicate := func(ic ItemComputeCI) bool {
|
|
||||||
return ic.ID == id
|
|
||||||
}
|
|
||||||
|
|
||||||
return lci.FilterFunc(predicate)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FilterByName returns ListComputeCI with specified Name.
|
|
||||||
func (lci ListComputeCI) FilterByName(name string) ListComputeCI {
|
|
||||||
predicate := func(ic ItemComputeCI) bool {
|
|
||||||
return ic.Name == name
|
|
||||||
}
|
|
||||||
|
|
||||||
return lci.FilterFunc(predicate)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FilterByStatus returns ListComputeCI with specified Status.
|
|
||||||
func (lci ListComputeCI) FilterByStatus(status string) ListComputeCI {
|
|
||||||
predicate := func(ic ItemComputeCI) bool {
|
|
||||||
return ic.Status == status
|
|
||||||
}
|
|
||||||
|
|
||||||
return lci.FilterFunc(predicate)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FilterFunc allows filtering ListComputeCI based on a user-specified predicate.
|
|
||||||
func (lci ListComputeCI) FilterFunc(predicate func(ItemComputeCI) bool) ListComputeCI {
|
|
||||||
var result ListComputeCI
|
|
||||||
|
|
||||||
for _, item := range lci {
|
|
||||||
if predicate(item) {
|
|
||||||
result = append(result, item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// FindOne returns first found ItemComputeCI
|
|
||||||
// If none was found, returns an empty struct.
|
|
||||||
func (lci ListComputeCI) FindOne() ItemComputeCI {
|
|
||||||
if len(lci) == 0 {
|
|
||||||
return ItemComputeCI{}
|
|
||||||
}
|
|
||||||
|
|
||||||
return lci[0]
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
package computeci
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
var computeciItems = ListComputeCI{
|
|
||||||
{
|
|
||||||
CustomFields: map[string]interface{}{},
|
|
||||||
Description: "",
|
|
||||||
Drivers: []string{
|
|
||||||
"KVM_X86",
|
|
||||||
},
|
|
||||||
GUID: 1,
|
|
||||||
ID: 1,
|
|
||||||
Name: "computeci_1",
|
|
||||||
Status: "ENABLED",
|
|
||||||
Template: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
CustomFields: map[string]interface{}{},
|
|
||||||
Description: "",
|
|
||||||
Drivers: []string{
|
|
||||||
"KVM_X86",
|
|
||||||
},
|
|
||||||
GUID: 2,
|
|
||||||
ID: 2,
|
|
||||||
Name: "computeci_2",
|
|
||||||
Status: "ENABLED",
|
|
||||||
Template: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
CustomFields: map[string]interface{}{},
|
|
||||||
Description: "",
|
|
||||||
Drivers: []string{
|
|
||||||
"SVA_KVM_X86",
|
|
||||||
},
|
|
||||||
GUID: 3,
|
|
||||||
ID: 3,
|
|
||||||
Name: "computeci_3",
|
|
||||||
Status: "DISABLED",
|
|
||||||
Template: "",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterByID(t *testing.T) {
|
|
||||||
actual := computeciItems.FilterByID(2).FindOne()
|
|
||||||
|
|
||||||
if actual.ID != 2 {
|
|
||||||
t.Fatal("expected ID 2, found: ", actual.ID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterByName(t *testing.T) {
|
|
||||||
actual := computeciItems.FilterByName("computeci_3").FindOne()
|
|
||||||
|
|
||||||
if actual.Name != "computeci_3" {
|
|
||||||
t.Fatal("expected Name 'computeci_2', found: ", actual.Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterByStatus(t *testing.T) {
|
|
||||||
actual := computeciItems.FilterByStatus("ENABLED")
|
|
||||||
|
|
||||||
if len(actual) != 2 {
|
|
||||||
t.Fatal("expected 2 found, actual: ", len(actual))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, item := range actual {
|
|
||||||
if item.Status != "ENABLED" {
|
|
||||||
t.Fatal("expected Status 'ENABLED', found: ", item.Status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilterFunc(t *testing.T) {
|
|
||||||
actual := computeciItems.FilterFunc(func(icc ItemComputeCI) bool {
|
|
||||||
for _, item := range icc.Drivers {
|
|
||||||
if item == "KVM_X86" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
|
|
||||||
if len(actual) != 2 {
|
|
||||||
t.Fatal("expected 2 found, actual: ", len(actual))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, item := range actual {
|
|
||||||
for _, driver := range item.Drivers {
|
|
||||||
if driver != "KVM_X86" {
|
|
||||||
t.Fatal("expected 'KVM_X86' Driver, found: ", driver)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
package computeci
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Request struct for information about computeci
|
|
||||||
type GetRequest struct {
|
|
||||||
// ID of the Compute CI
|
|
||||||
// Required: true
|
|
||||||
ComputeCIID uint64 `url:"computeciId" json:"computeciId" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get gets information about computeci by ID
|
|
||||||
func (c ComputeCI) Get(ctx context.Context, req GetRequest) (*ItemComputeCI, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
for _, validatonError := range validators.GetErrors(err) {
|
|
||||||
return nil, validators.ValidationError(validatonError)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/computeci/get"
|
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
info := ItemComputeCI{}
|
|
||||||
|
|
||||||
err = json.Unmarshal(res, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &info, nil
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package computeci
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Request struct for get list of computeci
|
|
||||||
type ListRequest struct {
|
|
||||||
// If true list deleted instances as well
|
|
||||||
// Required: false
|
|
||||||
IncludeDeleted bool `url:"includeDeleted,omitempty" json:"includeDeleted,omitempty"`
|
|
||||||
|
|
||||||
// Page number
|
|
||||||
// Required: false
|
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
|
||||||
|
|
||||||
// Page size
|
|
||||||
// Required: false
|
|
||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// List gets list of computeci instances
|
|
||||||
func (c ComputeCI) List(ctx context.Context, req ListRequest) (ListComputeCI, error) {
|
|
||||||
url := "/cloudapi/computeci/list"
|
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
list := ListComputeCI{}
|
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return list, nil
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
package computeci
|
|
||||||
|
|
||||||
// Main information about computeci
|
|
||||||
type ItemComputeCI struct {
|
|
||||||
// Custom fields
|
|
||||||
CustomFields map[string]interface{} `json:"customFields"`
|
|
||||||
|
|
||||||
// Description
|
|
||||||
Description string `json:"desc"`
|
|
||||||
|
|
||||||
// List drivers
|
|
||||||
Drivers []string `json:"drivers"`
|
|
||||||
|
|
||||||
// GUID
|
|
||||||
GUID uint64 `json:"guid"`
|
|
||||||
|
|
||||||
// ID
|
|
||||||
ID uint64 `json:"id"`
|
|
||||||
|
|
||||||
// Name
|
|
||||||
Name string `json:"name"`
|
|
||||||
|
|
||||||
// Status
|
|
||||||
Status string `json:"status"`
|
|
||||||
|
|
||||||
// Template
|
|
||||||
Template string `json:"template"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// List of computeci instances
|
|
||||||
type ListComputeCI []ItemComputeCI
|
|
||||||
@@ -2,7 +2,6 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -13,15 +12,15 @@ import (
|
|||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: true
|
// Required: true
|
||||||
AccountID uint64 `url:"accountId" json:"accountId"`
|
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
|
||||||
// ID of the grid (platform)
|
// ID of the grid (platform)
|
||||||
// Required: true
|
// Required: true
|
||||||
GID uint64 `url:"gid" json:"gid"`
|
GID uint64 `url:"gid" json:"gid" validate:"required"`
|
||||||
|
|
||||||
// Name of disk
|
// Name of disk
|
||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
// Description of disk
|
// Description of disk
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -36,7 +35,7 @@ type CreateRequest struct {
|
|||||||
// - D=Data
|
// - D=Data
|
||||||
// - T=Temp
|
// - T=Temp
|
||||||
// Required: true
|
// Required: true
|
||||||
Type string `url:"type" json:"type"`
|
Type string `url:"type" json:"type" validate:"diskType"`
|
||||||
|
|
||||||
// Size in GB default is 0
|
// Size in GB default is 0
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -55,29 +54,13 @@ type CreateRequest struct {
|
|||||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (drq CreateRequest) validate() error {
|
|
||||||
if drq.AccountID == 0 {
|
|
||||||
return errors.New("validation-error: field AccountID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
if drq.GID == 0 {
|
|
||||||
return errors.New("validation-error: field GID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
if drq.Name == "" {
|
|
||||||
return errors.New("validation-error: field Name can not be empty")
|
|
||||||
}
|
|
||||||
validType := validators.StringInSlice(drq.Type, []string{"B", "D", "T"})
|
|
||||||
if !validType {
|
|
||||||
return errors.New("validation-error: field Type must be set as B, D or T")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create creates a disk
|
// Create creates a disk
|
||||||
func (d Disks) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
func (d Disks) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/create"
|
url := "/cloudapi/disks/create"
|
||||||
|
|||||||
@@ -2,16 +2,17 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request for delete disk
|
// Request for delete disk
|
||||||
type DeleteRequest struct {
|
type DeleteRequest struct {
|
||||||
// ID of disk to delete
|
// ID of disk to delete
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
// Detach disk from machine first
|
// Detach disk from machine first
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -26,19 +27,13 @@ type DeleteRequest struct {
|
|||||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d DeleteRequest) validate() error {
|
|
||||||
if d.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID must be set")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete deletes disk by ID
|
// Delete deletes disk by ID
|
||||||
func (d Disks) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
func (d Disks) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/delete"
|
url := "/cloudapi/disks/delete"
|
||||||
|
|||||||
@@ -2,42 +2,34 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for multiple disks
|
// Request struct for multiple disks
|
||||||
type DisksDeleteRequest struct {
|
type DisksDeleteRequest struct {
|
||||||
// List of disk ids to delete
|
// List of disk ids to delete
|
||||||
// Required: true
|
// Required: true
|
||||||
DisksIDs []uint64 `url:"diskIds" json:"diskIds"`
|
DisksIDs []uint64 `url:"diskIds" json:"diskIds" validate:"required"`
|
||||||
|
|
||||||
// Reason for deleting the disks
|
// Reason for deleting the disks
|
||||||
// Required: true
|
// Required: true
|
||||||
Reason string `url:"reason" json:"reason"`
|
Reason string `url:"reason" json:"reason" validate:"required"`
|
||||||
|
|
||||||
// Whether to completely delete the disks, works only with non attached disks
|
// Whether to completely delete the disks, works only with non attached disks
|
||||||
// Required: false
|
// Required: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (drq DisksDeleteRequest) validate() error {
|
|
||||||
if len(drq.DisksIDs) == 0 {
|
|
||||||
return errors.New("validation-error: field DisksIDs must include one or more disks ids")
|
|
||||||
}
|
|
||||||
if drq.Reason == "" {
|
|
||||||
return errors.New("validation-error: field Reason must be set")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteDisks deletes multiple disks permanently
|
// DeleteDisks deletes multiple disks permanently
|
||||||
func (d Disks) DeleteDisks(ctx context.Context, req DisksDeleteRequest) (bool, error) {
|
func (d Disks) DeleteDisks(ctx context.Context, req DisksDeleteRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/deleteDisks"
|
url := "/cloudapi/disks/deleteDisks"
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
package disks
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
|
||||||
|
)
|
||||||
|
|
||||||
// FilterByID returns ListDisks with specified ID.
|
// FilterByID returns ListDisks with specified ID.
|
||||||
func (ld ListDisks) FilterByID(id uint64) ListDisks {
|
func (ld ListDisks) FilterByID(id uint64) ListDisks {
|
||||||
predicate := func(idisk ItemDisk) bool {
|
predicate := func(idisk ItemDisk) bool {
|
||||||
@@ -36,10 +45,201 @@ func (ld ListDisks) FilterByTechStatus(techStatus string) ListDisks {
|
|||||||
return ld.FilterFunc(predicate)
|
return ld.FilterFunc(predicate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FilterByComputeID is used to filter ListDisks attached to specified compute.
|
||||||
|
func (ld ListDisks) FilterByComputeID(computeID uint64) ListDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
for k := range idisk.Computes {
|
||||||
|
if k == strconv.FormatUint(computeID, 10) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByK8SID is used to filter ListDisks by specified K8S cluster.
|
||||||
|
func (ld ListDisks) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient interfaces.Caller) (*ListDisks, error) {
|
||||||
|
caller := k8s.New(decortClient)
|
||||||
|
|
||||||
|
req := k8s.GetRequest{
|
||||||
|
K8SID: k8sID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cluster, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result ListDisks
|
||||||
|
|
||||||
|
for _, masterCompute := range cluster.K8SGroups.Masters.DetailedInfo {
|
||||||
|
result.Data = append(result.Data, ld.FilterByComputeID(masterCompute.ID).Data...)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, workerGroup := range cluster.K8SGroups.Workers {
|
||||||
|
for _, workerCompute := range workerGroup.DetailedInfo {
|
||||||
|
result.Data = append(result.Data, ld.FilterByComputeID(workerCompute.ID).Data...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByLBID is used to filter ListDisks used by computes inside specified Load Balancer.
|
||||||
|
func (ld ListDisks) FilterByLBID(ctx context.Context, lbID uint64, decortClient interfaces.Caller) (*ListDisks, error) {
|
||||||
|
caller := lb.New(decortClient)
|
||||||
|
|
||||||
|
req := lb.GetRequest{
|
||||||
|
LBID: lbID,
|
||||||
|
}
|
||||||
|
|
||||||
|
foundLB, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result ListDisks
|
||||||
|
result.Data = append(result.Data, ld.FilterByComputeID(foundLB.PrimaryNode.ComputeID).Data...)
|
||||||
|
result.Data = append(result.Data, ld.FilterByComputeID(foundLB.SecondaryNode.ComputeID).Data...)
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
// FilterFunc allows filtering ListDisks based on a user-specified predicate.
|
// FilterFunc allows filtering ListDisks based on a user-specified predicate.
|
||||||
func (ld ListDisks) FilterFunc(predicate func(ItemDisk) bool) ListDisks {
|
func (ld ListDisks) FilterFunc(predicate func(ItemDisk) bool) ListDisks {
|
||||||
var result ListDisks
|
var result ListDisks
|
||||||
|
|
||||||
|
for _, item := range ld.Data {
|
||||||
|
if predicate(item) {
|
||||||
|
result.Data = append(result.Data, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindOne returns first found ItemDisk
|
||||||
|
// If none was found, returns an empty struct.
|
||||||
|
func (ld ListDisks) FindOne() ItemDisk {
|
||||||
|
if len(ld.Data) == 0 {
|
||||||
|
return ItemDisk{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.Data[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByID returns ListSearchDisks with specified ID.
|
||||||
|
func (ld ListSearchDisks) FilterByID(id uint64) ListSearchDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
return idisk.ID == id
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByName returns ListSearchDisks with specified Name.
|
||||||
|
func (ld ListSearchDisks) FilterByName(name string) ListSearchDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
return idisk.Name == name
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByStatus returns ListSearchDisks with specified Status.
|
||||||
|
func (ld ListSearchDisks) FilterByStatus(status string) ListSearchDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
return idisk.Status == status
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByTechStatus returns ListSearchDisks with specified TechStatus.
|
||||||
|
func (ld ListSearchDisks) FilterByTechStatus(techStatus string) ListSearchDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
return idisk.TechStatus == techStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByComputeID is used to filter ListSearchDisks attached to specified compute.
|
||||||
|
func (ld ListSearchDisks) FilterByComputeID(computeID uint64) ListSearchDisks {
|
||||||
|
predicate := func(idisk ItemDisk) bool {
|
||||||
|
for k := range idisk.Computes {
|
||||||
|
if k == strconv.FormatUint(computeID, 10) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ld.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByK8SID is used to filter ListSearchDisks by specified K8S cluster.
|
||||||
|
func (ld ListSearchDisks) FilterByK8SID(ctx context.Context, k8sID uint64, decortClient interfaces.Caller) (ListSearchDisks, error) {
|
||||||
|
caller := k8s.New(decortClient)
|
||||||
|
|
||||||
|
req := k8s.GetRequest{
|
||||||
|
K8SID: k8sID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cluster, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result ListSearchDisks
|
||||||
|
|
||||||
|
for _, masterCompute := range cluster.K8SGroups.Masters.DetailedInfo {
|
||||||
|
result = append(result, ld.FilterByComputeID(masterCompute.ID)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, workerGroup := range cluster.K8SGroups.Workers {
|
||||||
|
for _, workerCompute := range workerGroup.DetailedInfo {
|
||||||
|
result = append(result, ld.FilterByComputeID(workerCompute.ID)...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByLBID is used to filter ListSearchDisks used by computes inside specified Load Balancer.
|
||||||
|
func (ld ListSearchDisks) FilterByLBID(ctx context.Context, lbID uint64, decortClient interfaces.Caller) (ListSearchDisks, error) {
|
||||||
|
caller := lb.New(decortClient)
|
||||||
|
|
||||||
|
req := lb.GetRequest{
|
||||||
|
LBID: lbID,
|
||||||
|
}
|
||||||
|
|
||||||
|
foundLB, err := caller.Get(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result ListSearchDisks
|
||||||
|
result = append(result, ld.FilterByComputeID(foundLB.PrimaryNode.ComputeID)...)
|
||||||
|
result = append(result, ld.FilterByComputeID(foundLB.SecondaryNode.ComputeID)...)
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterFunc allows filtering ListSearchDisks based on a user-specified predicate.
|
||||||
|
func (ld ListSearchDisks) FilterFunc(predicate func(ItemDisk) bool) ListSearchDisks {
|
||||||
|
var result ListSearchDisks
|
||||||
|
|
||||||
for _, item := range ld {
|
for _, item := range ld {
|
||||||
if predicate(item) {
|
if predicate(item) {
|
||||||
result = append(result, item)
|
result = append(result, item)
|
||||||
@@ -51,10 +251,71 @@ func (ld ListDisks) FilterFunc(predicate func(ItemDisk) bool) ListDisks {
|
|||||||
|
|
||||||
// FindOne returns first found ItemDisk
|
// FindOne returns first found ItemDisk
|
||||||
// If none was found, returns an empty struct.
|
// If none was found, returns an empty struct.
|
||||||
func (ld ListDisks) FindOne() ItemDisk {
|
func (ld ListSearchDisks) FindOne() ItemDisk {
|
||||||
if len(ld) == 0 {
|
if len(ld) == 0 {
|
||||||
return ItemDisk{}
|
return ItemDisk{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ld[0]
|
return ld[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FilterByID returns ListDisksUnattached with specified ID.
|
||||||
|
func (lu ListDisksUnattached) FilterByID(id uint64) ListDisksUnattached {
|
||||||
|
predicate := func(idisk ItemDiskUnattached) bool {
|
||||||
|
return idisk.ID == id
|
||||||
|
}
|
||||||
|
|
||||||
|
return lu.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByName returns ListDisksUnattached with specified Name.
|
||||||
|
func (lu ListDisksUnattached) FilterByName(name string) ListDisksUnattached {
|
||||||
|
predicate := func(idisk ItemDiskUnattached) bool {
|
||||||
|
return idisk.Name == name
|
||||||
|
}
|
||||||
|
|
||||||
|
return lu.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByStatus returns ListDisksUnattached with specified Status.
|
||||||
|
func (lu ListDisksUnattached) FilterByStatus(status string) ListDisksUnattached {
|
||||||
|
predicate := func(idisk ItemDiskUnattached) bool {
|
||||||
|
return idisk.Status == status
|
||||||
|
}
|
||||||
|
|
||||||
|
return lu.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByTechStatus returns ListDisksUnattached with specified TechStatus.
|
||||||
|
func (lu ListDisksUnattached) FilterByTechStatus(techStatus string) ListDisksUnattached {
|
||||||
|
predicate := func(idisk ItemDiskUnattached) bool {
|
||||||
|
return idisk.TechStatus == techStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
return lu.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterFunc allows filtering ListDisksUnattached based on a user-specified predicate.
|
||||||
|
func (lu ListDisksUnattached) FilterFunc(predicate func(ItemDiskUnattached) bool) ListDisksUnattached {
|
||||||
|
var result ListDisksUnattached
|
||||||
|
|
||||||
|
for _, item := range lu.Data {
|
||||||
|
if predicate(item) {
|
||||||
|
result.Data = append(result.Data, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindOne returns first found ItemDiskUnattached
|
||||||
|
// If none was found, returns an empty struct.
|
||||||
|
func (lu ListDisksUnattached) FindOne() ItemDiskUnattached {
|
||||||
|
if len(lu.Data) == 0 {
|
||||||
|
return ItemDiskUnattached{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lu.Data[0]
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,189 @@
|
|||||||
package disks
|
package disks
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var techStatusAllocated = "ALLOCATED"
|
||||||
|
|
||||||
var disks = ListDisks{
|
var disks = ListDisks{
|
||||||
|
Data: []ItemDisk{
|
||||||
|
{
|
||||||
|
MachineID: 0,
|
||||||
|
MachineName: "",
|
||||||
|
DeviceName: "vda",
|
||||||
|
AccountID: 132847,
|
||||||
|
AccountName: "std_2",
|
||||||
|
ACL: map[string]interface{}{},
|
||||||
|
Computes: map[string]string{
|
||||||
|
"48500": "test",
|
||||||
|
},
|
||||||
|
CreatedTime: 1676975177,
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
DestructionTime: 0,
|
||||||
|
GID: 212,
|
||||||
|
ID: 65191,
|
||||||
|
ImageID: 9884,
|
||||||
|
Images: []uint64{},
|
||||||
|
IOTune: IOTune{
|
||||||
|
TotalIOPSSec: 2000,
|
||||||
|
},
|
||||||
|
Name: "bootdisk",
|
||||||
|
Order: 0,
|
||||||
|
Params: "",
|
||||||
|
ParentID: 0,
|
||||||
|
PCISlot: 6,
|
||||||
|
Pool: "vmstor",
|
||||||
|
PresentTo: []uint64{
|
||||||
|
27,
|
||||||
|
},
|
||||||
|
PurgeTime: 0,
|
||||||
|
ResID: "sample",
|
||||||
|
ResName: "sample",
|
||||||
|
Role: "",
|
||||||
|
Shareable: false,
|
||||||
|
SizeMax: 2,
|
||||||
|
SizeUsed: 2,
|
||||||
|
Snapshots: []ItemSnapshot{},
|
||||||
|
Status: "ASSIGNED",
|
||||||
|
TechStatus: techStatusAllocated,
|
||||||
|
Type: "B",
|
||||||
|
VMID: 48500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MachineID: 0,
|
||||||
|
MachineName: "",
|
||||||
|
DeviceName: "vda",
|
||||||
|
AccountID: 132852,
|
||||||
|
AccountName: "std",
|
||||||
|
ACL: map[string]interface{}{},
|
||||||
|
Computes: map[string]string{
|
||||||
|
"48502": "stdvm2",
|
||||||
|
},
|
||||||
|
CreatedTime: 1676982606,
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
DestructionTime: 0,
|
||||||
|
GID: 212,
|
||||||
|
ID: 65193,
|
||||||
|
ImageID: 9885,
|
||||||
|
Images: []uint64{},
|
||||||
|
IOTune: IOTune{
|
||||||
|
TotalIOPSSec: 2000,
|
||||||
|
},
|
||||||
|
Name: "bootdisk",
|
||||||
|
Order: 0,
|
||||||
|
Params: "",
|
||||||
|
ParentID: 0,
|
||||||
|
PCISlot: 6,
|
||||||
|
Pool: "vmstor",
|
||||||
|
PresentTo: []uint64{
|
||||||
|
27,
|
||||||
|
27,
|
||||||
|
},
|
||||||
|
PurgeTime: 0,
|
||||||
|
ResID: "sample",
|
||||||
|
ResName: "sample",
|
||||||
|
Role: "",
|
||||||
|
Shareable: false,
|
||||||
|
SizeMax: 4,
|
||||||
|
SizeUsed: 4,
|
||||||
|
Snapshots: []ItemSnapshot{},
|
||||||
|
Status: "ASSIGNED",
|
||||||
|
TechStatus: techStatusAllocated,
|
||||||
|
Type: "B",
|
||||||
|
VMID: 48502,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
EntryCount: 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_FilterByID(t *testing.T) {
|
||||||
|
actual := disks.FilterByID(65193)
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
actualItem := actual.FindOne()
|
||||||
|
|
||||||
|
if actualItem.ID != 65193 {
|
||||||
|
t.Fatal("expected ID 65193, found: ", actualItem.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_FilterByName(t *testing.T) {
|
||||||
|
actual := disks.FilterByName("bootdisk")
|
||||||
|
|
||||||
|
if len(actual.Data) != 2 {
|
||||||
|
t.Fatal("expected 2 elements, found: ", len(actual.Data))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.Name != "bootdisk" {
|
||||||
|
t.Fatal("expected 'bootdisk' name, found: ", item.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_FilterByStatus(t *testing.T) {
|
||||||
|
actual := disks.FilterByStatus("ASSIGNED")
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.Status != "ASSIGNED" {
|
||||||
|
t.Fatal("expected 'ASSIGNED' status, found: ", item.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_FilterByTechStatus(t *testing.T) {
|
||||||
|
actual := disks.FilterByTechStatus(techStatusAllocated)
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.TechStatus != techStatusAllocated {
|
||||||
|
t.Fatal("expected 'ALLOCATED' techStatus, found: ", item.TechStatus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_FilterFunc(t *testing.T) {
|
||||||
|
actual := disks.FilterFunc(func(id ItemDisk) bool {
|
||||||
|
return len(id.PresentTo) == 2
|
||||||
|
})
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(actual.Data[0].PresentTo) != 2 {
|
||||||
|
t.Fatal("expected 2 elements in PresentTo, found: ", len(actual.Data[0].PresentTo))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisks_SortByCreatedTime(t *testing.T) {
|
||||||
|
actual := disks.SortByCreatedTime(false)
|
||||||
|
|
||||||
|
if actual.Data[0].ID != 65191 {
|
||||||
|
t.Fatal("expected ID 65191, found: ", actual.Data[0].ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual = disks.SortByCreatedTime(true)
|
||||||
|
|
||||||
|
if actual.Data[0].ID != 65193 {
|
||||||
|
t.Fatal("expected ID 65193, found: ", actual.Data[0].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var searchDisks = ListSearchDisks{
|
||||||
ItemDisk{
|
ItemDisk{
|
||||||
MachineID: 0,
|
MachineID: 0,
|
||||||
MachineName: "",
|
MachineName: "",
|
||||||
@@ -42,7 +223,7 @@ var disks = ListDisks{
|
|||||||
SizeUsed: 2,
|
SizeUsed: 2,
|
||||||
Snapshots: []ItemSnapshot{},
|
Snapshots: []ItemSnapshot{},
|
||||||
Status: "ASSIGNED",
|
Status: "ASSIGNED",
|
||||||
TechStatus: "ALLOCATED",
|
TechStatus: techStatusAllocated,
|
||||||
Type: "B",
|
Type: "B",
|
||||||
VMID: 48500,
|
VMID: 48500,
|
||||||
},
|
},
|
||||||
@@ -86,14 +267,14 @@ var disks = ListDisks{
|
|||||||
SizeUsed: 4,
|
SizeUsed: 4,
|
||||||
Snapshots: []ItemSnapshot{},
|
Snapshots: []ItemSnapshot{},
|
||||||
Status: "ASSIGNED",
|
Status: "ASSIGNED",
|
||||||
TechStatus: "ALLOCATED",
|
TechStatus: techStatusAllocated,
|
||||||
Type: "B",
|
Type: "B",
|
||||||
VMID: 48502,
|
VMID: 48502,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByID(t *testing.T) {
|
func TestListSearchDisks_FilterByID(t *testing.T) {
|
||||||
actual := disks.FilterByID(65193)
|
actual := searchDisks.FilterByID(65193)
|
||||||
|
|
||||||
if len(actual) == 0 {
|
if len(actual) == 0 {
|
||||||
t.Fatal("No elements were found")
|
t.Fatal("No elements were found")
|
||||||
@@ -106,8 +287,8 @@ func TestFilterByID(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByName(t *testing.T) {
|
func TestListSearchDisks_FilterByName(t *testing.T) {
|
||||||
actual := disks.FilterByName("bootdisk")
|
actual := searchDisks.FilterByName("bootdisk")
|
||||||
|
|
||||||
if len(actual) != 2 {
|
if len(actual) != 2 {
|
||||||
t.Fatal("expected 2 elements, found: ", len(actual))
|
t.Fatal("expected 2 elements, found: ", len(actual))
|
||||||
@@ -120,8 +301,8 @@ func TestFilterByName(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByStatus(t *testing.T) {
|
func TestListSearchDisks_FilterByStatus(t *testing.T) {
|
||||||
actual := disks.FilterByStatus("ASSIGNED")
|
actual := searchDisks.FilterByStatus("ASSIGNED")
|
||||||
|
|
||||||
if len(actual) == 0 {
|
if len(actual) == 0 {
|
||||||
t.Fatal("No elements were found")
|
t.Fatal("No elements were found")
|
||||||
@@ -134,22 +315,22 @@ func TestFilterByStatus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterByTechStatus(t *testing.T) {
|
func TestListSearchDisks_FilterByTechStatus(t *testing.T) {
|
||||||
actual := disks.FilterByTechStatus("ALLOCATED")
|
actual := searchDisks.FilterByTechStatus(techStatusAllocated)
|
||||||
|
|
||||||
if len(actual) == 0 {
|
if len(actual) == 0 {
|
||||||
t.Fatal("No elements were found")
|
t.Fatal("No elements were found")
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, item := range actual {
|
for _, item := range actual {
|
||||||
if item.TechStatus != "ALLOCATED" {
|
if item.TechStatus != techStatusAllocated {
|
||||||
t.Fatal("expected 'ALLOCATED' techStatus, found: ", item.TechStatus)
|
t.Fatal("expected 'ALLOCATED' techStatus, found: ", item.TechStatus)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFilterFunc(t *testing.T) {
|
func TestListSearchDisks_FilterFunc(t *testing.T) {
|
||||||
actual := disks.FilterFunc(func(id ItemDisk) bool {
|
actual := searchDisks.FilterFunc(func(id ItemDisk) bool {
|
||||||
return len(id.PresentTo) == 2
|
return len(id.PresentTo) == 2
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -162,16 +343,214 @@ func TestFilterFunc(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSortByCreatedTime(t *testing.T) {
|
func TestListSearchDisks_SortByCreatedTime(t *testing.T) {
|
||||||
actual := disks.SortByCreatedTime(false)
|
actual := searchDisks.SortByCreatedTime(false)
|
||||||
|
|
||||||
if actual[0].ID != 65191 {
|
if actual[0].ID != 65191 {
|
||||||
t.Fatal("expected ID 65191, found: ", actual[0].ID)
|
t.Fatal("expected ID 65191, found: ", actual[0].ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
actual = disks.SortByCreatedTime(true)
|
actual = searchDisks.SortByCreatedTime(true)
|
||||||
|
|
||||||
if actual[0].ID != 65193 {
|
if actual[0].ID != 65193 {
|
||||||
t.Fatal("expected ID 65193, found: ", actual[0].ID)
|
t.Fatal("expected ID 65193, found: ", actual[0].ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var unattachedDisks = ListDisksUnattached{
|
||||||
|
Data: []ItemDiskUnattached{
|
||||||
|
{
|
||||||
|
CKey: "",
|
||||||
|
Meta: []interface{}{
|
||||||
|
"cloudbroker",
|
||||||
|
"disk",
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
AccountID: 149,
|
||||||
|
AccountName: "test_account1",
|
||||||
|
ACL: map[string]interface{}{},
|
||||||
|
BootPartition: 0,
|
||||||
|
CreatedTime: 1681477547,
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
DestructionTime: 0,
|
||||||
|
DiskPath: "",
|
||||||
|
GID: 2002,
|
||||||
|
GUID: 22636,
|
||||||
|
ID: 22636,
|
||||||
|
ImageID: 0,
|
||||||
|
Images: []uint64{},
|
||||||
|
IOTune: IOTune{
|
||||||
|
TotalIOPSSec: 2000,
|
||||||
|
},
|
||||||
|
IQN: "",
|
||||||
|
Login: "",
|
||||||
|
Milestones: 43834,
|
||||||
|
Name: "test_disk",
|
||||||
|
Order: 0,
|
||||||
|
Params: "",
|
||||||
|
ParentID: 0,
|
||||||
|
Password: "",
|
||||||
|
PCISlot: -1,
|
||||||
|
Pool: "data05",
|
||||||
|
PresentTo: []uint64{},
|
||||||
|
PurgeAttempts: 0,
|
||||||
|
PurgeTime: 0,
|
||||||
|
RealityDeviceNumber: 0,
|
||||||
|
ReferenceID: "",
|
||||||
|
ResID: "79bd3bd8-3424-48d3-963f-1870d506f169",
|
||||||
|
ResName: "volumes/volume_22636",
|
||||||
|
Role: "",
|
||||||
|
SEPID: 1,
|
||||||
|
Shareable: false,
|
||||||
|
SizeMax: 0,
|
||||||
|
SizeUsed: 0,
|
||||||
|
Snapshots: nil,
|
||||||
|
Status: "CREATED",
|
||||||
|
TechStatus: techStatusAllocated,
|
||||||
|
Type: "D",
|
||||||
|
VMID: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
CKey: "",
|
||||||
|
Meta: []interface{}{
|
||||||
|
"cloudbroker",
|
||||||
|
"disk",
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
AccountID: 150,
|
||||||
|
AccountName: "test_account",
|
||||||
|
ACL: map[string]interface{}{},
|
||||||
|
BootPartition: 0,
|
||||||
|
CreatedTime: 1681477558,
|
||||||
|
DeletedTime: 0,
|
||||||
|
Description: "",
|
||||||
|
DestructionTime: 0,
|
||||||
|
DiskPath: "",
|
||||||
|
GID: 2002,
|
||||||
|
GUID: 22637,
|
||||||
|
ID: 22637,
|
||||||
|
ImageID: 0,
|
||||||
|
Images: []uint64{},
|
||||||
|
IOTune: IOTune{
|
||||||
|
TotalIOPSSec: 2000,
|
||||||
|
},
|
||||||
|
IQN: "",
|
||||||
|
Login: "",
|
||||||
|
Milestones: 43834,
|
||||||
|
Name: "test_disk",
|
||||||
|
Order: 0,
|
||||||
|
Params: "",
|
||||||
|
ParentID: 0,
|
||||||
|
Password: "",
|
||||||
|
PCISlot: -1,
|
||||||
|
Pool: "data05",
|
||||||
|
PresentTo: []uint64{
|
||||||
|
27,
|
||||||
|
27,
|
||||||
|
},
|
||||||
|
PurgeAttempts: 0,
|
||||||
|
PurgeTime: 0,
|
||||||
|
RealityDeviceNumber: 0,
|
||||||
|
ReferenceID: "",
|
||||||
|
ResID: "79bd3bd8-3424-48d3-963f-1870d506f169",
|
||||||
|
ResName: "volumes/volume_22637",
|
||||||
|
Role: "",
|
||||||
|
SEPID: 1,
|
||||||
|
Shareable: false,
|
||||||
|
SizeMax: 0,
|
||||||
|
SizeUsed: 0,
|
||||||
|
Snapshots: nil,
|
||||||
|
Status: "CREATED",
|
||||||
|
TechStatus: techStatusAllocated,
|
||||||
|
Type: "B",
|
||||||
|
VMID: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
EntryCount: 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_FilterByID(t *testing.T) {
|
||||||
|
actual := unattachedDisks.FilterByID(22636)
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
actualItem := actual.FindOne()
|
||||||
|
|
||||||
|
if actualItem.ID != 22636 {
|
||||||
|
t.Fatal("expected ID 22636, found: ", actualItem.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_FilterByName(t *testing.T) {
|
||||||
|
actual := unattachedDisks.FilterByName("test_disk")
|
||||||
|
|
||||||
|
if len(actual.Data) != 2 {
|
||||||
|
t.Fatal("expected 2 elements, found: ", len(actual.Data))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.Name != "test_disk" {
|
||||||
|
t.Fatal("expected 'test_disk' name, found: ", item.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_FilterByStatus(t *testing.T) {
|
||||||
|
actual := unattachedDisks.FilterByStatus("CREATED")
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.Status != "CREATED" {
|
||||||
|
t.Fatal("expected 'CREATED' status, found: ", item.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_FilterByTechStatus(t *testing.T) {
|
||||||
|
actual := unattachedDisks.FilterByTechStatus(techStatusAllocated)
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.TechStatus != techStatusAllocated {
|
||||||
|
t.Fatal("expected 'ALLOCATED' techStatus, found: ", item.TechStatus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_FilterFunc(t *testing.T) {
|
||||||
|
actual := unattachedDisks.FilterFunc(func(id ItemDiskUnattached) bool {
|
||||||
|
return len(id.PresentTo) == 2
|
||||||
|
})
|
||||||
|
|
||||||
|
if len(actual.Data) == 0 {
|
||||||
|
t.Fatal("No elements were found")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(actual.Data[0].PresentTo) != 2 {
|
||||||
|
t.Fatal("expected 2 elements in PresentTo, found: ", len(actual.Data[0].PresentTo))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListDisksUnattached_SortByCreatedTime(t *testing.T) {
|
||||||
|
actual := unattachedDisks.SortByCreatedTime(false)
|
||||||
|
|
||||||
|
if actual.Data[0].ID != 22636 {
|
||||||
|
t.Fatal("expected ID 22636, found: ", actual.Data[0].ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual = unattachedDisks.SortByCreatedTime(true)
|
||||||
|
|
||||||
|
if actual.Data[0].ID != 22637 {
|
||||||
|
t.Fatal("expected ID 22637, found: ", actual.Data[0].ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,31 +3,26 @@ package disks
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for get information about disk
|
// Request struct for get information about disk
|
||||||
type GetRequest struct {
|
type GetRequest struct {
|
||||||
// ID of the disk
|
// ID of the disk
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
}
|
|
||||||
|
|
||||||
func (drq GetRequest) validate() error {
|
|
||||||
if drq.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get gets disk details
|
// Get gets disk details
|
||||||
// Notice: the devicename field is the name as it is passed to the kernel (kname in linux) for unattached disks this field has no relevant value
|
// Notice: the devicename field is the name as it is passed to the kernel (kname in linux) for unattached disks this field has no relevant value
|
||||||
func (d Disks) Get(ctx context.Context, req GetRequest) (*RecordDisk, error) {
|
func (d Disks) Get(ctx context.Context, req GetRequest) (*RecordDisk, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/get"
|
url := "/cloudapi/disks/get"
|
||||||
|
|||||||
@@ -2,16 +2,17 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for limit IO
|
// Request struct for limit IO
|
||||||
type LimitIORequest struct {
|
type LimitIORequest struct {
|
||||||
// ID of the disk to limit
|
// ID of the disk to limit
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
// Alias for total_iops_sec for backwards compatibility
|
// Alias for total_iops_sec for backwards compatibility
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -70,21 +71,15 @@ type LimitIORequest struct {
|
|||||||
SizeIOPSSec uint64 `url:"size_iops_sec,omitempty" json:"size_iops_sec,omitempty"`
|
SizeIOPSSec uint64 `url:"size_iops_sec,omitempty" json:"size_iops_sec,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (drq LimitIORequest) validate() error {
|
|
||||||
if drq.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LimitIO limit IO for a certain disk
|
// LimitIO limit IO for a certain disk
|
||||||
// total and read/write options are not allowed to be combined
|
// total and read/write options are not allowed to be combined
|
||||||
// see http://libvirt.org/formatdomain.html#elementsDisks iotune section for more details
|
// see http://libvirt.org/formatdomain.html#elementsDisks iotune section for more details
|
||||||
func (d Disks) LimitIO(ctx context.Context, req LimitIORequest) (bool, error) {
|
func (d Disks) LimitIO(ctx context.Context, req LimitIORequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/limitIO"
|
url := "/cloudapi/disks/limitIO"
|
||||||
|
|||||||
@@ -6,8 +6,32 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for get list/list_deleted of disks
|
// Request struct for get list of disks
|
||||||
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 account name
|
||||||
|
// Required: false
|
||||||
|
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
||||||
|
|
||||||
|
// Find by max size disk
|
||||||
|
// Required: false
|
||||||
|
DiskMaxSize int64 `url:"diskMaxSize,omitempty" json:"diskMaxSize,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Find by shared, true or false
|
||||||
|
// Required: false
|
||||||
|
Shared bool `url:"shared,omitempty" json:"shared,omitempty"`
|
||||||
|
|
||||||
// ID of the account the disks belong to
|
// ID of the account the disks belong to
|
||||||
// Required: false
|
// Required: false
|
||||||
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
@@ -16,6 +40,14 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Find by sep ID
|
||||||
|
// Required: false
|
||||||
|
SEPID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Find by pool name
|
||||||
|
// Required: false
|
||||||
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -26,7 +58,7 @@ type ListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List gets list the created disks belonging to an account
|
// List gets list the created disks belonging to an account
|
||||||
func (d Disks) List(ctx context.Context, req ListRequest) (ListDisks, error) {
|
func (d Disks) List(ctx context.Context, req ListRequest) (*ListDisks, error) {
|
||||||
url := "/cloudapi/disks/list"
|
url := "/cloudapi/disks/list"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -41,24 +73,5 @@ func (d Disks) List(ctx context.Context, req ListRequest) (ListDisks, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
|
||||||
|
|
||||||
// ListDeleted gets list the deleted disks belonging to an account
|
|
||||||
func (d Disks) ListDeleted(ctx context.Context, req ListRequest) (ListDisks, error) {
|
|
||||||
url := "/cloudapi/disks/listDeleted"
|
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
list := ListDisks{}
|
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return list, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
65
pkg/cloudapi/disks/list_deleted.go
Normal file
65
pkg/cloudapi/disks/list_deleted.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Request struct for get list of deleted disks
|
||||||
|
type ListDeletedRequest 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 account name
|
||||||
|
// Required: false
|
||||||
|
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
||||||
|
|
||||||
|
// Find by max size disk
|
||||||
|
// Required: false
|
||||||
|
DiskMaxSize int64 `url:"diskMaxSize,omitempty" json:"diskMaxSize,omitempty"`
|
||||||
|
|
||||||
|
// Find by shared, true or false
|
||||||
|
// Required: false
|
||||||
|
Shared bool `url:"shared,omitempty" json:"shared,omitempty"`
|
||||||
|
|
||||||
|
// ID of the account the disks belong to
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListDeleted gets list the deleted disks belonging to an account
|
||||||
|
func (d Disks) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListDisks, error) {
|
||||||
|
url := "/cloudapi/disks/listDeleted"
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
list := ListDisks{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &list)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &list, nil
|
||||||
|
}
|
||||||
@@ -9,12 +9,20 @@ import (
|
|||||||
// Request struct for get list types of disks
|
// Request struct for get list types of disks
|
||||||
type ListTypesRequest struct {
|
type ListTypesRequest struct {
|
||||||
// Show detailed disk types by seps
|
// Show detailed disk types by seps
|
||||||
|
// Required: true
|
||||||
|
Detailed bool `url:"detailed" json:"detailed" validate:"required"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Detailed bool `url:"detailed" json:"detailed"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListTypes gets list defined disk types
|
// ListTypes gets list defined disk types
|
||||||
func (d Disks) ListTypes(ctx context.Context, req ListTypesRequest) ([]interface{}, error) {
|
func (d Disks) ListTypes(ctx context.Context, req ListTypesRequest) (*ListTypes, error) {
|
||||||
url := "/cloudapi/disks/listTypes"
|
url := "/cloudapi/disks/listTypes"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -22,12 +30,12 @@ func (d Disks) ListTypes(ctx context.Context, req ListTypesRequest) ([]interface
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := make([]interface{}, 0)
|
list := ListTypes{}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,13 +8,49 @@ import (
|
|||||||
|
|
||||||
// Request struct for get list unattached disk
|
// Request struct for get list unattached disk
|
||||||
type ListUnattachedRequest struct {
|
type ListUnattachedRequest struct {
|
||||||
|
// Find by id
|
||||||
|
// Required: false
|
||||||
|
ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by account name
|
||||||
|
// Required: false
|
||||||
|
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
||||||
|
|
||||||
|
// Find by max size disk
|
||||||
|
// Required: false
|
||||||
|
DiskMaxSize int64 `url:"diskMaxSize,omitempty" json:"diskMaxSize,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Type of the disks
|
||||||
|
// Required: false
|
||||||
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: false
|
// Required: false
|
||||||
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
|
|
||||||
|
// Find by sep ID
|
||||||
|
// Required: false
|
||||||
|
SEPID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Find by pool name
|
||||||
|
// Required: false
|
||||||
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListUnattached gets list of unattached disks
|
// ListUnattached gets list of unattached disks
|
||||||
func (d Disks) ListUnattached(ctx context.Context, req ListUnattachedRequest) (ListDisks, error) {
|
func (d Disks) ListUnattached(ctx context.Context, req ListUnattachedRequest) (*ListDisksUnattached, error) {
|
||||||
url := "/cloudapi/disks/listUnattached"
|
url := "/cloudapi/disks/listUnattached"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -22,12 +58,12 @@ func (d Disks) ListUnattached(ctx context.Context, req ListUnattachedRequest) (L
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := ListDisks{}
|
list := ListDisksUnattached{}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,8 +114,158 @@ type ItemDisk struct {
|
|||||||
VMID uint64 `json:"vmid"`
|
VMID uint64 `json:"vmid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ItemDiskUnattached struct {
|
||||||
|
// CKey
|
||||||
|
CKey string `json:"_ckey"`
|
||||||
|
|
||||||
|
// Meta
|
||||||
|
Meta []interface{} `json:"_meta"`
|
||||||
|
|
||||||
|
// Account ID
|
||||||
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
|
// Account name
|
||||||
|
AccountName string `json:"accountName"`
|
||||||
|
|
||||||
|
// Access Control List
|
||||||
|
ACL map[string]interface{} `json:"acl"`
|
||||||
|
|
||||||
|
// Boot Partition
|
||||||
|
BootPartition uint64 `json:"bootPartition"`
|
||||||
|
|
||||||
|
// Created time
|
||||||
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// Deleted time
|
||||||
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"desc"`
|
||||||
|
|
||||||
|
// Destruction time
|
||||||
|
DestructionTime uint64 `json:"destructionTime"`
|
||||||
|
|
||||||
|
// Disk path
|
||||||
|
DiskPath string `json:"diskPath"`
|
||||||
|
|
||||||
|
// Grid ID
|
||||||
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Image ID
|
||||||
|
ImageID uint64 `json:"imageId"`
|
||||||
|
|
||||||
|
// Images
|
||||||
|
Images []uint64 `json:"images"`
|
||||||
|
|
||||||
|
// IOTune
|
||||||
|
IOTune IOTune `json:"iotune"`
|
||||||
|
|
||||||
|
// IQN
|
||||||
|
IQN string `json:"iqn"`
|
||||||
|
|
||||||
|
// Login
|
||||||
|
Login string `json:"login"`
|
||||||
|
|
||||||
|
// Milestones
|
||||||
|
Milestones uint64 `json:"milestones"`
|
||||||
|
|
||||||
|
// Name
|
||||||
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Order
|
||||||
|
Order uint64 `json:"order"`
|
||||||
|
|
||||||
|
// Params
|
||||||
|
Params string `json:"params"`
|
||||||
|
|
||||||
|
// Parent ID
|
||||||
|
ParentID uint64 `json:"parentId"`
|
||||||
|
|
||||||
|
// Password
|
||||||
|
Password string `json:"passwd"`
|
||||||
|
|
||||||
|
//PCISlot
|
||||||
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
|
// Pool
|
||||||
|
Pool string `json:"pool"`
|
||||||
|
|
||||||
|
// Present to
|
||||||
|
PresentTo []uint64 `json:"presentTo"`
|
||||||
|
|
||||||
|
// Purge attempts
|
||||||
|
PurgeAttempts uint64 `json:"purgeAttempts"`
|
||||||
|
|
||||||
|
// Purge time
|
||||||
|
PurgeTime uint64 `json:"purgeTime"`
|
||||||
|
|
||||||
|
// Reality device number
|
||||||
|
RealityDeviceNumber uint64 `json:"realityDeviceNumber"`
|
||||||
|
|
||||||
|
// Reference ID
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
|
// Resource ID
|
||||||
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
|
// Resource name
|
||||||
|
ResName string `json:"resName"`
|
||||||
|
|
||||||
|
// Role
|
||||||
|
Role string `json:"role"`
|
||||||
|
|
||||||
|
// ID SEP
|
||||||
|
SEPID uint64 `json:"sepId"`
|
||||||
|
|
||||||
|
// Shareable
|
||||||
|
Shareable bool `json:"shareable"`
|
||||||
|
|
||||||
|
// Size max
|
||||||
|
SizeMax uint64 `json:"sizeMax"`
|
||||||
|
|
||||||
|
// Size used
|
||||||
|
SizeUsed float64 `json:"sizeUsed"`
|
||||||
|
|
||||||
|
// List of snapshots
|
||||||
|
Snapshots ListSnapshots `json:"snapshots"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Tech status
|
||||||
|
TechStatus string `json:"techStatus"`
|
||||||
|
|
||||||
|
// Type
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// Virtual machine ID
|
||||||
|
VMID uint64 `json:"vmid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of disks searched
|
||||||
|
type ListSearchDisks []ItemDisk
|
||||||
|
|
||||||
// List of disks
|
// List of disks
|
||||||
type ListDisks []ItemDisk
|
type ListDisks struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemDisk `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of unattached disks
|
||||||
|
type ListDisksUnattached struct {
|
||||||
|
Data []ItemDiskUnattached `json:"data"`
|
||||||
|
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about snapshot
|
// Main information about snapshot
|
||||||
type ItemSnapshot struct {
|
type ItemSnapshot struct {
|
||||||
@@ -125,6 +275,8 @@ type ItemSnapshot struct {
|
|||||||
// Label
|
// Label
|
||||||
Label string `json:"label"`
|
Label string `json:"label"`
|
||||||
|
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
@@ -240,7 +392,7 @@ type RecordDisk struct {
|
|||||||
ParentID uint64 `json:"parentId"`
|
ParentID uint64 `json:"parentId"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot uint64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
// Pool
|
// Pool
|
||||||
Pool string `json:"pool"`
|
Pool string `json:"pool"`
|
||||||
@@ -290,3 +442,11 @@ type RecordDisk struct {
|
|||||||
// Virtual machine ID
|
// Virtual machine ID
|
||||||
VMID uint64 `json:"vmid"`
|
VMID uint64 `json:"vmid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ListTypes struct {
|
||||||
|
// Data
|
||||||
|
Data []interface{} `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,38 +2,30 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for rename disk
|
// Request struct for rename disk
|
||||||
type RenameRequest struct {
|
type RenameRequest struct {
|
||||||
// ID of the disk to rename
|
// ID of the disk to rename
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
// New name of disk
|
// New name of disk
|
||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
}
|
|
||||||
|
|
||||||
func (drq RenameRequest) validate() error {
|
|
||||||
if drq.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
if drq.Name == "" {
|
|
||||||
return errors.New("validation-error: field Name can not be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rename rename disk
|
// Rename rename disk
|
||||||
func (d Disks) Rename(ctx context.Context, req RenameRequest) (bool, error) {
|
func (d Disks) Rename(ctx context.Context, req RenameRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/rename"
|
url := "/cloudapi/disks/rename"
|
||||||
|
|||||||
@@ -2,31 +2,21 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for resize disk
|
// Request struct for resize disk
|
||||||
type ResizeRequest struct {
|
type ResizeRequest struct {
|
||||||
// ID of the disk to resize
|
// ID of the disk to resize
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
// New size of the disk in GB
|
// New size of the disk in GB
|
||||||
// Required: true
|
// Required: true
|
||||||
Size uint64 `url:"size" json:"size"`
|
Size uint64 `url:"size" json:"size" validate:"required"`
|
||||||
}
|
|
||||||
|
|
||||||
func (drq ResizeRequest) validate() error {
|
|
||||||
if drq.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
if drq.Size == 0 {
|
|
||||||
return errors.New("validation-error: field Size can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resize resize disk
|
// Resize resize disk
|
||||||
@@ -34,9 +24,11 @@ func (drq ResizeRequest) validate() error {
|
|||||||
// in that case please stop and start your machine after changing the disk size, for your changes to be reflected.
|
// in that case please stop and start your machine after changing the disk size, for your changes to be reflected.
|
||||||
// This method will not be used for disks, assigned to computes. Only unassigned disks and disks, assigned with "old" virtual machines.
|
// This method will not be used for disks, assigned to computes. Only unassigned disks and disks, assigned with "old" virtual machines.
|
||||||
func (d Disks) Resize(ctx context.Context, req ResizeRequest) (bool, error) {
|
func (d Disks) Resize(ctx context.Context, req ResizeRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/resize"
|
url := "/cloudapi/disks/resize"
|
||||||
@@ -59,9 +51,11 @@ func (d Disks) Resize(ctx context.Context, req ResizeRequest) (bool, error) {
|
|||||||
// in that case please stop and start your machine after changing the disk size, for your changes to be reflected.
|
// in that case please stop and start your machine after changing the disk size, for your changes to be reflected.
|
||||||
// This method will not be used for disks, assigned to "old" virtual machines. Only unassigned disks and disks, assigned with computes.
|
// This method will not be used for disks, assigned to "old" virtual machines. Only unassigned disks and disks, assigned with computes.
|
||||||
func (d Disks) Resize2(ctx context.Context, req ResizeRequest) (bool, error) {
|
func (d Disks) Resize2(ctx context.Context, req ResizeRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/resize2"
|
url := "/cloudapi/disks/resize2"
|
||||||
|
|||||||
@@ -2,38 +2,30 @@ package disks
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request struct for restore a deleted unattached disk
|
// Request struct for restore a deleted unattached disk
|
||||||
type RestoreRequest struct {
|
type RestoreRequest struct {
|
||||||
// ID of the disk to restore
|
// ID of the disk to restore
|
||||||
// Required: true
|
// Required: true
|
||||||
DiskID uint64 `url:"diskId" json:"diskId"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
// Reason for restoring the disk
|
// Reason for restoring the disk
|
||||||
// Required: true
|
// Required: true
|
||||||
Reason string `url:"reason" json:"reason"`
|
Reason string `url:"reason" json:"reason" validate:"required"`
|
||||||
}
|
|
||||||
|
|
||||||
func (drq RestoreRequest) validate() error {
|
|
||||||
if drq.DiskID == 0 {
|
|
||||||
return errors.New("validation-error: field DiskID can not be empty or equal to 0")
|
|
||||||
}
|
|
||||||
if drq.Reason == "" {
|
|
||||||
return errors.New("validation-error: field Reason can not be empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restore restore a deleted unattached disk from recycle bin
|
// Restore restore a deleted unattached disk from recycle bin
|
||||||
func (d Disks) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
func (d Disks) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
||||||
err := req.validate()
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/restore"
|
url := "/cloudapi/disks/restore"
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ type SearchRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Search search disks
|
// Search search disks
|
||||||
func (d Disks) Search(ctx context.Context, req SearchRequest) (ListDisks, error) {
|
func (d Disks) Search(ctx context.Context, req SearchRequest) (ListSearchDisks, error) {
|
||||||
url := "/cloudapi/disks/search"
|
url := "/cloudapi/disks/search"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
@@ -29,7 +29,7 @@ func (d Disks) Search(ctx context.Context, req SearchRequest) (ListDisks, error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := ListDisks{}
|
list := ListSearchDisks{}
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
err = json.Unmarshal(res, &list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -12,6 +12,26 @@ import (
|
|||||||
// - First argument -> prefix
|
// - First argument -> prefix
|
||||||
// - Second argument -> indent
|
// - Second argument -> indent
|
||||||
func (ld ListDisks) Serialize(params ...string) (serialization.Serialized, error) {
|
func (ld ListDisks) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if ld.EntryCount == 0 {
|
||||||
|
return []byte{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(ld, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(ld)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||||
|
//
|
||||||
|
// In order to serialize with indent make sure to follow these guidelines:
|
||||||
|
// - First argument -> prefix
|
||||||
|
// - Second argument -> indent
|
||||||
|
func (ld ListSearchDisks) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
if len(ld) == 0 {
|
if len(ld) == 0 {
|
||||||
return []byte{}, nil
|
return []byte{}, nil
|
||||||
}
|
}
|
||||||
@@ -41,3 +61,39 @@ func (idisk ItemDisk) Serialize(params ...string) (serialization.Serialized, err
|
|||||||
|
|
||||||
return json.Marshal(idisk)
|
return json.Marshal(idisk)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||||
|
//
|
||||||
|
// In order to serialize with indent make sure to follow these guidelines:
|
||||||
|
// - First argument -> prefix
|
||||||
|
// - Second argument -> indent
|
||||||
|
func (lu ListDisksUnattached) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if lu.EntryCount == 0 {
|
||||||
|
return []byte{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(lu, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(lu)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||||
|
//
|
||||||
|
// In order to serialize with indent make sure to follow these guidelines:
|
||||||
|
// - First argument -> prefix
|
||||||
|
// - Second argument -> indent
|
||||||
|
func (idisk ItemDiskUnattached) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(idisk, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(idisk)
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user