Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d137c7507a | |||
| 55027a1605 | |||
| de9cca4053 | |||
| 83bf1fb1fa | |||
| 16cad7a3e7 | |||
| 96273d2a12 | |||
| d4065938ac | |||
| cd741b7f11 | |||
| a85ad3acd5 |
13
CHANGELOG.md
13
CHANGELOG.md
@@ -1,9 +1,8 @@
|
|||||||
## Version 1.7.0
|
## Version 1.7.6
|
||||||
|
|
||||||
## Feature
|
### Bugfix
|
||||||
- Added support for authorization using the Basis.Virtual Security system. Add client and config
|
|
||||||
|
|
||||||
## Bugfix
|
- Fix allowed network plugin value from "weawenet" to "weavenet" in validators for cloudapi/k8s, cloudbroker/k8s and cloudbroker/k8ci
|
||||||
- Add model ListInfoSnapshots in cloudapi/bservice/models
|
- Delete omitempty from json, url tags in field Permanently in model DeleteRequest in cloudbroker/k8ci
|
||||||
- Fix func SnapshotList for work with new model cloudapi/bservice/snapshot_list
|
- Delete ItemAffinityGroup and ListAffinityGroup models and change Data field type in ListAffinityGroups model in order to fix panic for AffinityGroupsList method in cloudapi/rg
|
||||||
- Add models ItemAffinityGroup, ListAffinityGroup in cloudapi/rg/models
|
- Fix ListAffinityGroups.IDs method accordingly
|
||||||
426
README.md
426
README.md
@@ -17,29 +17,44 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
|
|
||||||
- [Установка](#установка)
|
- [Установка](#установка)
|
||||||
- [Список API](#список-api)
|
- [Список API](#список-api)
|
||||||
- [Cloudapi](#cloudapi)
|
- [Cloudapi](#cloudapi)
|
||||||
- [Cloudbroker](#cloudbroker)
|
- [Cloudbroker](#cloudbroker)
|
||||||
- [Работа с библиотекой](#работа-с-библиотекой)
|
- [Работа с библиотекой](#работа-с-библиотекой)
|
||||||
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
||||||
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
||||||
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
||||||
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
||||||
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
||||||
- [Создание клиента](#создание-клиента)
|
- [Создание клиента](#создание-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
- [Фильтрация](#фильтрация)
|
- [Фильтрация](#фильтрация)
|
||||||
- [Сортировка](#сортировка)
|
- [Сортировка](#сортировка)
|
||||||
- [Сериализация](#сериализация)
|
- [Сериализация](#сериализация)
|
||||||
|
- [Получение списка уникальных идентификаторов (ID) объекта](#получение-списка-уникальных-идентификаторов-id-объекта)
|
||||||
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
||||||
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
||||||
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
||||||
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
||||||
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
||||||
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
||||||
- [Создание legacy клиента](#создание-legacy-клиента)
|
- [Создание legacy клиента](#создание-legacy-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
|
- [Работа с BVS клиентом](#работа-с-bvs-клиентом)
|
||||||
|
- [Настройка параметров BVS в кабинете администратора](#настройка-параметров-bvs-в-кабинете-администратора)
|
||||||
|
- [Настройка конфигурации BVS клиента](#настройка-конфигурации-bvs-клиента)
|
||||||
|
- [Описание структуры token](#описание-структуры-token)
|
||||||
|
- [Пример конфигурации BVS клиента](#пример-конфигурации-bvs-клиента)
|
||||||
|
- [Парсинг BVS конфигурации из файла](#парсинг-bvs-конфигурации-из-файла)
|
||||||
|
- [Парсинг BVS токена из файла](#парсинг-bvs-токена-из-файла)
|
||||||
|
- [Пример BVS JSON конфигурации](#пример-bvs-json-конфигурации)
|
||||||
|
- [Пример BVS YAML конфигурации](#пример-bvs-yaml-конфигурации)
|
||||||
|
- [Создание BVS клиента](#создание-bvs-клиента)
|
||||||
|
- [Пример создания BVS клиента](#пример-создания-bvs-клиента)
|
||||||
|
- [Пример получения BVS токена](#пример-получения-bvs-токена)
|
||||||
|
- [Пример обновления BVS токена](#пример-обновления-bvs-токена)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса)
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
@@ -114,8 +129,8 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
Алгоритм работы с библиотекой выглядит следующим образом:
|
Алгоритм работы с библиотекой выглядит следующим образом:
|
||||||
|
|
||||||
1. Выполнение одного из действий:
|
1. Выполнение одного из действий:
|
||||||
- настройка конфигурации клиента;
|
- настройка конфигурации клиента;
|
||||||
- парсинг конфигурации из файла.
|
- парсинг конфигурации из файла.
|
||||||
2. Создание клиента.
|
2. Создание клиента.
|
||||||
3. Создание структуры запроса.
|
3. Создание структуры запроса.
|
||||||
4. Выполнение запроса.
|
4. Выполнение запроса.
|
||||||
@@ -157,7 +172,7 @@ func main(){
|
|||||||
|
|
||||||
#### Парсинг конфигурации из файла
|
#### Парсинг конфигурации из файла
|
||||||
|
|
||||||
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
||||||
<br>
|
<br>
|
||||||
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
@@ -168,7 +183,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из JSON-файла
|
// Парсинг конфигурации из JSON-файла
|
||||||
cfg := config.ParseConfigJSON("<PATH>")
|
cfg, _ := config.ParseConfigJSON("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -239,48 +254,48 @@ func main() {
|
|||||||
В каждом пакете находятся пакеты групп API:
|
В каждом пакете находятся пакеты групп API:
|
||||||
|
|
||||||
- **cloudapi**:
|
- **cloudapi**:
|
||||||
- `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/disks` - для `Disks`
|
- `pkg/cloudapi/disks` - для `Disks`
|
||||||
- `pkg/cloudapi/extnet` - для `ExtNet`
|
- `pkg/cloudapi/extnet` - для `ExtNet`
|
||||||
- `pkg/cloudapi/flipgroup` - для `FLIPGroup`
|
- `pkg/cloudapi/flipgroup` - для `FLIPGroup`
|
||||||
- `pkg/cloudapi/image` - для `Image`
|
- `pkg/cloudapi/image` - для `Image`
|
||||||
- `pkg/cloudapi/k8ci` - для `K8CI`
|
- `pkg/cloudapi/k8ci` - для `K8CI`
|
||||||
- `pkg/cloudapi/k8s` - для `K8S`
|
- `pkg/cloudapi/k8s` - для `K8S`
|
||||||
- `pkg/cloudapi/kvmppc` - для `KVMPPC`
|
- `pkg/cloudapi/kvmppc` - для `KVMPPC`
|
||||||
- `pkg/cloudapi/kvmx86` - для `KVMX86`
|
- `pkg/cloudapi/kvmx86` - для `KVMX86`
|
||||||
- `pkg/cloudapi/lb` - для `LB`
|
- `pkg/cloudapi/lb` - для `LB`
|
||||||
- `pkg/cloudapi/locations` - для `Locations`
|
- `pkg/cloudapi/locations` - для `Locations`
|
||||||
- `pkg/cloudapi/rg` - для `RG`
|
- `pkg/cloudapi/rg` - для `RG`
|
||||||
- `pkg/cloudapi/sizes` - для `Sizes`
|
- `pkg/cloudapi/sizes` - для `Sizes`
|
||||||
- `pkg/cloudapi/stack` - для `Stack`
|
- `pkg/cloudapi/stack` - для `Stack`
|
||||||
- `pkg/cloudapi/tasks` - для `Tasks`
|
- `pkg/cloudapi/tasks` - для `Tasks`
|
||||||
- `pkg/cloudapi/vins` - для `VINS`
|
- `pkg/cloudapi/vins` - для `VINS`
|
||||||
- **cloudbroker**:
|
- **cloudbroker**:
|
||||||
- `pkg/cloudbroker/account` - для `Account`
|
- `pkg/cloudbroker/account` - для `Account`
|
||||||
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
|
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
|
||||||
- `pkg/cloudbroker/backup` - для `Backup`
|
- `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/flipgroup` - для `FLIPGroup`
|
||||||
- `pkg/cloudbroker/grid` - для `Grid`
|
- `pkg/cloudbroker/grid` - для `Grid`
|
||||||
- `pkg/cloudbroker/group` - для `Group`
|
- `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/pcidevice` - для `PCIDevice`
|
||||||
- `pkg/cloudbroker/rg` - для `RG`
|
- `pkg/cloudbroker/rg` - для `RG`
|
||||||
- `pkg/cloudbroker/sep` - для `SEP`
|
- `pkg/cloudbroker/sep` - для `SEP`
|
||||||
- `pkg/cloudbroker/stack` - для `Stack`
|
- `pkg/cloudbroker/stack` - для `Stack`
|
||||||
- `pkg/cloudbroker/tasks` - для `Tasks`
|
- `pkg/cloudbroker/tasks` - для `Tasks`
|
||||||
- `pkg/cloudbroker/user` - для `User`
|
- `pkg/cloudbroker/user` - для `User`
|
||||||
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
||||||
- `pkg/cloudbroker/vins` - для `VINS`
|
- `pkg/cloudbroker/vins` - для `VINS`
|
||||||
|
|
||||||
Все поля структуры имеют описание, в которых содержится:
|
Все поля структуры имеют описание, в которых содержится:
|
||||||
|
|
||||||
@@ -421,50 +436,50 @@ func main() {
|
|||||||
|
|
||||||
Доступные методы для `.CloudAPI()`:
|
Доступные методы для `.CloudAPI()`:
|
||||||
|
|
||||||
- `.Account()` - для работы с `Account`
|
- `.Account()` - для работы с `Account`
|
||||||
- `.BService()` - для работы с `BService`
|
- `.BService()` - для работы с `BService`
|
||||||
- `.Compute()` - для работы с `Compute`
|
- `.Compute()` - для работы с `Compute`
|
||||||
- `.Disks()` - для работы с `Disks`
|
- `.Disks()` - для работы с `Disks`
|
||||||
- `.ExtNet()` - для работы с `ExtNet`
|
- `.ExtNet()` - для работы с `ExtNet`
|
||||||
- `.FLIPgroup()` - для работы с `FLIPGroup`
|
- `.FLIPgroup()` - для работы с `FLIPGroup`
|
||||||
- `.Image()` - для работы с `Image`
|
- `.Image()` - для работы с `Image`
|
||||||
- `.K8CI()` - для работы с `K8CI`
|
- `.K8CI()` - для работы с `K8CI`
|
||||||
- `.K8S()` - для работы с `K8S`
|
- `.K8S()` - для работы с `K8S`
|
||||||
- `.KVMPPC()` - для работы с `KVMPPC`
|
- `.KVMPPC()` - для работы с `KVMPPC`
|
||||||
- `.KVMx86()` - для работы с `KVMX86`
|
- `.KVMx86()` - для работы с `KVMX86`
|
||||||
- `.LB()` - для работы с `LB`
|
- `.LB()` - для работы с `LB`
|
||||||
- `.Locations()` - для работы с `Locations`
|
- `.Locations()` - для работы с `Locations`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.RG()` - для работы с `RG`
|
||||||
- `.Sizes()` - для работы с `Sizes`
|
- `.Sizes()` - для работы с `Sizes`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.Stack()` - для работы с `Stack`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
- `.VINS()` - для работы с `VINS`
|
- `.VINS()` - для работы с `VINS`
|
||||||
|
|
||||||
Доступные методы для `.CloudBroker()`:
|
Доступные методы для `.CloudBroker()`:
|
||||||
|
|
||||||
- `.Account()` - для работы с `Account`
|
- `.Account()` - для работы с `Account`
|
||||||
- `.APIAccess()` - для работы с `APIAccess`
|
- `.APIAccess()` - для работы с `APIAccess`
|
||||||
- `.Backup()` - для работы с `Backup`
|
- `.Backup()` - для работы с `Backup`
|
||||||
- `.Compute()` - для работы с `Compute`
|
- `.Compute()` - для работы с `Compute`
|
||||||
- `.Disks()` - для работы с `Disks`
|
- `.Disks()` - для работы с `Disks`
|
||||||
- `.ExtNet()` - для работы с `ExtNet`
|
- `.ExtNet()` - для работы с `ExtNet`
|
||||||
- `.FLIPGroup()` - для работы с `FLIPGroup`
|
- `.FLIPGroup()` - для работы с `FLIPGroup`
|
||||||
- `.Grid()` - для работы с `Grid`
|
- `.Grid()` - для работы с `Grid`
|
||||||
- `.Group()` - для работы с `Group`
|
- `.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`
|
- `.PCIDevice()` - для работы с `PCIDevice`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.RG()` - для работы с `RG`
|
||||||
- `.SEP()` - для работы с `SEP`
|
- `.SEP()` - для работы с `SEP`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.Stack()` - для работы с `Stack`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
- `.User()` - для работы с `User`
|
- `.User()` - для работы с `User`
|
||||||
- `.VGPU()` - для работы с `VGPU`
|
- `.VGPU()` - для работы с `VGPU`
|
||||||
- `.VINS()` - для работы с `VINS`
|
- `.VINS()` - для работы с `VINS`
|
||||||
|
|
||||||
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||||
|
|
||||||
@@ -635,7 +650,7 @@ filtered := resp.
|
|||||||
```go
|
```go
|
||||||
func main() {
|
func main() {
|
||||||
// Чтение конфигурации из файла
|
// Чтение конфигурации из файла
|
||||||
cfg := config.ParseConfigJSON("<PATH>")
|
cfg, _ := config.ParseConfigJSON("<PATH>")
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
client := decort.New(cfg)
|
client := decort.New(cfg)
|
||||||
@@ -767,7 +782,7 @@ func main() {
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Получение списка уникальных идентификаторов (ID) объекта
|
### Получение списка уникальных идентификаторов ID объекта
|
||||||
|
|
||||||
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
|
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
|
||||||
|
|
||||||
@@ -864,7 +879,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из YAML-файла
|
// Парсинг конфигурации из YAML-файла
|
||||||
legacyCfg := config.ParseLegacyConfigYAML("<PATH>")
|
legacyCfg, _ := config.ParseLegacyConfigYAML("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -916,7 +931,7 @@ func main() {
|
|||||||
legacyCfg.SetTimeout(5 * time.Minute)
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(cfg)
|
legacyClient := decort.NewLegacy(legacyCfg)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -943,7 +958,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(cfg)
|
legacyClient := decort.NewLegacy(legacyCfg)
|
||||||
|
|
||||||
// Создание структуры запроса
|
// Создание структуры запроса
|
||||||
// CreateRequest - реквест на создание виртуальной машины
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
@@ -956,7 +971,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Выполнение запроса
|
// Выполнение запроса
|
||||||
res, err := client.CloudAPI().KVMX86().Create(context.Background(), req)
|
res, err := legacyClient.CloudAPI().KVMX86().Create(context.Background(), req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -969,21 +984,43 @@ func main() {
|
|||||||
|
|
||||||
Работа с BVS клиентом применяется для пользователей, которые используют для авторизации BVS.
|
Работа с BVS клиентом применяется для пользователей, которые используют для авторизации BVS.
|
||||||
|
|
||||||
|
### Настройка параметров BVS в кабинете администратора
|
||||||
|
|
||||||
|
Для корректной работы функции обновления токена необходимо соблюдать следующие условия:
|
||||||
|
|
||||||
|
на странице администратора по следующему пути: домены-<имя вашего домена>-(символ i)-токены
|
||||||
|
- параметр "Время жизни токена доступа" - устанавливается для всего домена. Не применяется есть по следующему пути: безопасность-клиентские_системы-(символ i)-токены-"Время жизни токена доступа" не выставлено иное время, которое имеет больший приоритет для конкретной клиентской системы
|
||||||
|
- параметр "Время простоя сессии" - время жизни токена обновления. В случае указания количества минут меньше, чем время жизни токена, то обновление токена будет работать некорректно. Редомендуется указывать время или равное или больше времени жизни токена
|
||||||
|
- параметр "Максимальное время жизни сессии" - время в течение которого возможно производить обновление токена. Если данный параметр будет равен времени жизни токена, то обновление токена будет работать некорректно. Редомендуется указывать время больше времени жизни токена
|
||||||
|
|
||||||
### Настройка конфигурации BVS клиента
|
### Настройка конфигурации BVS клиента
|
||||||
|
|
||||||
Сначала, необходимо создать переменную конфигурации клиента. Конфигурация состоит как из обязательных, так и необязательных полей.
|
Сначала, необходимо создать переменную конфигурации клиента. Конфигурация состоит как из обязательных, так и необязательных полей.
|
||||||
|
|
||||||
| Поле | Тип | Обязательный | Описание |
|
| Поле | Тип | Обязательный | Описание |
|
||||||
| ------------- | ------ | ------------ | ------------------------------------------------------------------ |
|
| ------------- | --------------------------------------------- | ------------ | ------------------------------------------------------------------ |
|
||||||
| Username | string | Да | username legacy пользователя |
|
| Username | string | Да | username пользователя |
|
||||||
| Password | string | Да | пароль legacy пользователя |
|
| Password | string | Да | пароль пользователя |
|
||||||
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
| AppID | string | Да | app_id ключа для выполнения запросов |
|
||||||
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
| AppSecret | string | Да | app_secret ключ для выполнения запроса |
|
||||||
| Domain | string | Да | Имя домена |
|
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||||
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
||||||
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
| Domain | string | Да | Имя домена |
|
||||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||||
|
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||||
|
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||||
|
| Token | struct{} [см. ниже](#описание-структуры-token)| Нет | JWT токен |
|
||||||
|
| PathCfg | string | Нет | Путь записи конфигурации в файл |
|
||||||
|
| PathToken | string | Нет | Путь записи токена в файл |
|
||||||
|
| TimeToRefresh | uint | Нет | Количество минут, за сколько до истечения срока действия токена выполнится его обновление, по умолчанию - 1 минута |
|
||||||
|
|
||||||
|
### Описание структуры token
|
||||||
|
| Параметр | Тип | Описание |
|
||||||
|
| ------------ | ------ | ------------------------------- |
|
||||||
|
| AccessToken | string | Токен |
|
||||||
|
| TokenType | string | Тип токена |
|
||||||
|
| RefreshToken | string | Токен для запроса на обновление |
|
||||||
|
| Expiry | time | Время жизни токена |
|
||||||
|
|
||||||
#### Пример конфигурации BVS клиента
|
#### Пример конфигурации BVS клиента
|
||||||
|
|
||||||
@@ -999,9 +1036,9 @@ func main(){
|
|||||||
AppSecret: "<APP_SECRET>",
|
AppSecret: "<APP_SECRET>",
|
||||||
Username: "<USERNAME>",
|
Username: "<USERNAME>",
|
||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
SSOURL: "https://bvs-delta.qa.loc:8443"
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
DecortURL: "https://delta.qa.loc",
|
DecortURL: "https://delta.qa.loc",
|
||||||
Domain: "dynamix"
|
Domain: "dynamix",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1022,7 +1059,24 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из YAML-файла
|
// Парсинг конфигурации из YAML-файла
|
||||||
BVSCfg := config.ParseConfigBVSYAML("<PATH>")
|
BVSCfg, _ := config.ParseConfigBVSYAML("<PATH>")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Парсинг BVS токена из файла
|
||||||
|
|
||||||
|
Также возможно создать переменную токена из JSON или YAML файла, используя функцию `ParseTokenBVSJSON` (или `ParseTokenBVSYAML`) из пакета config.
|
||||||
|
<br>
|
||||||
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Парсинг токена из json-файла
|
||||||
|
BVSToken, _ := config.ParseTokenBVSJSON("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1037,9 +1091,18 @@ func main() {
|
|||||||
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
||||||
"decortUrl": "https://delta.qa.loc",
|
"decortUrl": "https://delta.qa.loc",
|
||||||
"domain": "dynamix",
|
"domain": "dynamix",
|
||||||
|
"token": {
|
||||||
|
"access_token": "string_token",
|
||||||
|
"token_type": "bearer",
|
||||||
|
"refresh_token": "string_refresh_token",
|
||||||
|
"expiry": "2023-11-24T12:40:27.954150524+03:00"
|
||||||
|
},
|
||||||
"retries": 5,
|
"retries": 5,
|
||||||
|
"sslSkipVerify": true,
|
||||||
"timeout": "5m",
|
"timeout": "5m",
|
||||||
"sslSkipVerify": false
|
"path_cfg": "config",
|
||||||
|
"path_token": "token",
|
||||||
|
"timeToRefresh": 5
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1051,10 +1114,18 @@ func main() {
|
|||||||
appSecret: <APP_SECRET>
|
appSecret: <APP_SECRET>
|
||||||
ssoUrl: https://bvs-delta.qa.loc:8443
|
ssoUrl: https://bvs-delta.qa.loc:8443
|
||||||
decortUrl: https://delta.qa.loc
|
decortUrl: https://delta.qa.loc
|
||||||
domain: dynamix,
|
domain: dynamix
|
||||||
|
token":
|
||||||
|
access_token: string_token
|
||||||
|
token_type: bearer
|
||||||
|
refresh_token: string_refresh_token
|
||||||
|
expiry: 2023-11-24T12:40:27.954150524+03:00
|
||||||
retries: 5
|
retries: 5
|
||||||
|
sslSkipVerify: true
|
||||||
timeout: 5m
|
timeout: 5m
|
||||||
sslSkipVerify: false
|
path_cfg: config
|
||||||
|
path_token: token
|
||||||
|
timeToRefresh: 5
|
||||||
```
|
```
|
||||||
### Создание BVS клиента
|
### Создание BVS клиента
|
||||||
|
|
||||||
@@ -1077,7 +1148,7 @@ func main() {
|
|||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
AppID: "<APPID>",
|
AppID: "<APPID>",
|
||||||
AppSecret: "<APPSECRET>",
|
AppSecret: "<APPSECRET>",
|
||||||
SSOURL: "https://bvs-delta.qa.loc:8443"
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Domain: "dynamix",
|
Domain: "dynamix",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
@@ -1086,7 +1157,89 @@ func main() {
|
|||||||
BVSCfg.SetTimeout(5 * time.Minute)
|
BVSCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
BVSClient := decort.NewBVS(cfg)
|
BVSClient := decort.NewBVS(BVSCfg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример получения BVS токена
|
||||||
|
|
||||||
|
В случае указания значения в переменной конфигурации `PathCfg` токен и конфигурация будут записаны в файл в формате `json`, переменная `PathToken` служит для записи токена в файл в формате `json`
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
BVSCfg := config.BVSConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Domain: "dynamix",
|
||||||
|
PathCfg: "config",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
BVSClient := decort.NewBVS(BVSCfg)
|
||||||
|
|
||||||
|
// Выполнение запроса на получение токена
|
||||||
|
token, err := BVSClient.GetToken(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(token)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример обновления BVS токена
|
||||||
|
|
||||||
|
В случае указания значения в переменной конфигурации `PathCfg` обновленный токен и конфигурация будут записаны в файл в формате `json`, переменная `PathToken` служит для записи токена в файл в формате `json`
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
BVSCfg := config.BVSConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Domain: "dynamix",
|
||||||
|
PathToken: "token",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
BVSClient := decort.NewBVS(BVSCfg)
|
||||||
|
|
||||||
|
// Выполнение запроса на обновление токена
|
||||||
|
token, err := BVSClient.RefreshToken(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(token)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1104,19 +1257,19 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Настройка конфигурации
|
// Настройка конфигурации
|
||||||
BVSCfg := config.config.BVSConfig{
|
BVSCfg := config.BVSConfig{
|
||||||
Username: "<USERNAME>",
|
Username: "<USERNAME>",
|
||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
AppID: "<APPID>",
|
AppID: "<APPID>",
|
||||||
AppSecret: "<APPSECRET>",
|
AppSecret: "<APPSECRET>",
|
||||||
SSOURL: "https://bvs-delta.qa.loc:8443"
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Domain: "dynamix",
|
Domain: "dynamix",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
BVSClient := decort.NewBVS(cfg)
|
BVSClient := decort.NewBVS(BVSCfg)
|
||||||
|
|
||||||
// Создание структуры запроса
|
// Создание структуры запроса
|
||||||
// CreateRequest - реквест на создание виртуальной машины
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
@@ -1129,10 +1282,11 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Выполнение запроса
|
// Выполнение запроса
|
||||||
res, err := client.CloudAPI().KVMX86().Create(context.Background(), req)
|
res, err := BVSClient.CloudAPI().KVMX86().Create(context.Background(), req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|||||||
517
client.go
517
client.go
@@ -4,11 +4,11 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -16,15 +16,12 @@ import (
|
|||||||
|
|
||||||
"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/constants"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
k8s_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const restmachine = "/restmachine"
|
// DecortClient is HTTP-client for platform
|
||||||
|
|
||||||
// HTTP-client for platform
|
|
||||||
type DecortClient struct {
|
type DecortClient struct {
|
||||||
decortURL string
|
decortURL string
|
||||||
client *http.Client
|
client *http.Client
|
||||||
@@ -73,340 +70,270 @@ func (dc *DecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
|||||||
|
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
|
values, err := query.Values(params)
|
||||||
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
|
|
||||||
var body *bytes.Buffer
|
|
||||||
var ctype string
|
|
||||||
|
|
||||||
if okCa {
|
|
||||||
body, ctype = createK8sCloudApi(k8sCaCreateReq)
|
|
||||||
} else if okCb {
|
|
||||||
body, ctype = createK8sCloudBroker(k8sCbCreateReq)
|
|
||||||
} else {
|
|
||||||
values, err := query.Values(params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
body = bytes.NewBufferString(values.Encode())
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+restmachine+url, body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
body := bytes.NewBufferString(values.Encode())
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.Restmachine+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
if err = dc.getToken(ctx); err != nil {
|
if err = dc.getToken(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := dc.do(req, ctype)
|
// perform request
|
||||||
if err != nil {
|
respBytes, err := dc.do(req, "")
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBytes, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
return respBytes, err
|
||||||
return nil, errors.New(string(respBytes))
|
}
|
||||||
|
|
||||||
|
// DecortApiCallMP method for sending requests to the platform
|
||||||
|
func (dc *DecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return respBytes, nil
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.Restmachine+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if err = dc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
respBytes, err := dc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dc *DecortClient) getToken(ctx context.Context) error {
|
func (dc *DecortClient) getToken(ctx context.Context) error {
|
||||||
dc.mutex.Lock()
|
dc.mutex.Lock()
|
||||||
defer dc.mutex.Unlock()
|
defer dc.mutex.Unlock()
|
||||||
|
|
||||||
if dc.cfg.Token == "" || time.Now().After(dc.expiryTime) {
|
// new token is not needed
|
||||||
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
if dc.cfg.Token != "" && !time.Now().After(dc.expiryTime) {
|
||||||
bodyReader := strings.NewReader(body)
|
return nil
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
dc.cfg.SSOURL = strings.TrimSuffix(dc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", dc.cfg.SSOURL+"/v1/oauth/access_token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// request token
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
token := string(tokenBytes)
|
||||||
|
dc.cfg.Token = token
|
||||||
|
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dc *DecortClient) do(req *http.Request, ctype string) (*http.Response, error) {
|
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||||
|
// In any other cases do returns nil response and error.
|
||||||
|
// Retries are implemented in case of connection reset errors.
|
||||||
|
func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||||
|
// set up request headers and body
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
if ctype != "" {
|
if ctype != "" {
|
||||||
req.Header.Add("Content-Type", ctype)
|
req.Header.Set("Content-Type", ctype)
|
||||||
} else {
|
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
// var resp *http.Response
|
buf, err := io.ReadAll(req.Body)
|
||||||
// var err error
|
if err != nil {
|
||||||
buf, _ := io.ReadAll(req.Body)
|
return nil, err
|
||||||
// req = req.Clone(req.Context())
|
|
||||||
|
|
||||||
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
|
||||||
resp, err := dc.client.Do(req)
|
|
||||||
|
|
||||||
// if err == nil {
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return resp, err
|
|
||||||
}
|
}
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
|
||||||
err = fmt.Errorf("%s", respBytes)
|
|
||||||
resp.Body.Close()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
req.Body.Close()
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
if resp != nil {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// retries logic GOES HERE
|
||||||
|
// get http response
|
||||||
|
//var resp *http.Response
|
||||||
|
//for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||||
|
// req := req.Clone(req.Context())
|
||||||
|
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
//
|
||||||
|
// if i > 0 {
|
||||||
|
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// resp, err = dc.client.Do(req)
|
||||||
|
//
|
||||||
|
// // stop retries on success and close response body
|
||||||
|
// if resp != nil {
|
||||||
|
// defer resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// if err == nil {
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // retries in case of connection errors with time sleep
|
||||||
|
// if isConnectionError(err) {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // return error in case of non-connection error
|
||||||
|
// return nil, err
|
||||||
|
//}
|
||||||
|
|
||||||
|
// handle http request errors
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle successful request
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle errors with status code other than 200
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func createK8sCloudApi(req k8s_ca.CreateRequest) (*bytes.Buffer, string) {
|
// isConnectionError checks if given error falls within specific and associated connection errors
|
||||||
|
//func isConnectionError(err error) bool {
|
||||||
|
// if strings.Contains(err.Error(), "connection reset by peer") {
|
||||||
|
// return true
|
||||||
|
// }
|
||||||
|
// if errors.Is(err, io.EOF) {
|
||||||
|
// return true
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return false
|
||||||
|
//}
|
||||||
|
|
||||||
|
// multiPartReq writes the request structure to the request body, and also returns string of the content-type
|
||||||
|
func multiPartReq(params interface{}) (*bytes.Buffer, string, error) {
|
||||||
reqBody := &bytes.Buffer{}
|
reqBody := &bytes.Buffer{}
|
||||||
writer := multipart.NewWriter(reqBody)
|
writer := multipart.NewWriter(reqBody)
|
||||||
if req.OidcCertificate != "" {
|
values := reflect.ValueOf(params)
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
types := values.Type()
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
defer writer.Close()
|
||||||
}
|
for i := 0; i < values.NumField(); i++ {
|
||||||
|
if !values.Field(i).IsValid() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
_ = writer.WriteField("name", req.Name)
|
if values.Field(i).IsZero() {
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
continue
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8SCIID, 10))
|
}
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
if file, ok := constants.FileName[types.Field(i).Name]; ok {
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
part, err := writer.CreateFormFile(trimString(types.Field(i)), file)
|
||||||
}
|
if err != nil {
|
||||||
if req.MasterSEPPool != "" {
|
return &bytes.Buffer{}, "", err
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
}
|
||||||
}
|
_, err = io.Copy(part, strings.NewReader(valueToString(values.Field(i).Interface())))
|
||||||
if req.WorkerSEPID != 0 {
|
if err != nil {
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
return &bytes.Buffer{}, "", err
|
||||||
}
|
}
|
||||||
if req.WorkerSEPPool != "" {
|
continue
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
if values.Field(i).Type().Kind() == reflect.Slice {
|
||||||
for _, v := range req.Labels {
|
switch slice := values.Field(i).Interface().(type) {
|
||||||
_ = writer.WriteField("labels", v)
|
case []string:
|
||||||
|
for _, val := range slice {
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), val)
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case []uint:
|
||||||
|
for _, val := range slice {
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), strconv.FormatUint(uint64(val), 10))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case []uint64:
|
||||||
|
for _, val := range slice {
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), strconv.FormatUint(val, 10))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return &bytes.Buffer{}, "", fmt.Errorf("unsupported slice type:%T", slice)
|
||||||
|
}
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), valueToString(values.Field(i).Interface()))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(req.MasterCPU), 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(req.MasterNum), 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(req.MasterRAM), 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(req.MasterDisk), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(req.WorkerCPU), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(req.WorkerNum), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(req.WorkerRAM), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(req.WorkerDisk), 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
ct := writer.FormDataContentType()
|
||||||
writer.Close()
|
return reqBody, ct, nil
|
||||||
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func createK8sCloudBroker(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
|
func valueToString(a any) string {
|
||||||
reqBody := &bytes.Buffer{}
|
switch str := a.(type) {
|
||||||
writer := multipart.NewWriter(reqBody)
|
case string:
|
||||||
if req.OidcCertificate != "" {
|
return str
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
case uint:
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
return strconv.FormatUint(uint64(str), 10)
|
||||||
|
case uint64:
|
||||||
|
return strconv.FormatUint(str, 10)
|
||||||
|
case bool:
|
||||||
|
return strconv.FormatBool(str)
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
}
|
||||||
_ = writer.WriteField("name", req.Name)
|
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
func trimString(el reflect.StructField) string {
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8CIID, 10))
|
return strings.TrimSuffix(el.Tag.Get("url"), ",omitempty")
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.MasterSEPPool != "" {
|
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
|
||||||
}
|
|
||||||
if req.WorkerSEPID != 0 {
|
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerSEPPool != "" {
|
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
|
||||||
for _, v := range req.Labels {
|
|
||||||
_ = writer.WriteField("labels", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(req.MasterCPU, 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(req.MasterNum, 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(req.MasterRAM, 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(req.MasterDisk, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(req.WorkerCPU, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(req.WorkerNum, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(req.WorkerRAM, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(req.WorkerDisk, 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
|
|
||||||
writer.Close()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
}
|
||||||
|
|||||||
609
client_bvs.go
609
client_bvs.go
@@ -8,21 +8,19 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"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/constants"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
k8s_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// HTTP-client for platform
|
// BVSDecortClient is HTTP-client for platform
|
||||||
type BVSDecortClient struct {
|
type BVSDecortClient struct {
|
||||||
client *http.Client
|
client *http.Client
|
||||||
cfg config.BVSConfig
|
cfg config.BVSConfig
|
||||||
@@ -30,11 +28,21 @@ type BVSDecortClient struct {
|
|||||||
decortURL string
|
decortURL string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type tokenJSON struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
ExpiresIn uint64 `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
// Сlient builder
|
// Сlient builder
|
||||||
func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
||||||
if cfg.Retries == 0 {
|
if cfg.Retries == 0 {
|
||||||
cfg.Retries = 5
|
cfg.Retries = 5
|
||||||
}
|
}
|
||||||
|
if cfg.TimeToRefresh == 0 {
|
||||||
|
cfg.TimeToRefresh = 1
|
||||||
|
}
|
||||||
|
|
||||||
return &BVSDecortClient{
|
return &BVSDecortClient{
|
||||||
decortURL: cfg.DecortURL,
|
decortURL: cfg.DecortURL,
|
||||||
@@ -63,339 +71,310 @@ func (bdc *BVSDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
|||||||
|
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
|
values, err := query.Values(params)
|
||||||
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
|
if err != nil {
|
||||||
var body *bytes.Buffer
|
return nil, err
|
||||||
var ctype string
|
}
|
||||||
|
|
||||||
if okCa {
|
body := bytes.NewBufferString(values.Encode())
|
||||||
body, ctype = createK8sCloudApiBVS(k8sCaCreateReq)
|
|
||||||
} else if okCb {
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.Restmachine+url, body)
|
||||||
body, ctype = createK8sCloudBrokerBVS(k8sCbCreateReq)
|
if err != nil {
|
||||||
} else {
|
return nil, err
|
||||||
values, err := query.Values(params)
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if bdc.cfg.Token.AccessToken == "" {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||||
|
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
reqCopy := req.Clone(ctx)
|
||||||
|
respBytes, err := bdc.do(req, "")
|
||||||
|
if err == nil {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token and retry in case of access denied
|
||||||
|
if err.Error() == "access is denied" {
|
||||||
|
_, err = bdc.GetToken(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, err = bdc.do(reqCopy, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
body = bytes.NewBufferString(values.Encode())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+restmachine+url, body)
|
return respBytes, err
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = bdc.getToken(ctx); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := bdc.do(req, ctype)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBytes, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
|
||||||
return nil, errors.New(string(respBytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
return respBytes, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bdc *BVSDecortClient) getToken(ctx context.Context) error {
|
func (bdc *BVSDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.Restmachine+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if bdc.cfg.Token.AccessToken == "" {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||||
|
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
reqCopy := req.Clone(ctx)
|
||||||
|
respBytes, err := bdc.do(req, ctype)
|
||||||
|
if err == nil {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token and retry in case of access denied
|
||||||
|
if err.Error() == "access is denied" {
|
||||||
|
_, err = bdc.GetToken(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, err = bdc.do(reqCopy, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetToken allows you to get a token and returns the token structure. When specifying the PathCfg variable,
|
||||||
|
// the token and configuration will be written to a file.
|
||||||
|
// When specifying the PathToken variable, the token will be written to a file.
|
||||||
|
func (bdc *BVSDecortClient) GetToken(ctx context.Context) (config.Token, error) {
|
||||||
bdc.mutex.Lock()
|
bdc.mutex.Lock()
|
||||||
defer bdc.mutex.Unlock()
|
defer bdc.mutex.Unlock()
|
||||||
|
|
||||||
if !bdc.cfg.Token.Valid() {
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Username, bdc.cfg.Password)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Username, bdc.cfg.Password)
|
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||||
bodyReader := strings.NewReader(body)
|
|
||||||
|
|
||||||
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
|
||||||
|
|
||||||
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
resp, err := bdc.client.Do(req)
|
// request token
|
||||||
if err != nil {
|
resp, err := bdc.client.Do(req)
|
||||||
return fmt.Errorf("cannot get token: %w", err)
|
if err != nil || resp == nil {
|
||||||
}
|
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
tokenBytes, _ := io.ReadAll(resp.Body)
|
var tokenBytes []byte
|
||||||
resp.Body.Close()
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
if resp.StatusCode != 200 {
|
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||||
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = json.Unmarshal(tokenBytes, &bdc.cfg.Token)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot unmarshal token: %s", tokenBytes)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
if resp.StatusCode != 200 {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
var tj tokenJSON
|
||||||
|
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot unmarshal token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bdc.cfg.Token = config.Token{
|
||||||
|
AccessToken: tj.AccessToken,
|
||||||
|
TokenType: tj.TokenType,
|
||||||
|
RefreshToken: tj.RefreshToken,
|
||||||
|
Expiry: tj.expiry(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathCfg != "" {
|
||||||
|
ser, _ := bdc.cfg.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathToken != "" {
|
||||||
|
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bdc.cfg.Token, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bdc *BVSDecortClient) do(req *http.Request, ctype string) (*http.Response, error) {
|
// RefreshToken allows you to refresh a token and returns the token structure. When specifying the PathCfg variable,
|
||||||
if ctype != "" {
|
// the token and configuration will be written to a file.
|
||||||
req.Header.Add("Content-Type", ctype)
|
// When specifying the PathToken variable, the token will be written to a file
|
||||||
} else {
|
func (bdc *BVSDecortClient) RefreshToken(ctx context.Context) (config.Token, error) {
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
bdc.mutex.Lock()
|
||||||
|
defer bdc.mutex.Unlock()
|
||||||
|
|
||||||
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Token.RefreshToken)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
resp, err := bdc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||||
}
|
}
|
||||||
bdc.cfg.Token.SetAuthHeader(req)
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
var tj tokenJSON
|
||||||
|
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot unmarshal after refresh token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bdc.cfg.Token = config.Token{
|
||||||
|
AccessToken: tj.AccessToken,
|
||||||
|
TokenType: tj.TokenType,
|
||||||
|
RefreshToken: tj.RefreshToken,
|
||||||
|
Expiry: tj.expiry(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathCfg != "" {
|
||||||
|
ser, _ := bdc.cfg.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathToken != "" {
|
||||||
|
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bdc.cfg.Token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *tokenJSON) expiry() (t time.Time) {
|
||||||
|
if v := e.ExpiresIn; v != 0 {
|
||||||
|
return time.Now().Add(time.Duration(v) * time.Second)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||||
|
// In any other cases do returns nil response and error.
|
||||||
|
// Retries are implemented in case of connection reset errors.
|
||||||
|
func (bdc *BVSDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||||
|
// set up request headers and body
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
if ctype != "" {
|
||||||
|
req.Header.Set("Content-Type", ctype)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Add("Authorization", "bearer "+bdc.cfg.Token.AccessToken)
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
// var resp *http.Response
|
buf, err := io.ReadAll(req.Body)
|
||||||
// var err error
|
if err != nil {
|
||||||
buf, _ := io.ReadAll(req.Body)
|
return nil, err
|
||||||
// req = req.Clone(req.Context())
|
|
||||||
|
|
||||||
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
|
||||||
resp, err := bdc.client.Do(req)
|
|
||||||
// if err == nil {
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return resp, err
|
|
||||||
}
|
}
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
|
||||||
err = fmt.Errorf("%s", respBytes)
|
|
||||||
resp.Body.Close()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
req.Body.Close()
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
resp, err := bdc.client.Do(req)
|
||||||
|
if resp != nil {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// retries logic GOES HERE
|
||||||
|
// get http response
|
||||||
|
//var resp *http.Response
|
||||||
|
//for i := uint64(0); i < bdc.cfg.Retries; i++ {
|
||||||
|
// req := req.Clone(req.Context())
|
||||||
|
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
//
|
||||||
|
// if i > 0 {
|
||||||
|
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// resp, err = bdc.client.Do(req)
|
||||||
|
//
|
||||||
|
// // stop retries on success and close response body
|
||||||
|
// if resp != nil {
|
||||||
|
// defer resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// if err == nil {
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // retries in case of connection errors with time sleep
|
||||||
|
// if isConnectionError(err) {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // return error in case of non-connection error
|
||||||
|
// return nil, err
|
||||||
|
//}
|
||||||
|
|
||||||
|
// handle http request errors
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
|
var respBytes []byte
|
||||||
|
respBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle access denied and successful request
|
||||||
|
if resp.StatusCode == 401 {
|
||||||
|
return respBytes, errors.New("access is denied")
|
||||||
|
}
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle errors with other status codes
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func createK8sCloudApiBVS(req k8s_ca.CreateRequest) (*bytes.Buffer, string) {
|
|
||||||
reqBody := &bytes.Buffer{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
if req.OidcCertificate != "" {
|
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("name", req.Name)
|
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8SCIID, 10))
|
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.MasterSEPPool != "" {
|
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
|
||||||
}
|
|
||||||
if req.WorkerSEPID != 0 {
|
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerSEPPool != "" {
|
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
|
||||||
for _, v := range req.Labels {
|
|
||||||
_ = writer.WriteField("labels", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(req.MasterCPU), 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(req.MasterNum), 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(req.MasterRAM), 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(req.MasterDisk), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(req.WorkerCPU), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(req.WorkerNum), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(req.WorkerRAM), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(req.WorkerDisk), 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
writer.Close()
|
|
||||||
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|
||||||
func createK8sCloudBrokerBVS(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
|
|
||||||
reqBody := &bytes.Buffer{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
if req.OidcCertificate != "" {
|
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("name", req.Name)
|
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8CIID, 10))
|
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.MasterSEPPool != "" {
|
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
|
||||||
}
|
|
||||||
if req.WorkerSEPID != 0 {
|
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerSEPPool != "" {
|
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
|
||||||
for _, v := range req.Labels {
|
|
||||||
_ = writer.WriteField("labels", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(req.MasterCPU, 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(req.MasterNum, 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(req.MasterRAM, 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(req.MasterDisk, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(req.WorkerCPU, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(req.WorkerNum, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(req.WorkerRAM, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(req.WorkerDisk, 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
|
|
||||||
writer.Close()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/oauth2"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ type BVSConfig struct {
|
|||||||
// Domain name
|
// Domain name
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "dynamix"
|
// Example: "dynamix"
|
||||||
Domain string `json:"domain" yaml:"domain"`
|
Domain string `json:"domain" yaml:"domain" validate:"required"`
|
||||||
|
|
||||||
// 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.
|
||||||
@@ -50,7 +50,7 @@ type BVSConfig struct {
|
|||||||
// JWT platform token
|
// JWT platform token
|
||||||
// Required: false
|
// Required: false
|
||||||
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
||||||
Token oauth2.Token `json:"token" yaml:"token"`
|
Token Token `json:"token" yaml:"token"`
|
||||||
|
|
||||||
// Amount platform request attempts
|
// Amount platform request attempts
|
||||||
// Default value: 5
|
// Default value: 5
|
||||||
@@ -64,6 +64,40 @@ type BVSConfig struct {
|
|||||||
// HTTP client timeout, unlimited if left empty
|
// HTTP client timeout, unlimited if left empty
|
||||||
// Required: false
|
// Required: false
|
||||||
Timeout Duration `json:"timeout" yaml:"timeout"`
|
Timeout Duration `json:"timeout" yaml:"timeout"`
|
||||||
|
|
||||||
|
// The path of the configuration file entry
|
||||||
|
// Required: false
|
||||||
|
PathCfg string `json:"path_cfg" yaml:"path_cfg"`
|
||||||
|
|
||||||
|
// The path of the token file entry
|
||||||
|
// Required: false
|
||||||
|
PathToken string `json:"path_token" yaml:"path_token"`
|
||||||
|
|
||||||
|
// The number of minutes before the expiration of the token, a refresh will be made
|
||||||
|
// Required: false
|
||||||
|
TimeToRefresh int64 `json:"timeToRefresh" yaml:"timeToRefresh"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Token struct {
|
||||||
|
// AccessToken is the token that authorizes and authenticates
|
||||||
|
// the requests.
|
||||||
|
// Required: false
|
||||||
|
AccessToken string `json:"access_token" yaml:"access_token"`
|
||||||
|
|
||||||
|
// TokenType is the type of token.
|
||||||
|
// The Type method returns either this or "Bearer", the default.
|
||||||
|
// Required: false
|
||||||
|
TokenType string `json:"token_type" yaml:"token_type"`
|
||||||
|
|
||||||
|
// RefreshToken is a token that's used by the application
|
||||||
|
// (as opposed to the user) to refresh the access token
|
||||||
|
// if it expires.
|
||||||
|
// Required: false
|
||||||
|
RefreshToken string `json:"refresh_token" yaml:"refresh_token"`
|
||||||
|
|
||||||
|
// Expiry is the optional expiration time of the access token.
|
||||||
|
// Required: false
|
||||||
|
Expiry time.Time `json:"expiry" yaml:"expiry"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTimeout is used to set HTTP client timeout.
|
// SetTimeout is used to set HTTP client timeout.
|
||||||
@@ -93,6 +127,50 @@ func ParseConfigBVSJSON(path string) (BVSConfig, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseConfigJSON parses Token from specified JSON-formatted file.
|
||||||
|
func ParseTokenBVSJSON(path string) (Token, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var token Token
|
||||||
|
|
||||||
|
err = json.Unmarshal(file, &token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseTokenBVSYAML parses Token from specified YAML-formatted file.
|
||||||
|
func ParseTokenBVSYAML(path string) (Token, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var token Token
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(file, &token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ParseConfigYAML parses Config from specified YAML-formatted file.
|
// ParseConfigYAML parses Config from specified YAML-formatted file.
|
||||||
func ParseConfigBVSYAML(path string) (BVSConfig, error) {
|
func ParseConfigBVSYAML(path string) (BVSConfig, error) {
|
||||||
file, err := os.ReadFile(path)
|
file, err := os.ReadFile(path)
|
||||||
@@ -114,3 +192,25 @@ func ParseConfigBVSYAML(path string) (BVSConfig, error) {
|
|||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t Token) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(t, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c BVSConfig) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(c, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(c)
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
|||||||
}
|
}
|
||||||
*d = Duration(tmp)
|
*d = Duration(tmp)
|
||||||
return nil
|
return nil
|
||||||
|
case float64:
|
||||||
|
return nil
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("invalid duration %v", value)
|
return fmt.Errorf("invalid duration %v", value)
|
||||||
}
|
}
|
||||||
@@ -40,6 +42,8 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
|
|||||||
}
|
}
|
||||||
*d = Duration(tmp)
|
*d = Duration(tmp)
|
||||||
return nil
|
return nil
|
||||||
|
case float64:
|
||||||
|
return nil
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("invalid duration %v", value)
|
return fmt.Errorf("invalid duration %v", value)
|
||||||
}
|
}
|
||||||
|
|||||||
12
go.mod
12
go.mod
@@ -5,20 +5,16 @@ 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
|
||||||
golang.org/x/oauth2 v0.13.0
|
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
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/golang/protobuf v1.5.3 // indirect
|
github.com/google/go-cmp v0.5.9 // indirect
|
||||||
github.com/kr/text v0.2.0 // 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.14.0 // indirect
|
golang.org/x/crypto v0.15.0 // indirect
|
||||||
golang.org/x/net v0.16.0 // indirect
|
golang.org/x/sys v0.14.0 // indirect
|
||||||
golang.org/x/sys v0.13.0 // indirect
|
golang.org/x/text v0.14.0 // indirect
|
||||||
golang.org/x/text v0.13.0 // indirect
|
|
||||||
google.golang.org/appengine v1.6.7 // indirect
|
|
||||||
google.golang.org/protobuf v1.31.0 // indirect
|
|
||||||
)
|
)
|
||||||
|
|||||||
34
go.sum
34
go.sum
@@ -8,13 +8,9 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
|||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU=
|
github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU=
|
||||||
github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s=
|
github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s=
|
||||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
|
||||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
|
||||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
|
||||||
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-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
|
||||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||||
|
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
github.com/google/go-querystring v1.1.0 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/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
@@ -28,29 +24,13 @@ github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUA
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/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=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
|
||||||
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
|
||||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
||||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/net v0.16.0 h1:7eBu7KsSvFDtSXUIDbh3aqlK4DPsZ1rByC8PFfBThos=
|
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||||
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY=
|
|
||||||
golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
|
||||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
|
||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
|
||||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
|
||||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
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=
|
||||||
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
|
|
||||||
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
|
||||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
|
||||||
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
|
||||||
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
|
||||||
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/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=
|
||||||
|
|||||||
@@ -6,4 +6,7 @@ import "context"
|
|||||||
type Caller interface {
|
type Caller interface {
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
||||||
|
|
||||||
|
// DecortApiCallMP method for sending requests to the platform
|
||||||
|
DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|||||||
7
internal/constants/constants.go
Normal file
7
internal/constants/constants.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package constants
|
||||||
|
|
||||||
|
const Restmachine = "/restmachine"
|
||||||
|
|
||||||
|
var FileName = map[string]string{
|
||||||
|
"OidcCertificate": "ca.crt",
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ var (
|
|||||||
|
|
||||||
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
||||||
|
|
||||||
networkPluginValues = []string{"flannel", "weawenet", "calico"}
|
networkPluginValues = []string{"flannel", "weavenet", "calico"}
|
||||||
|
|
||||||
strictLooseValues = []string{"strict", "loose"}
|
strictLooseValues = []string{"strict", "loose"}
|
||||||
|
|
||||||
|
|||||||
443
legacy-client.go
443
legacy-client.go
@@ -4,26 +4,22 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"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/constants"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
k8s_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Legacy HTTP-client for platform
|
// LegacyDecortClient is Legacy HTTP-client for platform
|
||||||
type LegacyDecortClient struct {
|
type LegacyDecortClient struct {
|
||||||
decortURL string
|
decortURL string
|
||||||
client *http.Client
|
client *http.Client
|
||||||
@@ -72,341 +68,168 @@ func (ldc *LegacyDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
|||||||
|
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
// get token
|
||||||
if err := ldc.getToken(ctx); err != nil {
|
if err := ldc.getToken(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
|
values, err := query.Values(params)
|
||||||
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
|
|
||||||
|
|
||||||
var body *bytes.Buffer
|
|
||||||
var ctype string
|
|
||||||
|
|
||||||
if okCa {
|
|
||||||
body, ctype = createK8sCloudApiLegacy(k8sCaCreateReq, ldc.cfg.Token)
|
|
||||||
} else if okCb {
|
|
||||||
body, ctype = createK8sCloudBrokerLegacy(k8sCbCreateReq, ldc.cfg.Token)
|
|
||||||
} else {
|
|
||||||
values, err := query.Values(params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
body = bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+restmachine+url, body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := ldc.do(req, ctype)
|
body := bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBytes, err := io.ReadAll(resp.Body)
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.Restmachine+url, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
// perform request
|
||||||
return nil, errors.New(string(respBytes))
|
respBytes, err := ldc.do(req, "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return respBytes, nil
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ldc *LegacyDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.Restmachine+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if err = ldc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
respBytes, err := ldc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
||||||
ldc.mutex.Lock()
|
ldc.mutex.Lock()
|
||||||
defer ldc.mutex.Unlock()
|
defer ldc.mutex.Unlock()
|
||||||
|
|
||||||
if ldc.cfg.Token == "" || time.Now().After(ldc.expiryTime) {
|
// new token is not needed
|
||||||
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
if ldc.cfg.Token != "" && !time.Now().After(ldc.expiryTime) {
|
||||||
bodyReader := strings.NewReader(body)
|
return nil
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// request token
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
token := string(tokenBytes)
|
||||||
|
ldc.cfg.Token = token
|
||||||
|
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) (*http.Response, error) {
|
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||||
|
// In any other cases do returns nil response and error.
|
||||||
|
// Retries are implemented in case of connection reset errors.
|
||||||
|
func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||||
|
// set up request headers and body
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
if ctype != "" {
|
if ctype != "" {
|
||||||
req.Header.Add("Content-Type", ctype)
|
req.Header.Set("Content-Type", ctype)
|
||||||
} else {
|
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
// var resp *http.Response
|
buf, err := io.ReadAll(req.Body)
|
||||||
// var err error
|
if err != nil {
|
||||||
buf, _ := io.ReadAll(req.Body)
|
return nil, err
|
||||||
// req = req.Clone(req.Context())
|
|
||||||
|
|
||||||
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
|
||||||
|
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
|
||||||
resp, err := ldc.client.Do(req)
|
|
||||||
|
|
||||||
// if err == nil {
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return resp, err
|
|
||||||
}
|
}
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
|
||||||
err = fmt.Errorf("%s", respBytes)
|
|
||||||
resp.Body.Close()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
req.Body.Close()
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if resp != nil {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// retries logic GOES HERE
|
||||||
|
// get http response
|
||||||
|
//var resp *http.Response
|
||||||
|
//for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||||
|
// req := req.Clone(req.Context())
|
||||||
|
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
//
|
||||||
|
// if i > 0 {
|
||||||
|
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// resp, err = ldc.client.Do(req)
|
||||||
|
//
|
||||||
|
// // stop retries on success and close response body
|
||||||
|
// if resp != nil {
|
||||||
|
// defer resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// if err == nil {
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // retries in case of connection errors with time sleep
|
||||||
|
// if isConnectionError(err) {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // return error in case of non-connection error
|
||||||
|
// return nil, err
|
||||||
|
//}
|
||||||
|
|
||||||
|
// handle http request errors
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle successful request
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle errors with status code other than 200
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func createK8sCloudApiLegacy(req k8s_ca.CreateRequest, token string) (*bytes.Buffer, string) {
|
|
||||||
reqBody := &bytes.Buffer{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
if req.OidcCertificate != "" {
|
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("name", req.Name)
|
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8SCIID, 10))
|
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.MasterSEPPool != "" {
|
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
|
||||||
}
|
|
||||||
if req.WorkerSEPID != 0 {
|
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerSEPPool != "" {
|
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
|
||||||
for _, v := range req.Labels {
|
|
||||||
_ = writer.WriteField("labels", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(uint64(req.MasterCPU), 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(uint64(req.MasterNum), 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(uint64(req.MasterRAM), 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(uint64(req.MasterDisk), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(uint64(req.WorkerCPU), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(uint64(req.WorkerNum), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(uint64(req.WorkerRAM), 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(uint64(req.WorkerDisk), 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
_ = writer.WriteField("authkey", token)
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
writer.Close()
|
|
||||||
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|
||||||
func createK8sCloudBrokerLegacy(req k8s_cb.CreateRequest, token string) (*bytes.Buffer, string) {
|
|
||||||
reqBody := &bytes.Buffer{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
if req.OidcCertificate != "" {
|
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("name", req.Name)
|
|
||||||
_ = writer.WriteField("rgId", strconv.FormatUint(req.RGID, 10))
|
|
||||||
_ = writer.WriteField("k8ciId", strconv.FormatUint(req.K8CIID, 10))
|
|
||||||
_ = writer.WriteField("workerGroupName", req.WorkerGroupName)
|
|
||||||
_ = writer.WriteField("networkPlugin", req.NetworkPlugin)
|
|
||||||
|
|
||||||
if req.MasterSEPID != 0 {
|
|
||||||
_ = writer.WriteField("masterSepId", strconv.FormatUint(req.MasterSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.MasterSEPPool != "" {
|
|
||||||
_ = writer.WriteField("masterSepPool", req.MasterSEPPool)
|
|
||||||
}
|
|
||||||
if req.WorkerSEPID != 0 {
|
|
||||||
_ = writer.WriteField("workerSepId", strconv.FormatUint(req.WorkerSEPID, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerSEPPool != "" {
|
|
||||||
_ = writer.WriteField("workerSepPool", req.WorkerSEPPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Labels != nil {
|
|
||||||
for _, v := range req.Labels {
|
|
||||||
_ = writer.WriteField("labels", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Taints != nil {
|
|
||||||
for _, v := range req.Taints {
|
|
||||||
_ = writer.WriteField("taints", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.Annotations != nil {
|
|
||||||
for _, v := range req.Annotations {
|
|
||||||
_ = writer.WriteField("annotations", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.MasterCPU != 0 {
|
|
||||||
_ = writer.WriteField("masterCpu", strconv.FormatUint(req.MasterCPU, 10))
|
|
||||||
}
|
|
||||||
if req.MasterNum != 0 {
|
|
||||||
_ = writer.WriteField("masterNum", strconv.FormatUint(req.MasterNum, 10))
|
|
||||||
}
|
|
||||||
if req.MasterRAM != 0 {
|
|
||||||
_ = writer.WriteField("masterRam", strconv.FormatUint(req.MasterRAM, 10))
|
|
||||||
}
|
|
||||||
if req.MasterDisk != 0 {
|
|
||||||
_ = writer.WriteField("masterDisk", strconv.FormatUint(req.MasterDisk, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerCPU != 0 {
|
|
||||||
_ = writer.WriteField("workerCpu", strconv.FormatUint(req.WorkerCPU, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerNum != 0 {
|
|
||||||
_ = writer.WriteField("workerNum", strconv.FormatUint(req.WorkerNum, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerRAM != 0 {
|
|
||||||
_ = writer.WriteField("workerRam", strconv.FormatUint(req.WorkerRAM, 10))
|
|
||||||
}
|
|
||||||
if req.WorkerDisk != 0 {
|
|
||||||
_ = writer.WriteField("workerDisk", strconv.FormatUint(req.WorkerDisk, 10))
|
|
||||||
}
|
|
||||||
if req.ExtNetID != 0 {
|
|
||||||
_ = writer.WriteField("extnetId", strconv.FormatUint(req.ExtNetID, 10))
|
|
||||||
}
|
|
||||||
if req.VinsId != 0 {
|
|
||||||
_ = writer.WriteField("vinsId", strconv.FormatUint(req.VinsId, 10))
|
|
||||||
}
|
|
||||||
if !req.WithLB {
|
|
||||||
_ = writer.WriteField("withLB", strconv.FormatBool(req.WithLB))
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("highlyAvailableLB", strconv.FormatBool(req.HighlyAvailable))
|
|
||||||
|
|
||||||
if req.AdditionalSANs != nil {
|
|
||||||
for _, v := range req.AdditionalSANs {
|
|
||||||
_ = writer.WriteField("additionalSANs", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if req.InitConfiguration != "" {
|
|
||||||
_ = writer.WriteField("initConfiguration", req.InitConfiguration)
|
|
||||||
}
|
|
||||||
if req.ClusterConfiguration != "" {
|
|
||||||
_ = writer.WriteField("clusterConfiguration", req.ClusterConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeletConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeletConfiguration", req.KubeletConfiguration)
|
|
||||||
}
|
|
||||||
if req.KubeProxyConfiguration != "" {
|
|
||||||
_ = writer.WriteField("kubeProxyConfiguration", req.KubeProxyConfiguration)
|
|
||||||
}
|
|
||||||
if req.JoinConfiguration != "" {
|
|
||||||
_ = writer.WriteField("joinConfiguration", req.JoinConfiguration)
|
|
||||||
}
|
|
||||||
if req.Description != "" {
|
|
||||||
_ = writer.WriteField("desc", req.Description)
|
|
||||||
}
|
|
||||||
if req.UserData != "" {
|
|
||||||
_ = writer.WriteField("userData", req.UserData)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
|
|
||||||
|
|
||||||
_ = writer.WriteField("authkey", token)
|
|
||||||
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
|
|
||||||
writer.Close()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ type RecordBasicService struct {
|
|||||||
// Main information about Compute
|
// Main information about Compute
|
||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
// Architecture
|
// Architecture
|
||||||
Architecture string `json:"arch"`
|
Architecture string `json:"arch"`
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleAdd add affinity rule
|
// AffinityRuleAdd add affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleRemove remove affinity rule
|
// AffinityRuleRemove remove affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AntiAffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleAdd add anti affinity rule
|
// AntiAffinityRuleAdd add anti affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AntiAffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleRemove remove anti affinity rule
|
// AntiAffinityRuleRemove remove anti affinity rule
|
||||||
|
|||||||
@@ -380,6 +380,9 @@ type RecordCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NeedReboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
// Natable VINS ID
|
// Natable VINS ID
|
||||||
NatableVINSID uint64 `json:"natableVinsId"`
|
NatableVINSID uint64 `json:"natableVinsId"`
|
||||||
|
|
||||||
@@ -857,6 +860,9 @@ type ItemCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NeedReboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
// Pinned or not
|
// Pinned or not
|
||||||
Pinned bool `json:"pinned"`
|
Pinned bool `json:"pinned"`
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type GetRequest struct {
|
|||||||
|
|
||||||
// If set to False returns only images in status CREATED
|
// If set to False returns only images in status CREATED
|
||||||
// Required: false
|
// Required: false
|
||||||
ShowAll bool `url:"show_all,omitempty" json:"show_all,omitempty"`
|
ShowAll bool `url:"showAll,omitempty" json:"showAll,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get gets image by ID.
|
// Get gets image by ID.
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
type ListRequest struct {
|
type ListRequest struct {
|
||||||
// Find by ID
|
// Find by ID
|
||||||
// Required: false
|
// Required: false
|
||||||
ByID uint64 `url:"id,omitempty" json:"id,omitempty"`
|
ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`
|
||||||
|
|
||||||
// Find by name
|
// Find by name
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ type CreateRequest struct {
|
|||||||
WorkerGroupName string `url:"workerGroupName" json:"workerGroupName" validate:"required,workerGroupName"`
|
WorkerGroupName string `url:"workerGroupName" json:"workerGroupName" validate:"required,workerGroupName"`
|
||||||
|
|
||||||
// Network plugin
|
// Network plugin
|
||||||
// Must be one of these values: flannel, weawenet, calico
|
// Must be one of these values: flannel, weavenet, calico
|
||||||
// Required: true
|
// Required: true
|
||||||
NetworkPlugin string `url:"networkPlugin" json:"networkPlugin" validate:"required,networkPlugin"`
|
NetworkPlugin string `url:"networkPlugin" json:"networkPlugin" validate:"required,networkPlugin"`
|
||||||
|
|
||||||
@@ -202,7 +202,7 @@ func (k8s K8S) Create(ctx context.Context, req CreateRequest) (string, error) {
|
|||||||
|
|
||||||
url := "/cloudapi/k8s/create"
|
url := "/cloudapi/k8s/create"
|
||||||
|
|
||||||
res, err := k8s.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k8s.client.DecortApiCallMP(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type DeleteRequest struct {
|
|||||||
// True if cluster is destroyed permanently.
|
// True if cluster is destroyed permanently.
|
||||||
// Otherwise it can be restored from Recycle Bin
|
// Otherwise it can be restored from Recycle Bin
|
||||||
// Required: true
|
// Required: true
|
||||||
Permanently bool `url:"permanently" json:"permanently" validate:"required"`
|
Permanently bool `url:"permanently" json:"permanently"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes kubernetes cluster
|
// Delete deletes kubernetes cluster
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// Find by account ID
|
// Find by account ID
|
||||||
// Required: false
|
// Required: false
|
||||||
AccountID uint64 `url:"accountID,omitempty" json:"accountID,omitempty"`
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
|
|
||||||
// Find by resource group ID
|
// Find by resource group ID
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ type RestartRequest struct {
|
|||||||
// ID of the load balancer instance to restart
|
// ID of the load balancer instance to restart
|
||||||
// Required: true
|
// Required: true
|
||||||
LBID uint64 `url:"lbId" json:"lbId" validate:"required"`
|
LBID uint64 `url:"lbId" json:"lbId" validate:"required"`
|
||||||
|
|
||||||
|
// restart secondary and primary nodes sequentially in HA mode
|
||||||
|
// Default is true
|
||||||
|
// Required: false
|
||||||
|
Safe bool `url:"safe" json:"safe"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restart restarts specified load balancer instance
|
// Restart restarts specified load balancer instance
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ package locations
|
|||||||
|
|
||||||
// Main information about locations
|
// Main information about locations
|
||||||
type ItemLocation struct {
|
type ItemLocation struct {
|
||||||
|
// AuthBroker
|
||||||
|
AuthBroker []string `json:"authBroker"`
|
||||||
|
|
||||||
// Grid ID
|
// Grid ID
|
||||||
GID uint64 `json:"gid"`
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
|
|||||||
@@ -55,10 +55,12 @@ func (lrc ListResourceConsumption) IDs() []uint64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// IDs gets array of ResourceGroupIDs from ListAffinityGroup struct
|
// IDs gets array of ResourceGroupIDs from ListAffinityGroup struct
|
||||||
func (lag ListAffinityGroup) IDs() []uint64 {
|
func (lag ListAffinityGroups) IDs() []uint64 {
|
||||||
res := make([]uint64, 0, len(lag))
|
res := make([]uint64, 0, len(lag.Data))
|
||||||
for _, ag := range lag {
|
for _, ag := range lag.Data {
|
||||||
res = append(res, ag.ID)
|
for _, v := range ag {
|
||||||
|
res = append(res, v...)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -331,19 +331,10 @@ type ItemAffinityGroupComputes struct {
|
|||||||
// List of affinity groups
|
// List of affinity groups
|
||||||
type ListAffinityGroupsComputes []ItemAffinityGroupComputes
|
type ListAffinityGroupsComputes []ItemAffinityGroupComputes
|
||||||
|
|
||||||
// Main information about
|
|
||||||
type ItemAffinityGroup struct {
|
|
||||||
ID uint64 `json:"id"`
|
|
||||||
NodeID uint64 `json:"node_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// List of affinity group
|
|
||||||
type ListAffinityGroup []ItemAffinityGroup
|
|
||||||
|
|
||||||
// List of affinity groups
|
// List of affinity groups
|
||||||
type ListAffinityGroups struct {
|
type ListAffinityGroups struct {
|
||||||
// Data
|
// Data
|
||||||
Data []map[string]ListAffinityGroup `json:"data"`
|
Data []map[string][]uint64 `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
@@ -486,6 +477,9 @@ type RecordLoadBalancer struct {
|
|||||||
// Access Control List
|
// Access Control List
|
||||||
ACL interface{} `json:"acl"`
|
ACL interface{} `json:"acl"`
|
||||||
|
|
||||||
|
// BackendHAIP
|
||||||
|
BackendHAIP string `json:"backendHAIP"`
|
||||||
|
|
||||||
// List of Backends
|
// List of Backends
|
||||||
Backends ListBackends `json:"backends"`
|
Backends ListBackends `json:"backends"`
|
||||||
|
|
||||||
@@ -510,6 +504,9 @@ type RecordLoadBalancer struct {
|
|||||||
// External network ID
|
// External network ID
|
||||||
ExtNetID uint64 `json:"extnetId"`
|
ExtNetID uint64 `json:"extnetId"`
|
||||||
|
|
||||||
|
// FrontendHAIP
|
||||||
|
FrontendHAIP string `json:"frontendHAIP"`
|
||||||
|
|
||||||
// List of frontends
|
// List of frontends
|
||||||
Frontends ListFrontends `json:"frontends"`
|
Frontends ListFrontends `json:"frontends"`
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,8 @@ type CreateInRGRequest struct {
|
|||||||
|
|
||||||
// External network ID
|
// External network ID
|
||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
// -1 - not connect to extnet, 0 - auto select, 1+ - extnet ID
|
||||||
|
ExtNetID int64 `url:"extNetId" json:"extNetId"`
|
||||||
|
|
||||||
// External IP, related only for extNetId >= 0
|
// External IP, related only for extNetId >= 0
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
10
pkg/cloudbroker/audit.go
Normal file
10
pkg/cloudbroker/audit.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package cloudbroker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/audit"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Accessing the Stack method group
|
||||||
|
func (cb *CloudBroker) Audit() *audit.Audit {
|
||||||
|
return audit.New(cb.client)
|
||||||
|
}
|
||||||
15
pkg/cloudbroker/audit/audit.go
Normal file
15
pkg/cloudbroker/audit/audit.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
|
||||||
|
// Structure for creating request to audit
|
||||||
|
type Audit struct {
|
||||||
|
client interfaces.Caller
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builder for audit endpoint
|
||||||
|
func New(client interfaces.Caller) *Audit {
|
||||||
|
return &Audit{
|
||||||
|
client: client,
|
||||||
|
}
|
||||||
|
}
|
||||||
46
pkg/cloudbroker/audit/get.go
Normal file
46
pkg/cloudbroker/audit/get.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetRequest struct to get information about account
|
||||||
|
type GetRequest struct {
|
||||||
|
// Audit GUID
|
||||||
|
// Required: true
|
||||||
|
AuditGuid string `url:"auditGuid" json:"auditGuid" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gets information about audit as a RecordAudit struct
|
||||||
|
func (a Audit) Get(ctx context.Context, req GetRequest) (*RecordAudit, error) {
|
||||||
|
res, err := a.GetRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := RecordAudit{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &info)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRaw gets information about audit as an array of bytes
|
||||||
|
func (a Audit) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudbroker/audit/get"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
46
pkg/cloudbroker/audit/linked_jobs.go
Normal file
46
pkg/cloudbroker/audit/linked_jobs.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LinkedJobsRequest struct to get information about jobs linked with Audit
|
||||||
|
type LinkedJobsRequest struct {
|
||||||
|
// Audit GUID
|
||||||
|
// Required: true
|
||||||
|
AuditGuid string `url:"auditGuid" json:"auditGuid" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LinkedJobs gets information about Linked Jobs as a ListLinkedJobs struct
|
||||||
|
func (a Audit) LinkedJobs(ctx context.Context, req LinkedJobsRequest) (*ListLinkedJobs, error) {
|
||||||
|
res, err := a.GetRawLinkedJobs(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := ListLinkedJobs{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &info)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRawLinkedJobs gets information about Linked Jobs as an array of bytes
|
||||||
|
func (a Audit) GetRawLinkedJobs(ctx context.Context, req LinkedJobsRequest) ([]byte, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudbroker/audit/linkedJobs"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
64
pkg/cloudbroker/audit/list.go
Normal file
64
pkg/cloudbroker/audit/list.go
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListRequest struct to give list of account audits
|
||||||
|
type ListRequest struct {
|
||||||
|
|
||||||
|
// Find all audits after point in time (unixtime)
|
||||||
|
// Required: false
|
||||||
|
TimestampAt uint64 `url:"timestampAt,omitempty" json:"timestampAt,omitempty"`
|
||||||
|
|
||||||
|
// Find all audits before point in time (unixtime)
|
||||||
|
// Required: false
|
||||||
|
TimestampTo uint64 `url:"timestampTo,omitempty" json:"timestampTo,omitempty"`
|
||||||
|
|
||||||
|
// Find by user (Mongo RegExp supported)
|
||||||
|
// Required: false
|
||||||
|
User string `url:"user,omitempty" json:"user,omitempty"`
|
||||||
|
|
||||||
|
// Find by api endpoint (Mongo RegExp supported)
|
||||||
|
// Required: false
|
||||||
|
Call string `url:"call,omitempty" json:"call,omitempty"`
|
||||||
|
|
||||||
|
// Find by HTTP status code
|
||||||
|
// Required: false
|
||||||
|
StatusCode uint64 `url:"statusCode,omitempty" json:"statusCode,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 audit records for the specified account object
|
||||||
|
func (a Audit) List(ctx context.Context, req ListRequest) (*ListAudits, error) {
|
||||||
|
res, err := a.ListRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
list := ListAudits{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &list)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &list, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRaw gets list of audit records an array of bytes
|
||||||
|
func (a Audit) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
url := "/cloudbroker/audit/list"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
102
pkg/cloudbroker/audit/models.go
Normal file
102
pkg/cloudbroker/audit/models.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
// Main info about audit
|
||||||
|
type ItemAudit struct {
|
||||||
|
// Call
|
||||||
|
Call string `json:"call"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
|
||||||
|
// Response time
|
||||||
|
ResponseTime float64 `json:"responsetime"`
|
||||||
|
|
||||||
|
// Status code
|
||||||
|
StatusCode uint64 `json:"statuscode"`
|
||||||
|
|
||||||
|
// Timestamp
|
||||||
|
Timestamp float64 `json:"timestamp"`
|
||||||
|
|
||||||
|
// User
|
||||||
|
User string `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of audits
|
||||||
|
type ListAudits struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemAudit `json:"data"`
|
||||||
|
|
||||||
|
// EntryCount
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main info about audit
|
||||||
|
type RecordAudit struct {
|
||||||
|
|
||||||
|
// Apitask
|
||||||
|
Apitask string `json:"apitask"`
|
||||||
|
|
||||||
|
// Arguments
|
||||||
|
Arguments string `json:"args"`
|
||||||
|
|
||||||
|
// Call
|
||||||
|
Call string `json:"call"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
|
||||||
|
// Kwargs
|
||||||
|
Kwargs string `json:"kwargs"`
|
||||||
|
|
||||||
|
// RemoteAddr
|
||||||
|
RemoteAddr string `json:"remote_addr"`
|
||||||
|
|
||||||
|
// Response time
|
||||||
|
ResponseTime float64 `json:"responsetime"`
|
||||||
|
|
||||||
|
// Result
|
||||||
|
Result string `json:"result"`
|
||||||
|
|
||||||
|
// Status code
|
||||||
|
StatusCode uint64 `json:"statuscode"`
|
||||||
|
|
||||||
|
// Tags
|
||||||
|
Tags string `json:"tags"`
|
||||||
|
|
||||||
|
// Timestamp
|
||||||
|
Timestamp float64 `json:"timestamp"`
|
||||||
|
|
||||||
|
// TimestampEnd
|
||||||
|
TimestampEnd float64 `json:"timestampEnd"`
|
||||||
|
|
||||||
|
// User
|
||||||
|
User string `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of Linked Jobs
|
||||||
|
type ListLinkedJobs []ItemLinkedJobs
|
||||||
|
|
||||||
|
// Main info about Linked Jobs
|
||||||
|
type ItemLinkedJobs struct {
|
||||||
|
|
||||||
|
// CMD
|
||||||
|
CMD string `json:"cmd"`
|
||||||
|
|
||||||
|
// NID
|
||||||
|
NID uint64 `json:"nid"`
|
||||||
|
|
||||||
|
// state
|
||||||
|
State string `json:"state"`
|
||||||
|
|
||||||
|
// TimeCreate
|
||||||
|
TimeCreate uint64 `json:"timeCreate"`
|
||||||
|
|
||||||
|
// TimeStart
|
||||||
|
TimeStart uint64 `json:"timeStart"`
|
||||||
|
|
||||||
|
// TimeStop
|
||||||
|
TimeStop uint64 `json:"timeStop"`
|
||||||
|
|
||||||
|
// Timeout
|
||||||
|
Timeout uint64 `json:"timeout"`
|
||||||
|
}
|
||||||
@@ -40,8 +40,8 @@ type AffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleAdd adds affinity rule
|
// AffinityRuleAdd adds affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleRemove remove affinity rule
|
// AffinityRuleRemove remove affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AntiAffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleAdd adds anti affinity rule
|
// AntiAffinityRuleAdd adds anti affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ type AntiAffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleRemove removes anti affinity rule
|
// AntiAffinityRuleRemove removes anti affinity rule
|
||||||
|
|||||||
38
pkg/cloudbroker/compute/delete_custom_fields.go
Normal file
38
pkg/cloudbroker/compute/delete_custom_fields.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeleteCustomFieldsRequest struct to delete compute's custom 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 {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudbroker/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
|
||||||
|
}
|
||||||
@@ -20,8 +20,8 @@ func (lid ListInfoDisks) IDs() []uint64 {
|
|||||||
|
|
||||||
// IDs gets array of PFWsIDs from ListPFW struct
|
// IDs gets array of PFWsIDs from ListPFW struct
|
||||||
func (lp ListPFW) IDs() []uint64 {
|
func (lp ListPFW) IDs() []uint64 {
|
||||||
res := make([]uint64, 0, len(lp))
|
res := make([]uint64, 0, len(lp.Data))
|
||||||
for _, p := range lp {
|
for _, p := range lp.Data {
|
||||||
res = append(res, p.ID)
|
res = append(res, p.ID)
|
||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
@@ -43,4 +43,4 @@ func (lpd ListPCIDevices) IDs() []uint64 {
|
|||||||
res = append(res, pd.ID)
|
res = append(res, pd.ID)
|
||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,14 @@ 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"`
|
||||||
|
}
|
||||||
|
|
||||||
// ACL information
|
// ACL information
|
||||||
type ItemACL struct {
|
type ItemACL struct {
|
||||||
// Explicit
|
// Explicit
|
||||||
@@ -75,6 +83,15 @@ type ItemSnapshot struct {
|
|||||||
// List of snapshots
|
// List of snapshots
|
||||||
type ListSnapshots []ItemSnapshot
|
type ListSnapshots []ItemSnapshot
|
||||||
|
|
||||||
|
// List of snapshots
|
||||||
|
type ListSnapShot struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemSnapshot `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about snapshot usage
|
// Main information about snapshot usage
|
||||||
type ItemSnapshotUsage struct {
|
type ItemSnapshotUsage struct {
|
||||||
// Count
|
// Count
|
||||||
@@ -232,7 +249,13 @@ type ItemPFW struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List port forwards
|
// List port forwards
|
||||||
type ListPFW []ItemPFW
|
type ListPFW struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemPFW `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about rule
|
// Main information about rule
|
||||||
type ItemRule struct {
|
type ItemRule struct {
|
||||||
@@ -569,6 +592,9 @@ type InfoCompute struct {
|
|||||||
// Boot disk size
|
// Boot disk size
|
||||||
BootDiskSize uint64 `json:"bootdiskSize"`
|
BootDiskSize uint64 `json:"bootdiskSize"`
|
||||||
|
|
||||||
|
// cd Image Id
|
||||||
|
CdImageId uint64 `json:"cdImageId"`
|
||||||
|
|
||||||
// Clone reference
|
// Clone reference
|
||||||
CloneReference uint64 `json:"cloneReference"`
|
CloneReference uint64 `json:"cloneReference"`
|
||||||
|
|
||||||
@@ -638,6 +664,9 @@ type InfoCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Need reboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
// List OS users
|
// List OS users
|
||||||
OSUsers ListOSUsers `json:"osUsers"`
|
OSUsers ListOSUsers `json:"osUsers"`
|
||||||
|
|
||||||
@@ -721,7 +750,7 @@ type RecordCompute struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Information about of disk IDs
|
// Information about of disk IDs
|
||||||
type ListInfoDisks []InfoDisk
|
type ListInfoDisks []InfoDisk
|
||||||
|
|
||||||
// Main information about compute for list
|
// Main information about compute for list
|
||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
@@ -732,7 +761,7 @@ type ItemCompute struct {
|
|||||||
InfoCompute
|
InfoCompute
|
||||||
|
|
||||||
// Total disk size
|
// Total disk size
|
||||||
TotalDiskSize uint64 `json:"totalDiskSize"`
|
TotalDiskSize uint64 `json:"totalDisksSize"`
|
||||||
|
|
||||||
// VINS connected
|
// VINS connected
|
||||||
VINSConnected uint64 `json:"vinsConnected"`
|
VINSConnected uint64 `json:"vinsConnected"`
|
||||||
|
|||||||
@@ -20,7 +20,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) (ListPFW, error) {
|
func (c Compute) PFWList(ctx context.Context, req PFWListRequest) (*ListPFW, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -40,5 +40,5 @@ func (c Compute) PFWList(ctx context.Context, req PFWListRequest) (ListPFW, erro
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type SnapshotListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SnapshotList gets list of compute snapshots
|
// SnapshotList gets list of compute snapshots
|
||||||
func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (ListSnapshots, error) {
|
func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (*ListSnapShot, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -29,12 +29,12 @@ func (c Compute) SnapshotList(ctx context.Context, req SnapshotListRequest) (Lis
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := ListSnapshots{}
|
list := ListSnapShot{}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -29,7 +29,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 {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package grid
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
@@ -38,7 +39,7 @@ func (g Grid) GetDiagnosisGET(ctx context.Context, req GetDiagnosisRequest) (str
|
|||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudbroker/grid/getDiagnosis"
|
url := fmt.Sprintf("/cloudbroker/grid/getDiagnosis/?gid=%d", req.GID)
|
||||||
|
|
||||||
res, err := g.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
res, err := g.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -67,6 +67,9 @@ type DiskUsage struct {
|
|||||||
|
|
||||||
// Detailed information about grid
|
// Detailed information about grid
|
||||||
type RecordGrid struct {
|
type RecordGrid struct {
|
||||||
|
// AuthBroker
|
||||||
|
AuthBroker []interface{} `json:"authBroker"`
|
||||||
|
|
||||||
// Flag
|
// Flag
|
||||||
Flag string `json:"flag"`
|
Flag string `json:"flag"`
|
||||||
|
|
||||||
@@ -91,6 +94,9 @@ type ItemGridList struct {
|
|||||||
// Resource information
|
// Resource information
|
||||||
Resources Resources `json:"Resources"`
|
Resources Resources `json:"Resources"`
|
||||||
|
|
||||||
|
// AuthBroker
|
||||||
|
AuthBroker []interface{} `json:"authBroker"`
|
||||||
|
|
||||||
// Flag
|
// Flag
|
||||||
Flag string `json:"flag"`
|
Flag string `json:"flag"`
|
||||||
|
|
||||||
|
|||||||
36
pkg/cloudbroker/k8ci/access_add.go
Normal file
36
pkg/cloudbroker/k8ci/access_add.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package k8ci
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AccessAddRequest struct for adding permission to access to account for a k8ci
|
||||||
|
type AccessAddRequest struct {
|
||||||
|
// ID of the K8 catalog item to add access for
|
||||||
|
// Required: true
|
||||||
|
K8CIID uint64 `url:"k8ciId" json:"k8ciId" validate:"required"`
|
||||||
|
|
||||||
|
// Account ID to add to the sharedWith access list
|
||||||
|
// Required: true
|
||||||
|
AccountId uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add accountId to sharedWith access list for k8ci.
|
||||||
|
func (k K8CI) AccessAdd(ctx context.Context, req AccessAddRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudbroker/k8ci/accessAdd"
|
||||||
|
|
||||||
|
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(res), nil
|
||||||
|
}
|
||||||
36
pkg/cloudbroker/k8ci/access_remove.go
Normal file
36
pkg/cloudbroker/k8ci/access_remove.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package k8ci
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AccessRemoveRequest struct for removing permission to access to account for a k8ci
|
||||||
|
type AccessRemoveRequest struct {
|
||||||
|
// ID of the K8 catalog item to remove access for
|
||||||
|
// Required: true
|
||||||
|
K8CIID uint64 `url:"k8ciId" json:"k8ciId" validate:"required"`
|
||||||
|
|
||||||
|
// Account ID to be removed from the sharedWith access list
|
||||||
|
// Required: true
|
||||||
|
AccountId uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove accountId from sharedWith access list for k8ci.
|
||||||
|
func (k K8CI) AccessRemove(ctx context.Context, req AccessRemoveRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudbroker/k8ci/accessRemove"
|
||||||
|
|
||||||
|
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(res), nil
|
||||||
|
}
|
||||||
@@ -60,7 +60,7 @@ type CreateRequest struct {
|
|||||||
MaxWorkerCount uint64 `url:"maxWorkerCount" json:"maxWorkerCount" validate:"required"`
|
MaxWorkerCount uint64 `url:"maxWorkerCount" json:"maxWorkerCount" validate:"required"`
|
||||||
|
|
||||||
// Network plugins
|
// Network plugins
|
||||||
// Values of slice must be flannel, weawenet or calico
|
// Values of slice must be flannel, weavenet or calico
|
||||||
//Required: true
|
//Required: true
|
||||||
NetworkPlugins []string `url:"networkPlugins" json:"networkPlugins" validate:"required,networkPlugins"`
|
NetworkPlugins []string `url:"networkPlugins" json:"networkPlugins" validate:"required,networkPlugins"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type DeleteRequest struct {
|
|||||||
|
|
||||||
// Delete permanently or not
|
// Delete permanently or not
|
||||||
// Required: false
|
// Required: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently" json:"permanently"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes K8CI by ID
|
// Delete deletes K8CI by ID
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ type CreateRequest struct {
|
|||||||
WorkerGroupName string `url:"workerGroupName" json:"workerGroupName" validate:"required,workerGroupName"`
|
WorkerGroupName string `url:"workerGroupName" json:"workerGroupName" validate:"required,workerGroupName"`
|
||||||
|
|
||||||
// Network plugin
|
// Network plugin
|
||||||
// Must be one of these values: flunnel, weawenet, calico
|
// Must be one of these values: flunnel, weavenet, calico
|
||||||
// Required: true
|
// Required: true
|
||||||
NetworkPlugin string `url:"networkPlugin" json:"networkPlugin" validate:"required,networkPlugin"`
|
NetworkPlugin string `url:"networkPlugin" json:"networkPlugin" validate:"required,networkPlugin"`
|
||||||
|
|
||||||
@@ -204,7 +204,7 @@ func (k K8S) Create(ctx context.Context, req CreateRequest) (string, error) {
|
|||||||
|
|
||||||
url := "/cloudbroker/k8s/create"
|
url := "/cloudbroker/k8s/create"
|
||||||
|
|
||||||
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k.client.DecortApiCallMP(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type DeleteRequest struct {
|
|||||||
// True if cluster is destroyed permanently.
|
// True if cluster is destroyed permanently.
|
||||||
// Otherwise it can be restored from recycle bin
|
// Otherwise it can be restored from recycle bin
|
||||||
// Required: false
|
// Required: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently" json:"permanently"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes kubernetes cluster
|
// Delete deletes kubernetes cluster
|
||||||
|
|||||||
@@ -29,10 +29,10 @@ func (l LB) HighlyAvailable(ctx context.Context, req HighlyAvailableRequest) (bo
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := strconv.ParseBool(string(res))
|
result, err := strconv.ParseUint(string(res), 10, 64)
|
||||||
if err != nil {
|
if err != nil || result != req.LBID {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ type AffinityGroupsListRequest struct {
|
|||||||
// Resource group ID
|
// Resource group ID
|
||||||
// Required: true
|
// Required: true
|
||||||
RGID uint64 `url:"rgId" json:"rgId" validate:"required"`
|
RGID uint64 `url:"rgId" json:"rgId" 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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityGroupsList gets all currently defined affinity groups in this resource group with compute IDs
|
// AffinityGroupsList gets all currently defined affinity groups in this resource group with compute IDs
|
||||||
|
|||||||
@@ -53,3 +53,12 @@ func (lpfw ListPFW) IDs() []uint64 {
|
|||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IDs gets array of ComputeIDs from ListAffinityGroupItems struct
|
||||||
|
func (lag ListAffinityGroupItems) IDs() []uint64 {
|
||||||
|
res := make([]uint64, 0, len(lag))
|
||||||
|
for _, ag := range lag {
|
||||||
|
res = append(res, ag.ID)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Find by status lock
|
||||||
|
// Required: false
|
||||||
|
LockStatus string `url:"lockStatus,omitempty" json:"lockStatus,omitempty"`
|
||||||
|
|
||||||
// Included deleted resource groups
|
// Included deleted resource groups
|
||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|||||||
@@ -65,6 +65,10 @@ type ItemResourceConsumption struct {
|
|||||||
// Reserved information
|
// Reserved information
|
||||||
Reserved Reservation `json:"Reserved"`
|
Reserved Reservation `json:"Reserved"`
|
||||||
|
|
||||||
|
// Resource limits
|
||||||
|
ResourceLimits ResourceLimits `json:"resourceLimits"`
|
||||||
|
|
||||||
|
// Resource group ID
|
||||||
RGID uint64 `json:"rgid"`
|
RGID uint64 `json:"rgid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -603,6 +607,9 @@ type ItemLB struct {
|
|||||||
// List ACL
|
// List ACL
|
||||||
ACL ListACL `json:"acl"`
|
ACL ListACL `json:"acl"`
|
||||||
|
|
||||||
|
// BackendHAIP
|
||||||
|
BackendHAIP string `json:"backendHAIP"`
|
||||||
|
|
||||||
// List backends
|
// List backends
|
||||||
Backends ListBackends `json:"backends"`
|
Backends ListBackends `json:"backends"`
|
||||||
|
|
||||||
@@ -627,6 +634,9 @@ type ItemLB struct {
|
|||||||
// External network ID
|
// External network ID
|
||||||
ExtNetID uint64 `json:"extnetId"`
|
ExtNetID uint64 `json:"extnetId"`
|
||||||
|
|
||||||
|
// FrontendHAIP
|
||||||
|
FrontendHAIP string `json:"frontendHAIP"`
|
||||||
|
|
||||||
// List of frontends
|
// List of frontends
|
||||||
Frontends ListFrontends `json:"frontends"`
|
Frontends ListFrontends `json:"frontends"`
|
||||||
|
|
||||||
@@ -687,8 +697,15 @@ type ListLB struct {
|
|||||||
|
|
||||||
type ListAffinityGroup struct {
|
type ListAffinityGroup struct {
|
||||||
// Data
|
// Data
|
||||||
Data map[string][]uint64 `json:"data"`
|
Data []map[string]ListAffinityGroupItems `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ListAffinityGroupItems []ItemAffinityGroup
|
||||||
|
|
||||||
|
type ItemAffinityGroup struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
NodeID uint64 `json:"node_id"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Lists all the stack.
|
|
||||||
package stack
|
package stack
|
||||||
|
|
||||||
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
|||||||
@@ -25,7 +25,8 @@ type CreateInRGRequest struct {
|
|||||||
|
|
||||||
// External network ID
|
// External network ID
|
||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
// -1 - not connect to extnet, 0 - auto select, 1+ - extnet ID
|
||||||
|
ExtNetID int64 `url:"extNetId" json:"extNetId"`
|
||||||
|
|
||||||
// External IP, related only for extNetId >= 0
|
// External IP, related only for extNetId >= 0
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -6,7 +6,16 @@
|
|||||||
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
||||||
"decortUrl": "https://delta.qa.loc",
|
"decortUrl": "https://delta.qa.loc",
|
||||||
"domain": "dynamix",
|
"domain": "dynamix",
|
||||||
|
"token": {
|
||||||
|
"access_token": "string_token",
|
||||||
|
"token_type": "bearer",
|
||||||
|
"refresh_token": "string_refresh_token",
|
||||||
|
"expiry": "2023-11-24T12:40:27.954150524+03:00"
|
||||||
|
},
|
||||||
"retries": 5,
|
"retries": 5,
|
||||||
|
"sslSkipVerify": true,
|
||||||
"timeout": "5m",
|
"timeout": "5m",
|
||||||
"sslSkipVerify": false
|
"path_cfg": "config",
|
||||||
|
"path_token": "token",
|
||||||
|
"timeToRefresh": 5
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,15 @@ appId: <APP_ID>
|
|||||||
appSecret: <APP_SECRET>
|
appSecret: <APP_SECRET>
|
||||||
ssoUrl: https://bvs-delta.qa.loc:8443
|
ssoUrl: https://bvs-delta.qa.loc:8443
|
||||||
decortUrl: https://delta.qa.loc
|
decortUrl: https://delta.qa.loc
|
||||||
domain: dynamix,
|
domain: dynamix
|
||||||
|
token":
|
||||||
|
access_token: string_token
|
||||||
|
token_type: bearer
|
||||||
|
refresh_token: string_refresh_token
|
||||||
|
expiry: 2023-11-24T12:40:27.954150524+03:00
|
||||||
retries: 5
|
retries: 5
|
||||||
|
sslSkipVerify: true
|
||||||
timeout: 5m
|
timeout: 5m
|
||||||
sslSkipVerify: false
|
path_cfg: config
|
||||||
|
path_token: token
|
||||||
|
timeToRefresh: 5
|
||||||
|
|||||||
Reference in New Issue
Block a user