Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e7c968797b | |||
| bc264c4d90 | |||
| d137c7507a | |||
| 55027a1605 | |||
| de9cca4053 | |||
| 83bf1fb1fa | |||
| 16cad7a3e7 | |||
| 96273d2a12 | |||
| d4065938ac | |||
| cd741b7f11 | |||
| a85ad3acd5 | |||
| 823dfb49bc | |||
| e6440bc4a3 |
199
CHANGELOG.md
199
CHANGELOG.md
@@ -1,4 +1,197 @@
|
|||||||
## Version 1.6.11
|
## Version 1.8.0
|
||||||
|
|
||||||
## Bugfix
|
### Feature
|
||||||
- Remove tag "required" from field Value in AffinityRuleAddRequest, AntiAffinityRuleAddRequest, AffinityRuleRemoveRequest AntiAffinityRuleRemoveRequest in cloudapi/compute and cloudbroker/compute
|
|
||||||
|
#### account:
|
||||||
|
- Add endpoints GrantAccessTemplates, ListAvailableTemplates, RevokeAccessTemplates in cloudbroker/account
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add ComputeFeatures field to RecordAccount and ItemAccount models in cloudapi/account
|
||||||
|
- Add ComputeFeatures field to InfoAccount and CreateRequest model in cloudbroker/account
|
||||||
|
- Add UpdateComputeFeatures endpoint in cloudbroker/account
|
||||||
|
- Add ExtnetId, FreeIPs fields to model ItemVINS in cloudapi/account and cloudbroker/account
|
||||||
|
|
||||||
|
#### audit:
|
||||||
|
- Add field GUID in model ItemLinkedJobs cloudbroker/audit
|
||||||
|
- Delete field StatusCode in model ListRequest cloudbroker/audit
|
||||||
|
- Add fields MinStatusCode and MaxStatusCode in model ListRequest cloudbroker/audit
|
||||||
|
|
||||||
|
#### bservice:
|
||||||
|
- Add validation of RAM to be divisible by 128 in cloudapi/bservice
|
||||||
|
|
||||||
|
#### compute:
|
||||||
|
- Add field CdImageId in models ItemCompute and RecordCompute in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add fields NatableVINSID, NatableVINSIP, NatableVINSName, NatableVINSNetwork, NatableVINSNetworkName in models RecordCompute in cloudbroker/compute
|
||||||
|
- Set field LocalBasePort in model PFWAddRequest as optional in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add HPBacked, CPUPin, NumaAffinity fields to RecordCompute and InfoCompute models in cloudbroker/compute
|
||||||
|
- Add HPBacked, CPUPin, NumaAffinity fields to RecordCompute and ItemCompute models in cloudapi/compute
|
||||||
|
- Add validation of RAM to be divisible by 128 in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add field NumaNodeId in models RecordCompute and ItemCompute in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add BootDiskSet endpoints in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add endpoints DiskSwitchToReplication, DiskMigrate in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add field Replication in model RecordCompute.Disks.ItemComputeDisk in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add endpoint getCustomFields in cloudbroker/compute
|
||||||
|
- Delete field AffinityLabel in model AffinityRelationsRequest in cloudbroker/compute
|
||||||
|
- Add fields ImageName and VirtualImageName, delete VINSConnected fields in RecordCompute model in cloudbroker/compute
|
||||||
|
- Add fields Enabled and NodeID in ItemInterface model in cloudbroker/compute. Add NodeID field in ItemVNFInterface model in cloudapi/compute
|
||||||
|
|
||||||
|
#### disks:
|
||||||
|
- Add endpoints Replicate, ReplicationResume, ReplicationReverse, ReplicationStart, ReplicationStop, ReplicationStatus, ReplicationSuspend in cloudapi/disks and cloudbroker/disks
|
||||||
|
- Add field Replication in models RecordDisk and ItemDisk in cloudapi/disks and cloudbroker/disks
|
||||||
|
- Add CreateTemplateFromBlank and CreateTemplateFromBlankAsync endpoints in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add fields Page and Size in model SearchRequest in cloudapi/disks
|
||||||
|
- Add FromPlatformDisk and FromPlatformDiskAsync endpoints in cloudapi/disks and cloudbroker/disks
|
||||||
|
|
||||||
|
#### flipgroup:
|
||||||
|
- Add fields ConnId, Status, AccountId to model ListRequest in cloudapi/flipgroup and cloudbroker/flipgroup
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
|
||||||
|
#### grid:
|
||||||
|
- Add endpoints addCustomBackupPath, removeCustomBackupPath, setPasswordPolicy in cloudbroker/grid
|
||||||
|
|
||||||
|
#### image:
|
||||||
|
- Add field CdPresentedTo in model RecordImage in cloudapi/image cloudbroker/image
|
||||||
|
- Set field AccountId in CreateRequest in cloudapi/image as required
|
||||||
|
- Add endpoints GrantAccess, RevokeAccess in cloudbroker/image
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add field NetworkInterfaceNaming in model CreateRequest in cloudapi/image cloudbroker/image, in model EditRequest in cloudbroker/image, in models ItemImage and RecordImage in cloudapi/image and cloudbroker/image
|
||||||
|
- Add validation field NetworkInterfaceNaming in cloudapi/image cloudbroker/image
|
||||||
|
- Delete field GID in model CreateRequest in cloudapi/image
|
||||||
|
- Delete field Meta and Ckey in model and RecordImage in cloudbroker/image
|
||||||
|
- Add model ItemImage in cloudbroker/image
|
||||||
|
|
||||||
|
#### k8s:
|
||||||
|
- Add field LbSysctlParams in model CreateRequest in cloudapi/k8s/create and cloudbroker/k8s/create
|
||||||
|
- Add validation of RAM to be divisible by 128 in cloudapi/k8s and cloudbroker/k8s
|
||||||
|
- Set uint64 as MasterRAM and WorkerRAM types in CreateRequest struct in cloudapi/k8s and cloudbroker/k8s
|
||||||
|
|
||||||
|
#### kvmppc
|
||||||
|
- Add validation of RAM to be divisible by 128 in cloudapi/kvmppc and cloudbroker/kvmppc
|
||||||
|
- Add DataDisks field to CreateRequest and CreateBlankRequest in cloudapi/kvmppc and cloudbroker/kvmppc
|
||||||
|
- Add DataDisks field to MassCreateRequest in cloudbroker/kvmppc
|
||||||
|
|
||||||
|
#### kvmx86
|
||||||
|
- Add validation of RAM to be divisible by 128 in cloudapi/kvmx86 and cloudbroker/kvmx86
|
||||||
|
- Add DataDisks field to CreateRequest and CreateBlankRequest in cloudapi/kvmx86 and cloudbroker/kvmx86
|
||||||
|
- Add DataDisks field to MassCreateRequest in cloudbroker/kvmx86
|
||||||
|
|
||||||
|
#### lb:
|
||||||
|
- Add fields UserManaged, ManagerId, ManagerType, PartK8S in models RecordLB, ItemLBList in cloudapi/lb and cloudbroker/lb
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add field SysctlParams in model CreateRequest in cloudapi/lb/create and cloudbroker/lb/create
|
||||||
|
- Add endpoint update_sysctl_params in cloudapi/lb and cloudbroker/lb
|
||||||
|
|
||||||
|
#### node:
|
||||||
|
- Add ApplyIpmiAction, Consumption, Decommission, Enable, EnableNodes, Get, GetRaw, List, ListRaw, Maintenance, Restrict, SetCoreIsolation, SetHugePages, SetSRIOVStatus, SetVFSNumber and Update endpoints in cloudbroker/node
|
||||||
|
- Add IDs method and Filters methods for ListNodes structure in cloudbroker/node
|
||||||
|
- Add Serialize method for ListNodes, ItemNode and RecordNode structures in cloudbroker/node
|
||||||
|
|
||||||
|
#### pcidevice:
|
||||||
|
- Add List, ListRaw endpoints in cloudapi/pcidevice
|
||||||
|
- Add IDs and Serialize methods for ListPCIDevices structure in cloudapi/pcidevice
|
||||||
|
|
||||||
|
#### rg:
|
||||||
|
- Add ComputeFeatures field to ItemResourceGroup and RecordResourceGroup models in cloudapi/rg
|
||||||
|
- Add ComputeFeatures field to ItemRG and CreateRequest models in cloudbroker/rg
|
||||||
|
- Add UpdateComputeFeatures endpoint in cloudbroker/rg
|
||||||
|
- Add ExtnetId, FreeIPs fields to model ItemVINS in cloudapi/rg and cloudbroker/rg
|
||||||
|
|
||||||
|
#### sep:
|
||||||
|
- Add endpoints addPool, delPool in cloudbroker/sep
|
||||||
|
- Set field Config in CreateRequest as required in cloudbroker/sep
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
|
||||||
|
#### stack:
|
||||||
|
- Add endpoints getLogicalCoresCount, setCpuAllocationRatio, setMemAllocationRatio in cloudbroker/stack
|
||||||
|
|
||||||
|
#### tasks:
|
||||||
|
- Add field TaskId, Status, Completed in model ListRequest in cloudapi/task and cloudbroker/task
|
||||||
|
- Add fields GUID, UpdatedBy in model ItemTask in cloudapi/task and cloudbroker/task
|
||||||
|
- Fix panic in List endpoints in cloudapi/task and cloudbroker/task
|
||||||
|
- Change type field Result from int to interface{} in models RecordAsyncTask, ItemAsyncTask in cloudapi/task and models ItemTask, RecordTask in cloudbroker/task
|
||||||
|
- Add methods ID(), Name(), ToString(), ToMaps() for processing the value of the Result field in model ItemTask in cloudapi/task and cloudbroker/task
|
||||||
|
- Add use case examples for the above methods in README.md
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add fields UpdateTimeAt and UpdateTimeTo in model ListRequest in cloudapi/tasks and cloudbroker/tasks
|
||||||
|
|
||||||
|
#### user:
|
||||||
|
- Add fields Call, StatusCode, TimestampAt, TimestampTo in models GetAuditRequest in cloudbroker/user
|
||||||
|
- Fix return value in GetAudit endpoint in cloudbroker/user
|
||||||
|
- Add model ListAudits and change type field APIAccess in model ItemUser in cloudbroker/user
|
||||||
|
- Add SortBy field for list groups and validation functionality in cloudbroker/user
|
||||||
|
- Add APIList, Authenticate, Brief, GetAudit, GetResourceConsumption, Get, GetRaw, IsValidInviteUserToken, Search, SetData endpoints in cloudapi/user
|
||||||
|
|
||||||
|
#### vfpool:
|
||||||
|
- Add Get, GetRaw, List, ListRaw endpoints in cloudapi/vfpool
|
||||||
|
- Add Create, Delete, Disable, Enable, Get, GetRaw, List, ListRaw, Update endpoints in cloudbroker/vfpool
|
||||||
|
- Add IDs method for ListVFPool, VFSInfoListand in cloudapi/vfpool and cloudbroker/vfpool
|
||||||
|
- Add Filters methods for ListVFPool structure in cloudapi/vfpool and cloudbroker/vfpool
|
||||||
|
- Add Serialize method for ListVFPool, ItemVFPool and RecordVFPool structures in cloudapi/vfpool and cloudbroker/vfpool
|
||||||
|
|
||||||
|
#### vins:
|
||||||
|
- Set field IntPort in model NATRuleAddRequest as optional in cloudapi/vins and cloudbroker/vins
|
||||||
|
- Add SortBy field for list groups and validation functionality
|
||||||
|
- Add ExtnetId, FreeIPs fields to model ItemVINS in cloudapi/vins and cloudbroker/vins
|
||||||
|
- Add DNSList field to models CreateInAccountRequest and CreateInRGRequest in cloudapi/vins and cloudbroker/vins
|
||||||
|
- Add DNSApply endpoints in cloudapi/vins and cloudbroker/vins
|
||||||
|
- Add field NodeID in model RecordVINS.RecordVNFDev.Interfaces in cloudapi/vins and cloudbroker/vins
|
||||||
|
|
||||||
|
### Bugfix
|
||||||
|
|
||||||
|
#### account:
|
||||||
|
- Fix wrong json, url field AccountID in model SetCPUAllocationParameterRequest in cloudbroker/account
|
||||||
|
- Fix wrong json, url field AccountID in model SetCPUAllocationRatioRequest in cloudbroker/account
|
||||||
|
- Change Start and End fields type from uint64 to float64 in model GetConsumptionRequest in cloudapi/account
|
||||||
|
|
||||||
|
#### apiaccess:
|
||||||
|
- Changed Job and Resmon field types in model CloudBrokerEndpoints in cloudbroker/apiaccess
|
||||||
|
- Add fields Page and Size in model UserListRequest in cloudbroker/apiaccess
|
||||||
|
|
||||||
|
#### bservice:
|
||||||
|
- Fix url for Disable endpoint in cloudapi/bservice
|
||||||
|
|
||||||
|
#### compute:
|
||||||
|
- Fix Entrycount tag in model ListComputes in cloudbroker/compute
|
||||||
|
- Add field Name in model ListPCIDeviceRequest in cloudbroker/compute
|
||||||
|
- Fix type of field Data in model ListPCIDevices in cloudapi/compute
|
||||||
|
- Add model ItemPCIDevice in cloudapi/compute
|
||||||
|
- Fix type of field Data in model ListVGPUs in cloudapi/compute and cloudbroker/compute
|
||||||
|
- Add model ItemVGPU in cloudapi/compute and cloudbroker/compute
|
||||||
|
|
||||||
|
#### disks:
|
||||||
|
- Delete tag required from field Detailed in ListTypesRequest model in cloudapi/disks
|
||||||
|
|
||||||
|
#### grid:
|
||||||
|
- Fix json, url tags in field Name in model RenameRequest in cloudbroker/grid
|
||||||
|
|
||||||
|
#### image:
|
||||||
|
- Fix url for ComputeCIUnset endpoint in cloudbroker/image
|
||||||
|
|
||||||
|
#### k8ci:
|
||||||
|
- Delete omitempty from json, url tags in field Permanently in model DeleteRequest in cloudbroker/k8ci
|
||||||
|
- Fix wrong json, url tags field ByID in model ListDeletedRequest in cloudbroker/k8ci
|
||||||
|
- Fix allowed network plugin value from "weawenet" to "weavenet" in validators for cloudbroker/k8ci
|
||||||
|
|
||||||
|
#### k8s:
|
||||||
|
- Fix allowed network plugin value from "weawenet" to "weavenet" in validators for cloudapi/k8s, cloudbroker/k8s
|
||||||
|
|
||||||
|
#### lb:
|
||||||
|
- Fix wrong json, url tags field AccountID in model ListDeletedRequest in cloudapi/lb
|
||||||
|
- Add field Safe in model RestartRequest in cloudbroker/lb
|
||||||
|
- Fix wrong json, url tags field AccountID in models ListRequest, ListDeletedRequest in cloudbroker/lb
|
||||||
|
- Fix url for Stop endpoint in cloudapi/lb
|
||||||
|
|
||||||
|
#### rg:
|
||||||
|
- Fix wrong json, url field AccountID in model ListLBRequest in cloudapi/rg and cloudbroker/rg
|
||||||
|
- Fix wrong json, url field UniqPools in model CreateRequest in cloudbroker/rg
|
||||||
|
|
||||||
|
#### sep:
|
||||||
|
- Fix wrong json, url tag in field GID in model ListRequest in cloudbroker/sep
|
||||||
|
|
||||||
|
#### user:
|
||||||
|
- Fix wrong json, url field Password in model ItemUser in cloudbroker/user
|
||||||
|
- Change ByID field type from uint64 to string in model ListRequest in cloudbroker/user
|
||||||
|
|
||||||
|
#### vins:
|
||||||
|
- Fix wrong json, url tags in models DefaultQOSUpdateRequest and NetQOSRequest in field IngressBirst in cloudbroker/vins
|
||||||
|
- Fix wrong name field ListNatRule to ListNATRule in cloudbroker/vins
|
||||||
729
README.md
729
README.md
@@ -11,34 +11,64 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
||||||
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
||||||
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
||||||
|
- Версия 1.7.х Decort-SDK соответствует 3.8.9 версии платформы
|
||||||
|
- Версия 1.8.х Decort-SDK соответствует 4.0.0 версии платформы
|
||||||
|
|
||||||
## Оглавление
|
## Оглавление
|
||||||
|
|
||||||
- [Установка](#установка)
|
- [Decort SDK](#decort-sdk)
|
||||||
- [Список API](#список-api)
|
- [Версии](#версии)
|
||||||
- [Cloudapi](#cloudapi)
|
- [Оглавление](#оглавление)
|
||||||
- [Cloudbroker](#cloudbroker)
|
- [Установка](#установка)
|
||||||
- [Работа с библиотекой](#работа-с-библиотекой)
|
- [Список API](#список-api)
|
||||||
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
- [Cloudapi](#cloudapi)
|
||||||
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
- [Cloudbroker](#cloudbroker)
|
||||||
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
- [Работа с библиотекой](#работа-с-библиотекой)
|
||||||
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
||||||
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
||||||
- [Создание клиента](#создание-клиента)
|
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
||||||
- [Фильтрация](#фильтрация)
|
- [Создание клиента](#создание-клиента)
|
||||||
- [Сортировка](#сортировка)
|
- [Пример](#пример)
|
||||||
- [Сериализация](#сериализация)
|
- [Создание структуры запроса](#создание-структуры-запроса)
|
||||||
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
- [Пример комментариев структуры](#пример-комментариев-структуры)
|
||||||
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
- [Пример создания запроса для развертывания виртуальной машины:](#пример-создания-запроса-для-развертывания-виртуальной-машины)
|
||||||
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
- [Пример выполнения запроса](#пример-выполнения-запроса)
|
||||||
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
- [Пример выполнения GetRaw и ListRaw запросов](#пример-выполнения-getraw-и-listraw-запросов)
|
||||||
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
- [Фильтрация](#фильтрация)
|
||||||
- [Создание legacy клиента](#создание-legacy-клиента)
|
- [Использование на примере `compute.FilterByK8SID`:](#использование-на-примере-computefilterbyk8sid)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Сортировка](#сортировка)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Сериализация](#сериализация)
|
||||||
|
- [Комплексный пример](#комплексный-пример)
|
||||||
|
- [Получение списка уникальных идентификаторов ID объекта](#получение-списка-уникальных-идентификаторов-id-объекта)
|
||||||
|
- [Методы поля Result для группы tasks](#методы-поля-result-для-группы-tasks)
|
||||||
|
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
||||||
|
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
||||||
|
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
||||||
|
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
||||||
|
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
||||||
|
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
||||||
|
- [Создание legacy клиента](#создание-legacy-клиента)
|
||||||
|
- [Пример создания legacy клиента](#пример-создания-legacy-клиента)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-1)
|
||||||
|
- [Работа с 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-токена)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-2)
|
||||||
|
- [Пример валидации запросов, имеющих в своей структуре поле RAM (или MasterRam/WorkerRAM)](#пример-валидации-запросов-имеющих-в-своей-структуре-поле-ram-или-masterramworkerram)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-3)
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
@@ -77,6 +107,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
|
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
|
||||||
- `Stack` - получение информации о вычислительных узлах;
|
- `Stack` - получение информации о вычислительных узлах;
|
||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
|
- `VFPool` - управление пулом виртуальных сетевых функций;
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `VINS` - управление виртуальными изолированными сетями.
|
||||||
|
|
||||||
### Cloudbroker
|
### Cloudbroker
|
||||||
@@ -99,6 +130,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
||||||
- `KVMx86` - создание виртуальной машины x86;
|
- `KVMx86` - создание виртуальной машины x86;
|
||||||
- `LB` - управление балансировщиками нагрузки;
|
- `LB` - управление балансировщиками нагрузки;
|
||||||
|
- `Node` - управление нодами платформы;
|
||||||
- `PCIDevice` - управление устройствами;
|
- `PCIDevice` - управление устройствами;
|
||||||
- `RG` - управление ресурсными группами аккаунта;
|
- `RG` - управление ресурсными группами аккаунта;
|
||||||
- `SEP` - управление storage endpoint (sep);
|
- `SEP` - управление storage endpoint (sep);
|
||||||
@@ -106,6 +138,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
- `User` - управление пользователями (индивидуально);
|
- `User` - управление пользователями (индивидуально);
|
||||||
- `VGPU` - управление виртуальными графическими процессорами;
|
- `VGPU` - управление виртуальными графическими процессорами;
|
||||||
|
- `VFPool` - управление пулом виртуальных сетевых функций;
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `VINS` - управление виртуальными изолированными сетями.
|
||||||
|
|
||||||
## Работа с библиотекой
|
## Работа с библиотекой
|
||||||
@@ -113,8 +146,8 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
Алгоритм работы с библиотекой выглядит следующим образом:
|
Алгоритм работы с библиотекой выглядит следующим образом:
|
||||||
|
|
||||||
1. Выполнение одного из действий:
|
1. Выполнение одного из действий:
|
||||||
- настройка конфигурации клиента;
|
- настройка конфигурации клиента;
|
||||||
- парсинг конфигурации из файла.
|
- парсинг конфигурации из файла.
|
||||||
2. Создание клиента.
|
2. Создание клиента.
|
||||||
3. Создание структуры запроса.
|
3. Создание структуры запроса.
|
||||||
4. Выполнение запроса.
|
4. Выполнение запроса.
|
||||||
@@ -156,7 +189,7 @@ func main(){
|
|||||||
|
|
||||||
#### Парсинг конфигурации из файла
|
#### Парсинг конфигурации из файла
|
||||||
|
|
||||||
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
||||||
<br>
|
<br>
|
||||||
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
@@ -167,7 +200,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из JSON-файла
|
// Парсинг конфигурации из JSON-файла
|
||||||
cfg := config.ParseConfigJSON("<PATH>")
|
cfg, _ := config.ParseConfigJSON("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -238,48 +271,51 @@ 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/vfpool` - для `VFPool`
|
||||||
|
- `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/node` - для `Node`
|
||||||
- `pkg/cloudbroker/rg` - для `RG`
|
- `pkg/cloudbroker/pcidevice` - для `PCIDevice`
|
||||||
- `pkg/cloudbroker/sep` - для `SEP`
|
- `pkg/cloudbroker/rg` - для `RG`
|
||||||
- `pkg/cloudbroker/stack` - для `Stack`
|
- `pkg/cloudbroker/sep` - для `SEP`
|
||||||
- `pkg/cloudbroker/tasks` - для `Tasks`
|
- `pkg/cloudbroker/stack` - для `Stack`
|
||||||
- `pkg/cloudbroker/user` - для `User`
|
- `pkg/cloudbroker/tasks` - для `Tasks`
|
||||||
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
- `pkg/cloudbroker/user` - для `User`
|
||||||
- `pkg/cloudbroker/vins` - для `VINS`
|
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
||||||
|
- `pkg/cloudbroker/vfpool` - для `VFPool`
|
||||||
|
- `pkg/cloudbroker/vins` - для `VINS`
|
||||||
|
|
||||||
Все поля структуры имеют описание, в которых содержится:
|
Все поля структуры имеют описание, в которых содержится:
|
||||||
|
|
||||||
@@ -420,50 +456,53 @@ 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`
|
- `.VFPool()` - для работы с `VFPool`
|
||||||
|
- `.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`
|
- `.Node()` - для работы с `Node`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.PCIDevice()` - для работы с `PCIDevice`
|
||||||
- `.SEP()` - для работы с `SEP`
|
- `.RG()` - для работы с `RG`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.SEP()` - для работы с `SEP`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.Stack()` - для работы с `Stack`
|
||||||
- `.User()` - для работы с `User`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
- `.VGPU()` - для работы с `VGPU`
|
- `.User()` - для работы с `User`
|
||||||
- `.VINS()` - для работы с `VINS`
|
- `.VGPU()` - для работы с `VGPU`
|
||||||
|
- `.VFPool()` - для работы с `VFPool`
|
||||||
|
- `.VINS()` - для работы с `VINS`
|
||||||
|
|
||||||
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||||
|
|
||||||
@@ -634,7 +673,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)
|
||||||
@@ -766,7 +805,7 @@ func main() {
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Получение списка уникальных идентификаторов (ID) объекта
|
### Получение списка уникальных идентификаторов ID объекта
|
||||||
|
|
||||||
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
|
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
|
||||||
|
|
||||||
@@ -812,6 +851,87 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Методы поля Result для группы tasks
|
||||||
|
|
||||||
|
Поле Result внутри структур группы tasks имеет тип интерфейс и может содержать:
|
||||||
|
- строку о результате выполнения задачи, например `true`
|
||||||
|
- массив, содержащий ID и имя созданного ресурса, например `[12345, "resource_name"]`
|
||||||
|
- массив, содержащий информацию о восстновленных дисках, например `[{"computeId": 123, "diskId": 456}, {"computeId": 789, "diskId": 10}]`
|
||||||
|
|
||||||
|
Соответственно, для получения информации из поля Result доступны следующие методы:
|
||||||
|
- ToString(): строковое представление результата выполнения задачи
|
||||||
|
- ID() и Name(): получение ID и имени созданного в результате выполнения задачи ресурса
|
||||||
|
- ToMaps(): получение списка карт, содержащих информацию о дисках, восстановленных в результате выполнения задачи.
|
||||||
|
Все методы оборудованы возвратом ошибок. Непустая ошибка означает, что из поля Result нельзя получить информацию, которую предоставляет метод.
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
|
||||||
|
tasks_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/tasks"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
cfg := config.Config{
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://sso.digitalenergy.online",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
client := decort.New(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса GetRequest на получение информации о конкретной задаче и выполнение запроса с помощью конвейера
|
||||||
|
getReq := tasks.GetRequest{
|
||||||
|
AuditID: "b6316",
|
||||||
|
}
|
||||||
|
task, err := client.CloudAPI().Tasks().Get(context.Background(), getReq)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Получение списка карт с информацией о восстановленных дисках
|
||||||
|
maps, err := task.Result.ToMaps()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
fmt.Println(maps)
|
||||||
|
|
||||||
|
// Получение строкового результата выполнения задачи task
|
||||||
|
res, _ := task.Result.ToString()
|
||||||
|
fmt.Println(res)
|
||||||
|
|
||||||
|
// Создание структуры запроса ListRequest на получение информации о всех задачах и выполнение запроса с помощью конвейера
|
||||||
|
listReq := tasks_cb.ListRequest{}
|
||||||
|
tasks, err := client.CloudBroker().Tasks().List(context.Background(), listReq)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, t := range tasks {
|
||||||
|
// Получение id ресурса, созданного в результате выполнения задачи t
|
||||||
|
id, err := task.Result.ID()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
fmt.Println(id)
|
||||||
|
|
||||||
|
// Получение имени ресурса, созданного в результате выполнения задачи t
|
||||||
|
name, _ := task.Result.Name()
|
||||||
|
fmt.Println(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Работа с legacy клиентом
|
## Работа с legacy клиентом
|
||||||
|
|
||||||
Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o.
|
Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o.
|
||||||
@@ -863,7 +983,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из YAML-файла
|
// Парсинг конфигурации из YAML-файла
|
||||||
legacyCfg := config.ParseLegacyConfigYAML("<PATH>")
|
legacyCfg, _ := config.ParseLegacyConfigYAML("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -915,7 +1035,7 @@ func main() {
|
|||||||
legacyCfg.SetTimeout(5 * time.Minute)
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(cfg)
|
legacyClient := decort.NewLegacy(legacyCfg)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -936,12 +1056,13 @@ func main() {
|
|||||||
legacyCfg := config.LegacyConfig{
|
legacyCfg := config.LegacyConfig{
|
||||||
Username: "<USERNAME>",
|
Username: "<USERNAME>",
|
||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
|
Domain: "dynamix",
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(cfg)
|
legacyClient := decort.NewLegacy(legacyCfg)
|
||||||
|
|
||||||
// Создание структуры запроса
|
// Создание структуры запроса
|
||||||
// CreateRequest - реквест на создание виртуальной машины
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
@@ -954,10 +1075,384 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Работа с BVS клиентом
|
||||||
|
|
||||||
|
Работа с BVS клиентом применяется для пользователей, которые используют для авторизации BVS.
|
||||||
|
|
||||||
|
### Настройка параметров BVS в кабинете администратора
|
||||||
|
|
||||||
|
Для корректной работы функции обновления токена необходимо соблюдать следующие условия:
|
||||||
|
|
||||||
|
на странице администратора по следующему пути: домены-<имя вашего домена>-(символ i)-токены
|
||||||
|
- параметр "Время жизни токена доступа" - устанавливается для всего домена. Не применяется есть по следующему пути: безопасность-клиентские_системы-(символ i)-токены-"Время жизни токена доступа" не выставлено иное время, которое имеет больший приоритет для конкретной клиентской системы
|
||||||
|
- параметр "Время простоя сессии" - время жизни токена обновления. В случае указания количества минут меньше, чем время жизни токена, то обновление токена будет работать некорректно. Редомендуется указывать время или равное или больше времени жизни токена
|
||||||
|
- параметр "Максимальное время жизни сессии" - время в течение которого возможно производить обновление токена. Если данный параметр будет равен времени жизни токена, то обновление токена будет работать некорректно. Редомендуется указывать время больше времени жизни токена
|
||||||
|
|
||||||
|
### Настройка конфигурации BVS клиента
|
||||||
|
|
||||||
|
Сначала, необходимо создать переменную конфигурации клиента. Конфигурация состоит как из обязательных, так и необязательных полей.
|
||||||
|
|
||||||
|
| Поле | Тип | Обязательный | Описание |
|
||||||
|
| ------------- | --------------------------------------------- | ------------ | ------------------------------------------------------------------ |
|
||||||
|
| Username | string | Да | username пользователя |
|
||||||
|
| Password | string | Да | пароль пользователя |
|
||||||
|
| AppID | string | Да | app_id ключа для выполнения запросов |
|
||||||
|
| AppSecret | string | Да | app_secret ключ для выполнения запроса |
|
||||||
|
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||||
|
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
||||||
|
| Domain | string | Да | Имя домена |
|
||||||
|
| 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 клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main(){
|
||||||
|
// Настройка конфигурации
|
||||||
|
BvsCfg := config.BVSConfig{
|
||||||
|
AppID: "<APP_ID>",
|
||||||
|
AppSecret: "<APP_SECRET>",
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443",
|
||||||
|
DecortURL: "https://delta.qa.loc",
|
||||||
|
Domain: "dynamix",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
BvsCfg.SetTimeout(5 * time.Minute)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Парсинг BVS конфигурации из файла
|
||||||
|
|
||||||
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigBVSJSON` (или `ParseConfigBVSYAML`) из пакета config.
|
||||||
|
<br>
|
||||||
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Парсинг конфигурации из YAML-файла
|
||||||
|
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>")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример BVS JSON конфигурации
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "<USERNAME>",
|
||||||
|
"password": "<PASSWORD>",
|
||||||
|
"appId": "<APP_ID>",
|
||||||
|
"appSecret": "<APP_SECRET>",
|
||||||
|
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
||||||
|
"decortUrl": "https://delta.qa.loc",
|
||||||
|
"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,
|
||||||
|
"sslSkipVerify": true,
|
||||||
|
"timeout": "5m",
|
||||||
|
"path_cfg": "config",
|
||||||
|
"path_token": "token",
|
||||||
|
"timeToRefresh": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример BVS YAML конфигурации
|
||||||
|
```yaml
|
||||||
|
username: <USERNAME>
|
||||||
|
password: <PASSWORD>
|
||||||
|
appId: <APP_ID>
|
||||||
|
appSecret: <APP_SECRET>
|
||||||
|
ssoUrl: https://bvs-delta.qa.loc:8443
|
||||||
|
decortUrl: https://delta.qa.loc
|
||||||
|
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
|
||||||
|
sslSkipVerify: true
|
||||||
|
timeout: 5m
|
||||||
|
path_cfg: config
|
||||||
|
path_token: token
|
||||||
|
timeToRefresh: 5
|
||||||
|
```
|
||||||
|
### Создание BVS клиента
|
||||||
|
|
||||||
|
Создание клиента происходит с помощью функции-строителя `NewBVS` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
||||||
|
|
||||||
|
#### Пример создания BVS клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"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",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
BVSCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример выполнения запроса
|
||||||
|
|
||||||
|
```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",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
BVSClient := decort.NewBVS(BVSCfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса
|
||||||
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
|
req := kvmx86.CreateRequest{
|
||||||
|
RGID: 123,
|
||||||
|
Name: "compute",
|
||||||
|
CPU: 4,
|
||||||
|
RAM: 4096,
|
||||||
|
ImageID: 321,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выполнение запроса
|
||||||
|
res, err := BVSClient.CloudAPI().KVMX86().Create(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
#### Пример валидации запросов, имеющих в своей структуре поле RAM (или MasterRam/WorkerRAM)
|
||||||
|
|
||||||
|
Если структура запроса содержит поле RAM (или MasterRam/WorkerRAM), то он может быть проверен на валидность. Для этого запрос должен быть передан в функцию ValidateRAM. Вторым аргументом ValidateRAM ожидает число uint64. Рекомендуется использовать константу constants.RAM_DIVISIBILITY. Функция проверит кратно ли значение поля RAM (или MasterRam/WorkerRAM) этому числу.
|
||||||
|
|
||||||
|
#### Пример выполнения запроса
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/kvmx86"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
cfg := config.Config{
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://sso-delta.qa.loc:8443",
|
||||||
|
DecortURL: "https://delta.qa.loc",
|
||||||
|
Retries: 5,
|
||||||
|
SSLSkipVerify: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
client := decort.New(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса
|
||||||
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
|
req := kvmx86.CreateRequest{
|
||||||
|
Name: "kvmx86",
|
||||||
|
RGID: 907,
|
||||||
|
CPU: 2048,
|
||||||
|
RAM: 1024,
|
||||||
|
ImageID: 161,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Валидация запроса
|
||||||
|
err := validators.ValidateRAM(req, constants.RAM_DIVISIBILITY)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("unable to validate request: %v", err)
|
||||||
|
}
|
||||||
|
//Выполнение запроса с помощью конвейера
|
||||||
|
res, err := client.CloudBroker().KVMX86().Create(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println(res)
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
484
client.go
484
client.go
@@ -4,10 +4,12 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -15,13 +17,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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// HTTP-client for platform
|
// DecortClient is HTTP-client for platform
|
||||||
type DecortClient struct {
|
type DecortClient struct {
|
||||||
decortURL string
|
decortURL string
|
||||||
client *http.Client
|
client *http.Client
|
||||||
@@ -70,35 +71,54 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// perform request
|
// perform request
|
||||||
var respBytes []byte
|
respBytes, err := dc.do(req, "")
|
||||||
respBytes, err = dc.do(req, ctype)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecortApiCallMP method for sending requests to the platform
|
||||||
|
func (dc *DecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if err = dc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
respBytes, err := dc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return respBytes, err
|
return respBytes, err
|
||||||
}
|
}
|
||||||
@@ -107,41 +127,53 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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) {
|
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)
|
||||||
@@ -152,14 +184,52 @@ func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
req.Body.Close()
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
resp, err := dc.client.Do(req)
|
resp, err := dc.client.Do(req)
|
||||||
if err != nil || resp == nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
// handle successful request
|
// handle successful request
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
if resp.StatusCode == 200 {
|
if resp.StatusCode == 200 {
|
||||||
@@ -171,228 +241,110 @@ func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
|||||||
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)
|
||||||
|
values := reflect.ValueOf(params)
|
||||||
|
types := values.Type()
|
||||||
defer writer.Close()
|
defer writer.Close()
|
||||||
if req.OidcCertificate != "" {
|
for i := 0; i < values.NumField(); i++ {
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
if !values.Field(i).IsValid() {
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case []map[string]interface{}:
|
||||||
|
for _, val := range slice {
|
||||||
|
encodeStr, err := json.Marshal(val)
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
err = writer.WriteField(trimString(types.Field(i)), string(encodeStr))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return &bytes.Buffer{}, "", fmt.Errorf("unsupported slice type:%T", slice)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), valueToString(values.Field(i).Interface()))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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()
|
||||||
return reqBody, ct
|
return reqBody, ct, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
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:
|
||||||
defer writer.Close()
|
return str
|
||||||
if req.OidcCertificate != "" {
|
case uint:
|
||||||
part, _ := writer.CreateFormFile("oidcCertificate", "ca.crt")
|
return strconv.FormatUint(uint64(str), 10)
|
||||||
_, _ = io.Copy(part, strings.NewReader(req.OidcCertificate))
|
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()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
}
|
||||||
|
|||||||
380
client_bvs.go
Normal file
380
client_bvs.go
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
package decortsdk
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-querystring/query"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BVSDecortClient is HTTP-client for platform
|
||||||
|
type BVSDecortClient struct {
|
||||||
|
client *http.Client
|
||||||
|
cfg config.BVSConfig
|
||||||
|
mutex *sync.Mutex
|
||||||
|
decortURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
type tokenJSON struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
ExpiresIn uint64 `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сlient builder
|
||||||
|
func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
||||||
|
if cfg.Retries == 0 {
|
||||||
|
cfg.Retries = 5
|
||||||
|
}
|
||||||
|
if cfg.TimeToRefresh == 0 {
|
||||||
|
cfg.TimeToRefresh = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return &BVSDecortClient{
|
||||||
|
decortURL: cfg.DecortURL,
|
||||||
|
client: &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{
|
||||||
|
//nolint:gosec
|
||||||
|
InsecureSkipVerify: cfg.SSLSkipVerify,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cfg: cfg,
|
||||||
|
mutex: &sync.Mutex{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloudAPI builder
|
||||||
|
func (bdc *BVSDecortClient) CloudAPI() *cloudapi.CloudAPI {
|
||||||
|
return cloudapi.New(bdc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloudBroker builder
|
||||||
|
func (bdc *BVSDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
||||||
|
return cloudbroker.New(bdc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecortApiCall method for sending requests to the platform
|
||||||
|
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
body := bytes.NewBufferString(values.Encode())
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if bdc.cfg.Token.AccessToken == "" {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||||
|
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
reqCopy := req.Clone(ctx)
|
||||||
|
respBytes, err := bdc.do(req, "")
|
||||||
|
if err == nil {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token and retry in case of access denied
|
||||||
|
if err.Error() == "access is denied" {
|
||||||
|
_, err = bdc.GetToken(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, err = bdc.do(reqCopy, "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bdc *BVSDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if bdc.cfg.Token.AccessToken == "" {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
if bdc.cfg.Token.RefreshToken != "" && bdc.cfg.Token.Expiry.Add(-time.Duration(bdc.cfg.TimeToRefresh)*time.Minute).Before(time.Now()) {
|
||||||
|
if _, err := bdc.RefreshToken(ctx); err != nil {
|
||||||
|
if _, err = bdc.GetToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
reqCopy := req.Clone(ctx)
|
||||||
|
respBytes, err := bdc.do(req, ctype)
|
||||||
|
if err == nil {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token and retry in case of access denied
|
||||||
|
if err.Error() == "access is denied" {
|
||||||
|
_, err = bdc.GetToken(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
respBytes, err = bdc.do(reqCopy, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetToken allows you to get a token and returns the token structure. When specifying the PathCfg variable,
|
||||||
|
// the token and configuration will be written to a file.
|
||||||
|
// When specifying the PathToken variable, the token will be written to a file.
|
||||||
|
func (bdc *BVSDecortClient) GetToken(ctx context.Context) (config.Token, error) {
|
||||||
|
bdc.mutex.Lock()
|
||||||
|
defer bdc.mutex.Unlock()
|
||||||
|
|
||||||
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Username, bdc.cfg.Password)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// request token
|
||||||
|
resp, err := bdc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
var tj tokenJSON
|
||||||
|
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot unmarshal token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bdc.cfg.Token = config.Token{
|
||||||
|
AccessToken: tj.AccessToken,
|
||||||
|
TokenType: tj.TokenType,
|
||||||
|
RefreshToken: tj.RefreshToken,
|
||||||
|
Expiry: tj.expiry(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathCfg != "" {
|
||||||
|
ser, _ := bdc.cfg.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathToken != "" {
|
||||||
|
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bdc.cfg.Token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefreshToken allows you to refresh a token and returns the token structure. When specifying the PathCfg variable,
|
||||||
|
// the token and configuration will be written to a file.
|
||||||
|
// When specifying the PathToken variable, the token will be written to a file
|
||||||
|
func (bdc *BVSDecortClient) RefreshToken(ctx context.Context) (config.Token, error) {
|
||||||
|
bdc.mutex.Lock()
|
||||||
|
defer bdc.mutex.Unlock()
|
||||||
|
|
||||||
|
// set up request headers and body
|
||||||
|
body := fmt.Sprintf("grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Token.RefreshToken)
|
||||||
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// refresh token
|
||||||
|
resp, err := bdc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot refresh token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
var tj tokenJSON
|
||||||
|
if err = json.Unmarshal(tokenBytes, &tj); err != nil {
|
||||||
|
return config.Token{}, fmt.Errorf("cannot unmarshal after refresh token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bdc.cfg.Token = config.Token{
|
||||||
|
AccessToken: tj.AccessToken,
|
||||||
|
TokenType: tj.TokenType,
|
||||||
|
RefreshToken: tj.RefreshToken,
|
||||||
|
Expiry: tj.expiry(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathCfg != "" {
|
||||||
|
ser, _ := bdc.cfg.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathCfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if bdc.cfg.PathToken != "" {
|
||||||
|
ser, _ := bdc.cfg.Token.Serialize("", " ")
|
||||||
|
_ = ser.WriteToFile(bdc.cfg.PathToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bdc.cfg.Token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *tokenJSON) expiry() (t time.Time) {
|
||||||
|
if v := e.ExpiresIn; v != 0 {
|
||||||
|
return time.Now().Add(time.Duration(v) * time.Second)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// do method performs request and returns response as an array of bytes and nil error in case of response status code 200.
|
||||||
|
// In any other cases do returns nil response and error.
|
||||||
|
// Retries are implemented in case of connection reset errors.
|
||||||
|
func (bdc *BVSDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
||||||
|
// set up request headers and body
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
if ctype != "" {
|
||||||
|
req.Header.Set("Content-Type", ctype)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Add("Authorization", "bearer "+bdc.cfg.Token.AccessToken)
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
|
buf, err := io.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Body.Close()
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
resp, err := bdc.client.Do(req)
|
||||||
|
if resp != nil {
|
||||||
|
defer resp.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// retries logic GOES HERE
|
||||||
|
// get http response
|
||||||
|
//var resp *http.Response
|
||||||
|
//for i := uint64(0); i < bdc.cfg.Retries; i++ {
|
||||||
|
// req := req.Clone(req.Context())
|
||||||
|
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
//
|
||||||
|
// if i > 0 {
|
||||||
|
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// resp, err = bdc.client.Do(req)
|
||||||
|
//
|
||||||
|
// // stop retries on success and close response body
|
||||||
|
// if resp != nil {
|
||||||
|
// defer resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// if err == nil {
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // retries in case of connection errors with time sleep
|
||||||
|
// if isConnectionError(err) {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // return error in case of non-connection error
|
||||||
|
// return nil, err
|
||||||
|
//}
|
||||||
|
|
||||||
|
// handle http request errors
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
|
var respBytes []byte
|
||||||
|
respBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle access denied and successful request
|
||||||
|
if resp.StatusCode == 401 {
|
||||||
|
return respBytes, errors.New("access is denied")
|
||||||
|
}
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return respBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle errors with other status codes
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
|
}
|
||||||
216
config/config_bvs.go
Normal file
216
config/config_bvs.go
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BVSConfig struct {
|
||||||
|
// ServiceAccount username
|
||||||
|
// Required: true
|
||||||
|
// Example : "osh_mikoev"
|
||||||
|
Username string `json:"username" yaml:"username" validate:"required"`
|
||||||
|
|
||||||
|
// ServiceAccount password
|
||||||
|
// Required: true
|
||||||
|
// Example: "[1o>hYkjnJr)HI78q7t&#%8Lm"
|
||||||
|
Password string `json:"password" yaml:"password" validate:"required"`
|
||||||
|
|
||||||
|
// Domain name
|
||||||
|
// Required: true
|
||||||
|
// Example: "dynamix"
|
||||||
|
Domain string `json:"domain" yaml:"domain" validate:"required"`
|
||||||
|
|
||||||
|
// Application (client) identifier for authorization
|
||||||
|
// in the cloud platform controller in oauth2 mode.
|
||||||
|
// Required: true
|
||||||
|
// Example: "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
|
||||||
|
AppID string `json:"appId" yaml:"appId" validate:"required"`
|
||||||
|
|
||||||
|
// Application (client) secret code for authorization
|
||||||
|
// in the cloud platform controller in oauth2 mode.
|
||||||
|
// Example: "frvet09rvesfis0c9erv9fsov0vsdfi09ovds0f"
|
||||||
|
AppSecret string `json:"appSecret" yaml:"appSecret" validate:"required"`
|
||||||
|
|
||||||
|
// Platform authentication service address
|
||||||
|
// Required: true
|
||||||
|
// Example: "https://sso.digitalenergy.online"
|
||||||
|
SSOURL string `json:"ssoUrl" yaml:"ssoUrl" validate:"url"`
|
||||||
|
|
||||||
|
// The address of the platform on which the actions are planned
|
||||||
|
// Required: true
|
||||||
|
// Example: "https://mr4.digitalenergy.online"
|
||||||
|
DecortURL string `json:"decortUrl" yaml:"decortUrl" validate:"url"`
|
||||||
|
|
||||||
|
// JWT platform token
|
||||||
|
// Required: false
|
||||||
|
// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
|
||||||
|
Token Token `json:"token" yaml:"token"`
|
||||||
|
|
||||||
|
// Amount platform request attempts
|
||||||
|
// Default value: 5
|
||||||
|
// Required: false
|
||||||
|
Retries uint64 `json:"retries" yaml:"retries"`
|
||||||
|
|
||||||
|
// Skip verify
|
||||||
|
// Required: false
|
||||||
|
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||||
|
|
||||||
|
// HTTP client timeout, unlimited if left empty
|
||||||
|
// Required: false
|
||||||
|
Timeout Duration `json:"timeout" yaml:"timeout"`
|
||||||
|
|
||||||
|
// The path of the configuration file entry
|
||||||
|
// Required: false
|
||||||
|
PathCfg string `json:"path_cfg" yaml:"path_cfg"`
|
||||||
|
|
||||||
|
// The path of the token file entry
|
||||||
|
// Required: false
|
||||||
|
PathToken string `json:"path_token" yaml:"path_token"`
|
||||||
|
|
||||||
|
// The number of minutes before the expiration of the token, a refresh will be made
|
||||||
|
// Required: false
|
||||||
|
TimeToRefresh int64 `json:"timeToRefresh" yaml:"timeToRefresh"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Token struct {
|
||||||
|
// AccessToken is the token that authorizes and authenticates
|
||||||
|
// the requests.
|
||||||
|
// Required: false
|
||||||
|
AccessToken string `json:"access_token" yaml:"access_token"`
|
||||||
|
|
||||||
|
// TokenType is the type of token.
|
||||||
|
// The Type method returns either this or "Bearer", the default.
|
||||||
|
// Required: false
|
||||||
|
TokenType string `json:"token_type" yaml:"token_type"`
|
||||||
|
|
||||||
|
// RefreshToken is a token that's used by the application
|
||||||
|
// (as opposed to the user) to refresh the access token
|
||||||
|
// if it expires.
|
||||||
|
// Required: false
|
||||||
|
RefreshToken string `json:"refresh_token" yaml:"refresh_token"`
|
||||||
|
|
||||||
|
// Expiry is the optional expiration time of the access token.
|
||||||
|
// Required: false
|
||||||
|
Expiry time.Time `json:"expiry" yaml:"expiry"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTimeout is used to set HTTP client timeout.
|
||||||
|
func (c *BVSConfig) SetTimeout(dur time.Duration) {
|
||||||
|
c.Timeout = Duration(dur)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseConfigJSON parses Config from specified JSON-formatted file.
|
||||||
|
func ParseConfigBVSJSON(path string) (BVSConfig, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config BVSConfig
|
||||||
|
|
||||||
|
err = json.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseConfigJSON parses Token from specified JSON-formatted file.
|
||||||
|
func ParseTokenBVSJSON(path string) (Token, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var token Token
|
||||||
|
|
||||||
|
err = json.Unmarshal(file, &token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseTokenBVSYAML parses Token from specified YAML-formatted file.
|
||||||
|
func ParseTokenBVSYAML(path string) (Token, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var token Token
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(file, &token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(token)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseConfigYAML parses Config from specified YAML-formatted file.
|
||||||
|
func ParseConfigBVSYAML(path string) (BVSConfig, error) {
|
||||||
|
file, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var config BVSConfig
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(file, &config)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validators.ValidateConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t Token) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(t, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c BVSConfig) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(c, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(c)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
8
go.mod
8
go.mod
@@ -5,15 +5,17 @@ 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
|
||||||
|
github.com/joho/godotenv v1.5.1
|
||||||
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/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.5.0 // indirect
|
golang.org/x/crypto v0.15.0 // indirect
|
||||||
golang.org/x/sys v0.4.0 // indirect
|
golang.org/x/sys v0.14.0 // indirect
|
||||||
golang.org/x/text v0.6.0 // indirect
|
golang.org/x/text v0.14.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
17
go.sum
17
go.sum
@@ -8,10 +8,13 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
|||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/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/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
|
|
||||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
@@ -23,12 +26,12 @@ github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUA
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/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.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
|
golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
|
||||||
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
|
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
|
||||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
||||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
|||||||
@@ -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
interfaces/request.go
Normal file
7
interfaces/request.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package interfaces
|
||||||
|
|
||||||
|
// Interface to valiate RAM values
|
||||||
|
type RequestWithRAM interface {
|
||||||
|
// GetRAM returns RAM values
|
||||||
|
GetRAM() map[string]uint64
|
||||||
|
}
|
||||||
12
internal/constants/constants.go
Normal file
12
internal/constants/constants.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package constants
|
||||||
|
|
||||||
|
const (
|
||||||
|
RESTMACHINE = "/restmachine"
|
||||||
|
|
||||||
|
// RAM_DIVISIBILITY sets divisibility of RAM value
|
||||||
|
RAM_DIVISIBILITY uint64 = 128
|
||||||
|
)
|
||||||
|
|
||||||
|
var FileName = map[string]string{
|
||||||
|
"OidcCertificate": "ca.crt",
|
||||||
|
}
|
||||||
@@ -1,31 +1,35 @@
|
|||||||
package validators
|
package validators
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/multierror"
|
||||||
)
|
)
|
||||||
|
|
||||||
// computeDriverValidator is used to validate Driver field in kvmx86/kvmppc create.
|
// computeDriverValidator is used to validate Driver field in kvmx86/kvmppc create.
|
||||||
func computeDriverValidator(fe validator.FieldLevel) bool {
|
func computeDriverValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDriverValues)
|
return IsInSlice(fieldValue, computeDriverValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// protoValidator is used to validate Proto fields.
|
// protoValidator is used to validate Proto fields.
|
||||||
func protoValidator(fe validator.FieldLevel) bool {
|
func protoValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, protoValues)
|
return IsInSlice(fieldValue, protoValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// accessTypeValidator is used to validate AccessType fields.
|
// accessTypeValidator is used to validate AccessType fields.
|
||||||
func accessTypeValidator(fe validator.FieldLevel) bool {
|
func accessTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, accessTypeValues)
|
return IsInSlice(fieldValue, accessTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// resTypesValidator is used to validate ResTypes fields.
|
// resTypesValidator is used to validate ResTypes fields.
|
||||||
@@ -36,7 +40,7 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !StringInSlice(value, resTypesValues) {
|
if !IsInSlice(value, resTypesValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,56 +52,56 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
|||||||
func driverValidator(fe validator.FieldLevel) bool {
|
func driverValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, driverValues)
|
return IsInSlice(fieldValue, driverValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// accountCUTypeValidator is used to validate CUType field.
|
// accountCUTypeValidator is used to validate CUType field.
|
||||||
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, accountCUTypeValues)
|
return IsInSlice(fieldValue, accountCUTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// bserviceModeValidator is used to validate Mode field.
|
// bserviceModeValidator is used to validate Mode field.
|
||||||
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, bserviceModeValues)
|
return IsInSlice(fieldValue, bserviceModeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeTopologyValidator is used to validate Topology field.
|
// computeTopologyValidator is used to validate Topology field.
|
||||||
func computeTopologyValidator(fe validator.FieldLevel) bool {
|
func computeTopologyValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeTopologyValues)
|
return IsInSlice(fieldValue, computeTopologyValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computePolicyValidator is used to validate Policy field.
|
// computePolicyValidator is used to validate Policy field.
|
||||||
func computePolicyValidator(fe validator.FieldLevel) bool {
|
func computePolicyValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computePolicyValues)
|
return IsInSlice(fieldValue, computePolicyValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeModeValidator is used to validate Mode field.
|
// computeModeValidator is used to validate Mode field.
|
||||||
func computeModeValidator(fe validator.FieldLevel) bool {
|
func computeModeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeModeValues)
|
return IsInSlice(fieldValue, computeModeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeDiskTypeValidator is used to validate DiskType field.
|
// computeDiskTypeValidator is used to validate DiskType field.
|
||||||
func computeDiskTypeValidator(fe validator.FieldLevel) bool {
|
func computeDiskTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDiskTypeValues)
|
return IsInSlice(fieldValue, computeDiskTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeNetTypeValidator is used to validate NetType field.
|
// computeNetTypeValidator is used to validate NetType field.
|
||||||
func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeNetTypeValues)
|
return IsInSlice(fieldValue, computeNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeOrderValidator is used to validate Order field.
|
// computeOrderValidator is used to validate Order field.
|
||||||
@@ -108,7 +112,7 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !StringInSlice(value, computeOrderValues) {
|
if !IsInSlice(value, computeOrderValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,70 +124,70 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
|||||||
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDataDisksValues)
|
return IsInSlice(fieldValue, computeDataDisksValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// diskTypeValidator is used to validate Type field.
|
// diskTypeValidator is used to validate Type field.
|
||||||
func diskTypeValidator(fe validator.FieldLevel) bool {
|
func diskTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, diskTypeValues)
|
return IsInSlice(fieldValue, diskTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// flipgroupClientTypeValidator is used to validate ClientType field.
|
// flipgroupClientTypeValidator is used to validate ClientType field.
|
||||||
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, flipgroupClientTypeValues)
|
return IsInSlice(fieldValue, flipgroupClientTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// kvmNetTypeValidator is used to validate NetType field.
|
// kvmNetTypeValidator is used to validate NetType field.
|
||||||
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, kvmNetTypeValues)
|
return IsInSlice(fieldValue, kvmNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// lbAlgorithmValidator is used to validate Algorithm field.
|
// lbAlgorithmValidator is used to validate Algorithm field.
|
||||||
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, lbAlgorithmValues)
|
return IsInSlice(fieldValue, lbAlgorithmValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// rgDefNetValidator is used to validate DefNet field.
|
// rgDefNetValidator is used to validate DefNet field.
|
||||||
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, rgDefNetValues)
|
return IsInSlice(fieldValue, rgDefNetValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// rgNetTypeValidator is used to validate NetType field.
|
// rgNetTypeValidator is used to validate NetType field.
|
||||||
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, rgNetTypeValues)
|
return IsInSlice(fieldValue, rgNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// vinsTypeValidator is used to validate Type field.
|
// vinsTypeValidator is used to validate Type field.
|
||||||
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, vinsTypeValues)
|
return IsInSlice(fieldValue, vinsTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageBootTypeValidator is used to validate BootType field.
|
// imageBootTypeValidator is used to validate BootType field.
|
||||||
func imageBootTypeValidator(fe validator.FieldLevel) bool {
|
func imageBootTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageBootTypeValues)
|
return IsInSlice(fieldValue, imageBootTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageTypeValidator is used to validate ImageType field.
|
// imageTypeValidator is used to validate ImageType field.
|
||||||
func imageTypeValidator(fe validator.FieldLevel) bool {
|
func imageTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageTypeValues)
|
return IsInSlice(fieldValue, imageTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageDriversValidator is used to validate Drivers field.
|
// imageDriversValidator is used to validate Drivers field.
|
||||||
@@ -194,7 +198,7 @@ func imageDriversValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, item := range fieldSlice {
|
for _, item := range fieldSlice {
|
||||||
if !StringInSlice(item, imageDriversValues) {
|
if !IsInSlice(item, imageDriversValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,14 +210,14 @@ func imageDriversValidator(fe validator.FieldLevel) bool {
|
|||||||
func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageArchitectureValues)
|
return IsInSlice(fieldValue, imageArchitectureValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sepFieldTypeValidator is used to validate FieldType field.
|
// sepFieldTypeValidator is used to validate FieldType field.
|
||||||
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, sepFieldTypeValues)
|
return IsInSlice(fieldValue, sepFieldTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// hwPathValidator is used to validate HWPath field.
|
// hwPathValidator is used to validate HWPath field.
|
||||||
@@ -230,7 +234,7 @@ func networkPluginValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, networkPluginValues)
|
return IsInSlice(fieldValue, networkPluginValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// networkPluginsValidator is used to validate NetworkPlugins field
|
// networkPluginsValidator is used to validate NetworkPlugins field
|
||||||
@@ -243,7 +247,7 @@ func networkPluginsValidator(fe validator.FieldLevel) bool {
|
|||||||
for _, item := range fieldSlice {
|
for _, item := range fieldSlice {
|
||||||
item = strings.ToLower(item)
|
item = strings.ToLower(item)
|
||||||
|
|
||||||
if !StringInSlice(item, networkPluginValues) {
|
if !IsInSlice(item, networkPluginValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -255,14 +259,14 @@ func interfaceStateValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, interfaceStateValues)
|
return IsInSlice(fieldValue, interfaceStateValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
func strictLooseValidator(fe validator.FieldLevel) bool {
|
func strictLooseValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, strictLooseValues)
|
return IsInSlice(fieldValue, strictLooseValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// name workerGroup must be more 3 symbol
|
// name workerGroup must be more 3 symbol
|
||||||
@@ -272,3 +276,60 @@ func workerGroupNameValidator(fe validator.FieldLevel) bool {
|
|||||||
|
|
||||||
return len(fieldValue) >= 3
|
return len(fieldValue) >= 3
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func sortByValidator(fe validator.FieldLevel) bool {
|
||||||
|
|
||||||
|
sortByRegexp := regexp.MustCompile(`^[+-][a-zA-Z_]+`)
|
||||||
|
|
||||||
|
return sortByRegexp.MatchString(fe.Field().String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func actionValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, actionValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func vmActionValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, vmActionValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func computeFeaturesValidator(fe validator.FieldLevel) bool {
|
||||||
|
field := fe.Field()
|
||||||
|
slice, ok := field.Interface().([]string)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return IsSubSlice(slice, computeFeaturesValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func networkInterfaceNamingValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, networkInterfaceNamingValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateRAM checks if request contains RAM value that is positive integer divisible by divisibility passed.
|
||||||
|
// It is recommended to pass constants.RAM_DIVISIBILITY as divisility arguement
|
||||||
|
func ValidateRAM(r interfaces.RequestWithRAM, divisibility uint64) error {
|
||||||
|
|
||||||
|
if divisibility == 0 {
|
||||||
|
|
||||||
|
return errors.New("second argument of ValidateRAM should be greater than 0")
|
||||||
|
}
|
||||||
|
mapRAM := r.GetRAM()
|
||||||
|
|
||||||
|
errs := make([]error, 0, len(mapRAM))
|
||||||
|
|
||||||
|
for k, v := range mapRAM {
|
||||||
|
|
||||||
|
if v%divisibility != 0 {
|
||||||
|
|
||||||
|
errs = append(errs, fmt.Errorf("expected value of %s: \"%d\" should be divisible by %d", k, v, divisibility))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return multierror.Join(errs...)
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ func GetErrors(err error) validator.ValidationErrors {
|
|||||||
return err.(validator.ValidationErrors)
|
return err.(validator.ValidationErrors)
|
||||||
}
|
}
|
||||||
|
|
||||||
func StringInSlice(str string, target []string) bool {
|
func IsInSlice(str string, target []string) bool {
|
||||||
for _, v := range target {
|
for _, v := range target {
|
||||||
if v == str {
|
if v == str {
|
||||||
return true
|
return true
|
||||||
@@ -42,3 +42,12 @@ func StringInSlice(str string, target []string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsSubSlice(source []string, target []string) bool {
|
||||||
|
for _, s := range source {
|
||||||
|
if !IsInSlice(s, target) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|||||||
@@ -229,6 +229,35 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
prefix,
|
prefix,
|
||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(interfaceStateValues))
|
joinValues(interfaceStateValues))
|
||||||
|
|
||||||
|
case "sortBy":
|
||||||
|
return fmt.Sprintf("%s %s must be in format +|-(field)",
|
||||||
|
prefix,
|
||||||
|
fe.Field())
|
||||||
|
|
||||||
|
case "action":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(actionValues))
|
||||||
|
|
||||||
|
case "vmaction":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(vmActionValues))
|
||||||
|
|
||||||
|
case "computeFeatures":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(computeFeaturesValues))
|
||||||
|
|
||||||
|
case "networkInterfaceNaming":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(networkInterfaceNamingValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
return fe.Error()
|
return fe.Error()
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ func getDecortValidator() *validator.Validate {
|
|||||||
|
|
||||||
// registerAllValidators registers all custom validators in DecortValidator.
|
// registerAllValidators registers all custom validators in DecortValidator.
|
||||||
func registerAllValidators(validate *validator.Validate) error {
|
func registerAllValidators(validate *validator.Validate) error {
|
||||||
|
|
||||||
err := validate.RegisterValidation("proto", protoValidator)
|
err := validate.RegisterValidation("proto", protoValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -185,5 +186,30 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("sortBy", sortByValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("action", actionValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("vmaction", vmActionValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("computeFeatures", computeFeaturesValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("networkInterfaceNaming", networkInterfaceNamingValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,9 +39,17 @@ 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"}
|
||||||
|
|
||||||
interfaceStateValues = []string{"on", "off"}
|
interfaceStateValues = []string{"on", "off"}
|
||||||
|
|
||||||
|
actionValues = []string{"power_on", "shutdown", "force_shutdown", "reboot"}
|
||||||
|
|
||||||
|
vmActionValues = []string{"stop", "move"}
|
||||||
|
|
||||||
|
computeFeaturesValues = []string{"hugepages", "numa", "cpupin", "vfnic"}
|
||||||
|
|
||||||
|
networkInterfaceNamingValues = []string{"eth", "ens"}
|
||||||
)
|
)
|
||||||
|
|||||||
404
legacy-client.go
404
legacy-client.go
@@ -6,23 +6,20 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"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
|
||||||
@@ -71,36 +68,53 @@ 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)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
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)
|
body := bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// perform request
|
// perform request
|
||||||
var respBytes []byte
|
respBytes, err := ldc.do(req, "")
|
||||||
respBytes, err = ldc.do(req, ctype)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ldc *LegacyDecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
|
body, ctype, err := multiPartReq(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if err = ldc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
respBytes, err := ldc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return respBytes, err
|
return respBytes, err
|
||||||
}
|
}
|
||||||
@@ -109,60 +123,108 @@ 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+constants.RESTMACHINE+"/cloudapi/user/authenticate", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
// request token
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if err != nil || resp == nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenBytes []byte
|
||||||
|
tokenBytes, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// save token in config
|
||||||
|
token := string(tokenBytes)
|
||||||
|
ldc.cfg.Token = token
|
||||||
|
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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) {
|
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")
|
||||||
|
|
||||||
buf, err := io.ReadAll(req.Body)
|
buf, err := io.ReadAll(req.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Body.Close()
|
req.Body.Close()
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
resp, err := ldc.client.Do(req)
|
resp, err := ldc.client.Do(req)
|
||||||
if err != nil || resp == nil {
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("got empty response without error")
|
||||||
|
}
|
||||||
|
|
||||||
// handle successful request
|
// handle successful request
|
||||||
respBytes, err := io.ReadAll(resp.Body)
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
if err!= nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if resp.StatusCode == 200 {
|
if resp.StatusCode == 200 {
|
||||||
return respBytes, nil
|
return respBytes, nil
|
||||||
}
|
}
|
||||||
@@ -171,233 +233,3 @@ func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, erro
|
|||||||
err = fmt.Errorf("%s", respBytes)
|
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)
|
|
||||||
defer writer.Close()
|
|
||||||
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()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|
||||||
func createK8sCloudBrokerLegacy(req k8s_cb.CreateRequest, token string) (*bytes.Buffer, string) {
|
|
||||||
reqBody := &bytes.Buffer{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
defer writer.Close()
|
|
||||||
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()
|
|
||||||
return reqBody, ct
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ type GetConsumptionRequest struct {
|
|||||||
|
|
||||||
// Epoch represents the start time
|
// Epoch represents the start time
|
||||||
// Required: true
|
// Required: true
|
||||||
Start uint64 `url:"start" json:"start" validate:"required"`
|
Start float64 `url:"start" json:"start" validate:"required"`
|
||||||
|
|
||||||
// Epoch represents the end time
|
// Epoch represents the end time
|
||||||
// Required: true
|
// Required: true
|
||||||
End uint64 `url:"end" json:"end" validate:"required"`
|
End float64 `url:"end" json:"end" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetConsumption downloads the resources tracking files for an account within a given period
|
// GetConsumption downloads the resources tracking files for an account within a given period
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of accounts
|
// ListRequest struct to get list of accounts
|
||||||
@@ -24,6 +26,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -35,6 +41,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets a list of all accounts the user has access to a ListAccounts struct
|
// List gets a list of all accounts the user has access to a ListAccounts struct
|
||||||
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
||||||
|
|
||||||
res, err := a.ListRaw(ctx, req)
|
res, err := a.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -52,6 +59,11 @@ func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, erro
|
|||||||
|
|
||||||
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
||||||
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/list"
|
url := "/cloudapi/account/list"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ type ListComputesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -57,6 +61,7 @@ type ListComputesRequest struct {
|
|||||||
|
|
||||||
// ListComputes gets list all compute instances under specified account, accessible by the user
|
// ListComputes gets list all compute instances under specified account, accessible by the user
|
||||||
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get a list of deleted accounts
|
// ListDeletedRequest struct to get a list of deleted accounts
|
||||||
@@ -27,10 +29,20 @@ type ListDeletedRequest struct {
|
|||||||
// Find by access control list
|
// Find by access control list
|
||||||
// Required: false
|
// Required: false
|
||||||
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
|
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListDeleted gets list of all deleted accounts the user has access to
|
// ListDeleted gets list of all deleted accounts the user has access to
|
||||||
func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
|
func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
|
||||||
|
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listDeleted"
|
url := "/cloudapi/account/listDeleted"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListDisksRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListDisksRequest struct {
|
|||||||
|
|
||||||
// ListDisks gets list all currently unattached disks under specified account
|
// ListDisks gets list all currently unattached disks under specified account
|
||||||
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
|
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ type ListFLIPGroupsRequest struct {
|
|||||||
|
|
||||||
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
|
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
|
||||||
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
|
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -41,10 +41,15 @@ type ListRGRequest struct {
|
|||||||
// Find by status
|
// Find by status
|
||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRG gets list of all resource groups under specified account, accessible by the user
|
// ListRG gets list of all resource groups under specified account, accessible by the user
|
||||||
func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
|
func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListTemplatesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListTemplatesRequest struct {
|
|||||||
|
|
||||||
// ListTemplates gets list of templates which can be managed by this account
|
// ListTemplates gets list of templates which can be managed by this account
|
||||||
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListVINSRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtIP string `url:"extIp,omitempty" json:"extIp,omitempty"`
|
ExtIP string `url:"extIp,omitempty" json:"extIp,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListVINSRequest struct {
|
|||||||
|
|
||||||
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
||||||
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -53,6 +53,9 @@ type ItemAccount struct {
|
|||||||
// Access Control List
|
// Access Control List
|
||||||
ACL []RecordACL `json:"acl"`
|
ACL []RecordACL `json:"acl"`
|
||||||
|
|
||||||
|
// Compute Features
|
||||||
|
ComputeFeatures []string `json:"computeFeatures"`
|
||||||
|
|
||||||
// Created time
|
// Created time
|
||||||
CreatedTime uint64 `json:"createdTime"`
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
@@ -176,6 +179,9 @@ type RecordAccount struct {
|
|||||||
// Company URL
|
// Company URL
|
||||||
CompanyURL string `json:"companyurl"`
|
CompanyURL string `json:"companyurl"`
|
||||||
|
|
||||||
|
// Compute Features
|
||||||
|
ComputeFeatures []string `json:"computeFeatures"`
|
||||||
|
|
||||||
// Computes
|
// Computes
|
||||||
Computes Computes `json:"computes"`
|
Computes Computes `json:"computes"`
|
||||||
|
|
||||||
@@ -374,6 +380,12 @@ type ItemVINS struct {
|
|||||||
// External IP
|
// External IP
|
||||||
ExternalIP string `json:"externalIP"`
|
ExternalIP string `json:"externalIP"`
|
||||||
|
|
||||||
|
// Extnet ID
|
||||||
|
ExtnetId uint64 `json:"extnetId"`
|
||||||
|
|
||||||
|
// Free IPs
|
||||||
|
FreeIPs uint64 `json:"freeIPs"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error)
|
|||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/delete"
|
url := "/cloudapi/bservice/disable"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -74,6 +74,16 @@ type GroupAddRequest struct {
|
|||||||
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r GroupAddRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// GroupAdd creates new Compute Group within BasicService.
|
// GroupAdd creates new Compute Group within BasicService.
|
||||||
// Compute Group is NOT started automatically,
|
// Compute Group is NOT started automatically,
|
||||||
// so you need to explicitly start it
|
// so you need to explicitly start it
|
||||||
|
|||||||
@@ -43,6 +43,16 @@ type GroupUpdateRequest struct {
|
|||||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r GroupUpdateRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// GroupUpdate updates existing Compute group within Basic Service and apply new settings to its computes as necessary
|
// GroupUpdate updates existing Compute group within Basic Service and apply new settings to its computes as necessary
|
||||||
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
|
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of BasicService instances
|
// ListRequest struct to get list of BasicService instances
|
||||||
@@ -40,6 +42,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
AccountName string `url:"accountName,omitempty" json:"accountName,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -51,6 +57,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
||||||
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
||||||
|
|
||||||
res, err := b.ListRaw(ctx, req)
|
res, err := b.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -68,6 +75,11 @@ func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices
|
|||||||
|
|
||||||
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
||||||
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/list"
|
url := "/cloudapi/bservice/list"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list of deleted BasicService instances
|
// ListDeletedRequest struct to get list of deleted BasicService instances
|
||||||
@@ -16,6 +18,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -27,6 +33,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
||||||
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
|
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/listDeleted"
|
url := "/cloudapi/bservice/listDeleted"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -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"`
|
||||||
@@ -168,9 +168,18 @@ type ItemSnapshot struct {
|
|||||||
Valid bool `json:"valid"`
|
Valid bool `json:"valid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of Snapshots
|
// List of Snapshot
|
||||||
type ListSnapshots []ItemSnapshot
|
type ListSnapshots []ItemSnapshot
|
||||||
|
|
||||||
|
// List of Snapshots
|
||||||
|
type ListInfoSnapshots struct {
|
||||||
|
// Data
|
||||||
|
Data ListSnapshots `json:"data"`
|
||||||
|
|
||||||
|
// EntryCount
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about Group
|
// Main information about Group
|
||||||
type RecordGroup struct {
|
type RecordGroup struct {
|
||||||
// Account ID
|
// Account ID
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type SnapshotListRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SnapshotList gets list existing snapshots of the Basic Service
|
// SnapshotList gets list existing snapshots of the Basic Service
|
||||||
func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (ListSnapshots, error) {
|
func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (*ListInfoSnapshots, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -29,12 +29,12 @@ func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (Li
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := ListSnapshots{}
|
list := ListInfoSnapshots{}
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
err = json.Unmarshal(res, &list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ type AffinityRuleAddRequest struct {
|
|||||||
|
|
||||||
// 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: false
|
// Required: false
|
||||||
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
Value string `url:"value" json:"value"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ type AffinityRuleRemoveRequest struct {
|
|||||||
|
|
||||||
// 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: false
|
// Required: false
|
||||||
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
Value string `url:"value" json:"value"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ type AntiAffinityRuleAddRequest struct {
|
|||||||
|
|
||||||
// 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: false
|
// Required: false
|
||||||
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
Value string `url:"value" json:"value"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ type AntiAffinityRuleRemoveRequest struct {
|
|||||||
|
|
||||||
// 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: false
|
// Required: false
|
||||||
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
Value string `url:"value" json:"value"`
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
42
pkg/cloudapi/compute/boot_disk_set.go
Normal file
42
pkg/cloudapi/compute/boot_disk_set.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BootDiskSetRequest struct to set boot disk for compute
|
||||||
|
type BootDiskSetRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the disk to set as boot
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BootDiskSet sets boot disk for compute
|
||||||
|
func (c Compute) BootDiskSet(ctx context.Context, req BootDiskSetRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/bootDiskSet"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
112
pkg/cloudapi/compute/create_template_from_blank.go
Normal file
112
pkg/cloudapi/compute/create_template_from_blank.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateTemplateFromBlankRequest struct to create template from boot disk of current compute
|
||||||
|
type CreateTemplateFromBlankRequest struct {
|
||||||
|
// ID of the compute to create template from
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Name of the rescue disk
|
||||||
|
// Required: true
|
||||||
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// Boot type of image BIOS or UEFI
|
||||||
|
// Required: true
|
||||||
|
BootType string `url:"boottype" json:"boottype" validate:"imageBootType"`
|
||||||
|
|
||||||
|
// Image type linux, windows or other
|
||||||
|
// Required: true
|
||||||
|
ImageType string `url:"imagetype" json:"imagetype" validate:"imageType"`
|
||||||
|
|
||||||
|
// Username for the image
|
||||||
|
// Required: false
|
||||||
|
Username string `url:"username,omitempty" json:"username,omitempty"`
|
||||||
|
|
||||||
|
// Password for the image
|
||||||
|
// Required: false
|
||||||
|
Password string `url:"password,omitempty" json:"password,omitempty"`
|
||||||
|
|
||||||
|
// Account ID to make the image exclusive
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
|
|
||||||
|
// SEP ID
|
||||||
|
// Required: false
|
||||||
|
SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Pool for image create
|
||||||
|
// Required: false
|
||||||
|
PoolName string `url:"poolName,omitempty" json:"poolName,omitempty"`
|
||||||
|
|
||||||
|
// Does this machine supports hot resize
|
||||||
|
// Default: false
|
||||||
|
// Required: false
|
||||||
|
HotResize bool `url:"hotresize" json:"hotresize"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wrapperCreateTemplateFromBlankRequest struct {
|
||||||
|
CreateTemplateFromBlankRequest
|
||||||
|
AsyncMode bool `url:"asyncMode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateTemplateFromBlank creates template from boot disk of current compute in sync mode.
|
||||||
|
// It returns id of created compute and error.
|
||||||
|
func (c Compute) CreateTemplateFromBlank(ctx context.Context, req CreateTemplateFromBlankRequest) (uint64, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
reqWrapped := wrapperCreateTemplateFromBlankRequest{
|
||||||
|
CreateTemplateFromBlankRequest: req,
|
||||||
|
AsyncMode: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/createTemplateFromBlank"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseUint(string(res), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateTemplateFromBlankAsync creates template from boot disk of current compute in async mode.
|
||||||
|
// It returns guid of task and error.
|
||||||
|
func (c Compute) CreateTemplateFromBlankAsync(ctx context.Context, req CreateTemplateFromBlankRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
reqWrapped := wrapperCreateTemplateFromBlankRequest{
|
||||||
|
CreateTemplateFromBlankRequest: req,
|
||||||
|
AsyncMode: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/createTemplateFromBlank"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := strings.ReplaceAll(string(res), "\"", "")
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
53
pkg/cloudapi/compute/disk_migrate.go
Normal file
53
pkg/cloudapi/compute/disk_migrate.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiskMigrateRequest struct to migrate compute's disk to target disk
|
||||||
|
type DiskMigrateRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// ID source disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// ID target disk
|
||||||
|
// Required: true
|
||||||
|
TargetDiskID uint64 `url:"targetDiskId" json:"targetDiskId" validate:"required"`
|
||||||
|
|
||||||
|
// Migration mode. 1 - Data migration and domain update were already completed by third-party software.
|
||||||
|
// Use this if target disk already connected to compute and you only need to save changes for next reboot.
|
||||||
|
// Required: true
|
||||||
|
Mode int64 `url:"mode" json:"mode" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiskMigrate - migrate compute's disk to target disk. Source disk will be detached, target disk will be attached to the same PCI slot.
|
||||||
|
// (WARNING) Current realisation is limited. No actual data migration will be performed.
|
||||||
|
// Use this API if target disk already connected to compute and you only need to save changes for next reboot (mode: 1).
|
||||||
|
func (c Compute) DiskMigrate(ctx context.Context, req DiskMigrateRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/diskMigrate"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
46
pkg/cloudapi/compute/disk_switch_to_replication.go
Normal file
46
pkg/cloudapi/compute/disk_switch_to_replication.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiskSwitchToReplicationRequest struct to switch disk to it's replication
|
||||||
|
type DiskSwitchToReplicationRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the disk to switch
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Delete replication relationship
|
||||||
|
// Required: false
|
||||||
|
StopReplication bool `url:"stopReplication" json:"stopReplication"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiskSwitchToReplication switches disk to it's replication
|
||||||
|
func (c Compute) DiskSwitchToReplication(ctx context.Context, req DiskSwitchToReplicationRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/diskSwitchToReplication"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of available computes
|
// ListRequest struct to get list of available computes
|
||||||
@@ -52,6 +54,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -64,6 +70,7 @@ type ListRequest struct {
|
|||||||
// List gets list of the available computes.
|
// List gets list of the available computes.
|
||||||
// Filtering based on status is possible
|
// Filtering based on status is possible
|
||||||
func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, error) {
|
func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
res, err := c.ListRaw(ctx, req)
|
res, err := c.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -81,6 +88,11 @@ func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, erro
|
|||||||
|
|
||||||
// ListRaw gets list of the available computes.
|
// ListRaw gets list of the available computes.
|
||||||
func (c Compute) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (c Compute) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/list"
|
url := "/cloudapi/compute/list"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get deleted computes list
|
// ListDeletedRequest struct to get deleted computes list
|
||||||
@@ -44,6 +46,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -55,6 +61,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list all deleted computes
|
// ListDeleted gets list all deleted computes
|
||||||
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListComputes, error) {
|
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/listDeleted"
|
url := "/cloudapi/compute/listDeleted"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListPCIDeviceRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListPCIDeviceRequest struct {
|
|||||||
|
|
||||||
// ListPCIDevice gets list PCI device
|
// ListPCIDevice gets list PCI device
|
||||||
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) (*ListPCIDevices, error) {
|
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) (*ListPCIDevices, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ type ListVGPURequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListVGPURequest struct {
|
|||||||
|
|
||||||
// ListVGPU gets list vGPU
|
// ListVGPU gets list vGPU
|
||||||
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) (*ListVGPUs, error) {
|
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) (*ListVGPUs, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -305,6 +305,9 @@ type RecordCompute 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"`
|
||||||
|
|
||||||
@@ -314,6 +317,9 @@ type RecordCompute struct {
|
|||||||
// Compute CI ID
|
// Compute CI ID
|
||||||
ComputeCIID uint64 `json:"computeciId"`
|
ComputeCIID uint64 `json:"computeciId"`
|
||||||
|
|
||||||
|
// CPU Pin
|
||||||
|
CPUPin bool `json:"cpupin"`
|
||||||
|
|
||||||
// Number of cores
|
// Number of cores
|
||||||
CPU uint64 `json:"cpus"`
|
CPU uint64 `json:"cpus"`
|
||||||
|
|
||||||
@@ -350,6 +356,9 @@ type RecordCompute struct {
|
|||||||
// GUID
|
// GUID
|
||||||
GUID uint64 `json:"guid"`
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HPBacked
|
||||||
|
HPBacked bool `json:"hpBacked"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
@@ -380,6 +389,15 @@ type RecordCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NeedReboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
|
// Numa Affinity
|
||||||
|
NumaAffinity string `json:"numaAffinity"`
|
||||||
|
|
||||||
|
//NumaNodeId
|
||||||
|
NumaNodeId int64 `json:"numaNodeId"`
|
||||||
|
|
||||||
// Natable VINS ID
|
// Natable VINS ID
|
||||||
NatableVINSID uint64 `json:"natableVinsId"`
|
NatableVINSID uint64 `json:"natableVinsId"`
|
||||||
|
|
||||||
@@ -536,6 +554,9 @@ type ItemVNFInterface struct {
|
|||||||
// Network type
|
// Network type
|
||||||
NetType string `json:"netType"`
|
NetType string `json:"netType"`
|
||||||
|
|
||||||
|
// NodeID
|
||||||
|
NodeID int64 `json:"nodeId"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot int64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
@@ -651,6 +672,9 @@ type ItemComputeDisk struct {
|
|||||||
// Reality device number
|
// Reality device number
|
||||||
RealityDeviceNumber uint64 `json:"realityDeviceNumber"`
|
RealityDeviceNumber uint64 `json:"realityDeviceNumber"`
|
||||||
|
|
||||||
|
// Replication
|
||||||
|
Replication interface{} `json:"replication"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
@@ -758,6 +782,7 @@ type IOTune struct {
|
|||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
// Access Control List
|
// Access Control List
|
||||||
ACL ListACL `json:"acl"`
|
ACL ListACL `json:"acl"`
|
||||||
|
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64 `json:"accountId"`
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
@@ -785,6 +810,9 @@ type ItemCompute 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"`
|
||||||
|
|
||||||
@@ -794,6 +822,9 @@ type ItemCompute struct {
|
|||||||
// Compute CI ID
|
// Compute CI ID
|
||||||
ComputeCIID uint64 `json:"computeciId"`
|
ComputeCIID uint64 `json:"computeciId"`
|
||||||
|
|
||||||
|
// CPU Pin
|
||||||
|
CPUPin bool `json:"cpupin"`
|
||||||
|
|
||||||
// Number of cores
|
// Number of cores
|
||||||
CPU uint64 `json:"cpus"`
|
CPU uint64 `json:"cpus"`
|
||||||
|
|
||||||
@@ -830,6 +861,9 @@ type ItemCompute struct {
|
|||||||
// GUID
|
// GUID
|
||||||
GUID uint64 `json:"guid"`
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HPBacked
|
||||||
|
HPBacked bool `json:"hpBacked"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
@@ -857,6 +891,15 @@ type ItemCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NeedReboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
|
// Numa Affinity
|
||||||
|
NumaAffinity string `json:"numaAffinity"`
|
||||||
|
|
||||||
|
//NumaNodeId
|
||||||
|
NumaNodeId int64 `json:"numaNodeId"`
|
||||||
|
|
||||||
// Pinned or not
|
// Pinned or not
|
||||||
Pinned bool `json:"pinned"`
|
Pinned bool `json:"pinned"`
|
||||||
|
|
||||||
@@ -942,17 +985,106 @@ type ListComputes struct {
|
|||||||
// List VGPUs
|
// List VGPUs
|
||||||
type ListVGPUs struct {
|
type ListVGPUs struct {
|
||||||
// Data
|
// Data
|
||||||
Data []interface{} `json:"data"`
|
Data []ItemVGPU `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Main information about vgpu device
|
||||||
|
type ItemVGPU struct {
|
||||||
|
// Account ID
|
||||||
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
|
// Created Time
|
||||||
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// Deleted Time
|
||||||
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// GID
|
||||||
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Last Claimed By
|
||||||
|
LastClaimedBy uint64 `json:"lastClaimedBy"`
|
||||||
|
|
||||||
|
// Last Update Time
|
||||||
|
LastUpdateTime uint64 `json:"lastUpdateTime"`
|
||||||
|
|
||||||
|
// Mode
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
|
||||||
|
// PCI Slot
|
||||||
|
PCISlot uint64 `json:"pciSlot"`
|
||||||
|
|
||||||
|
// PGPUID
|
||||||
|
PGPUID uint64 `json:"pgpuid"`
|
||||||
|
|
||||||
|
// Profile ID
|
||||||
|
ProfileID uint64 `json:"profileId"`
|
||||||
|
|
||||||
|
// RAM
|
||||||
|
RAM uint64 `json:"ram"`
|
||||||
|
|
||||||
|
// Reference ID
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
|
// RG ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Type
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// VM ID
|
||||||
|
VMID uint64 `json:"vmid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main information about PCI device
|
||||||
|
type ItemPCIDevice struct {
|
||||||
|
// Compute ID
|
||||||
|
ComputeID uint64 `json:"computeId"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"description"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HwPath
|
||||||
|
HwPath string `json:"hwPath"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Name
|
||||||
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Resource group ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// Stack ID
|
||||||
|
StackID uint64 `json:"stackId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// System name
|
||||||
|
SystemName string `json:"systemName"`
|
||||||
|
}
|
||||||
|
|
||||||
// List PCI devices
|
// List PCI devices
|
||||||
type ListPCIDevices struct {
|
type ListPCIDevices struct {
|
||||||
// Data
|
// Data
|
||||||
Data []interface{} `json:"data"`
|
Data []ItemPCIDevice `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ type PFWAddRequest struct {
|
|||||||
PublicPortEnd int64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
PublicPortEnd int64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
||||||
|
|
||||||
// Internal base port number
|
// Internal base port number
|
||||||
// Required: true
|
// Required: false
|
||||||
LocalBasePort uint64 `url:"localBasePort" json:"localBasePort" validate:"required"`
|
LocalBasePort uint64 `url:"localBasePort,omitempty" json:"localBasePort,omitempty"`
|
||||||
|
|
||||||
// Network protocol
|
// Network protocol
|
||||||
// either "tcp" or "udp"
|
// either "tcp" or "udp"
|
||||||
|
|||||||
@@ -29,6 +29,16 @@ type ResizeRequest struct {
|
|||||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r ResizeRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// Resize resizes compute instance
|
// Resize resizes compute instance
|
||||||
func (c Compute) Resize(ctx context.Context, req ResizeRequest) (bool, error) {
|
func (c Compute) Resize(ctx context.Context, req ResizeRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
|
|||||||
127
pkg/cloudapi/disks/from_platform_disk.go
Normal file
127
pkg/cloudapi/disks/from_platform_disk.go
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FromPlatformDiskRequest struct to create template from platform disk
|
||||||
|
type FromPlatformDiskRequest struct {
|
||||||
|
// ID of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Name of the rescue disk
|
||||||
|
// Required: true
|
||||||
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// Boot type of image BIOS or UEFI
|
||||||
|
// Required: true
|
||||||
|
BootType string `url:"boottype" json:"boottype" validate:"imageBootType"`
|
||||||
|
|
||||||
|
// Image type linux, windows or other
|
||||||
|
// Required: true
|
||||||
|
ImageType string `url:"imagetype" json:"imagetype" validate:"imageType"`
|
||||||
|
|
||||||
|
// Binary architecture of this image
|
||||||
|
// Should be:
|
||||||
|
// - X86_64
|
||||||
|
// - PPC64_LE
|
||||||
|
// Required: true
|
||||||
|
Architecture string `url:"architecture" json:"architecture" validate:"imageArchitecture"`
|
||||||
|
|
||||||
|
// Username for the image
|
||||||
|
// Required: false
|
||||||
|
Username string `url:"username,omitempty" json:"username,omitempty"`
|
||||||
|
|
||||||
|
// Password for the image
|
||||||
|
// Required: false
|
||||||
|
Password string `url:"password,omitempty" json:"password,omitempty"`
|
||||||
|
|
||||||
|
// Account ID to make the image exclusive
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
|
|
||||||
|
// SEP ID
|
||||||
|
// Required: false
|
||||||
|
SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Pool for image create
|
||||||
|
// Required: false
|
||||||
|
PoolName string `url:"poolName,omitempty" json:"poolName,omitempty"`
|
||||||
|
|
||||||
|
// List of types of compute suitable for image
|
||||||
|
// Example: [ "KVM_X86" ]
|
||||||
|
// Required: false
|
||||||
|
Drivers []string `url:"drivers" json:"drivers" validate:"min=1,max=2,imageDrivers"`
|
||||||
|
|
||||||
|
// Does this machine supports hot resize
|
||||||
|
// Required: false
|
||||||
|
HotResize bool `url:"hotresize" json:"hotresize"`
|
||||||
|
|
||||||
|
// Bootable image
|
||||||
|
// Required: true
|
||||||
|
Bootable bool `url:"bootable" json:"bootable"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wrapperFromPlatformDiskRequest struct {
|
||||||
|
FromPlatformDiskRequest
|
||||||
|
AsyncMode bool `url:"asyncMode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPlatformDisk creates template from platform disk in sync mode.
|
||||||
|
// It returns id of created disk and error.
|
||||||
|
func (d Disks) FromPlatformDisk(ctx context.Context, req FromPlatformDiskRequest) (uint64, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/fromPlatformDisk"
|
||||||
|
|
||||||
|
reqWrapped := wrapperFromPlatformDiskRequest{
|
||||||
|
FromPlatformDiskRequest: req,
|
||||||
|
AsyncMode: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseUint(string(res), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPlatformDiskAsync creates template from platform disk in async mode.
|
||||||
|
// It returns guid of task and error.
|
||||||
|
func (d Disks) FromPlatformDiskAsync(ctx context.Context, req FromPlatformDiskRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/fromPlatformDisk"
|
||||||
|
|
||||||
|
reqWrapped := wrapperFromPlatformDiskRequest{
|
||||||
|
FromPlatformDiskRequest: req,
|
||||||
|
AsyncMode: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := strings.ReplaceAll(string(res), "\"", "")
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of disks
|
// ListRequest struct to get list of disks
|
||||||
@@ -48,6 +50,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -59,6 +65,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of the created disks belonging to an account as a ListDisks struct
|
// List gets list of the created disks belonging to an account as a ListDisks struct
|
||||||
func (d Disks) List(ctx context.Context, req ListRequest) (*ListDisks, error) {
|
func (d Disks) List(ctx context.Context, req ListRequest) (*ListDisks, error) {
|
||||||
|
|
||||||
res, err := d.ListRaw(ctx, req)
|
res, err := d.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -76,6 +83,11 @@ func (d Disks) List(ctx context.Context, req ListRequest) (*ListDisks, error) {
|
|||||||
|
|
||||||
// ListRaw gets list of the created disks belonging to an account as an array of bytes
|
// ListRaw gets list of the created disks belonging to an account as an array of bytes
|
||||||
func (d Disks) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (d Disks) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/list"
|
url := "/cloudapi/disks/list"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list of deleted disks
|
// ListDeletedRequest struct to get list of deleted disks
|
||||||
@@ -36,6 +38,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list the deleted disks belonging to an account
|
// ListDeleted gets list the deleted disks belonging to an account
|
||||||
func (d Disks) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListDisks, error) {
|
func (d Disks) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListDisks, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/listDeleted"
|
url := "/cloudapi/disks/listDeleted"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,13 +4,19 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListTypesRequest struct to get list types of disks
|
// ListTypesRequest struct to get list types of disks
|
||||||
type ListTypesRequest struct {
|
type ListTypesRequest struct {
|
||||||
// Show detailed disk types by seps
|
// Show detailed disk types by seps
|
||||||
// Required: true
|
// Required: true
|
||||||
Detailed bool `url:"detailed" json:"detailed" validate:"required"`
|
Detailed bool `url:"detailed" json:"detailed"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -23,6 +29,11 @@ type ListTypesRequest struct {
|
|||||||
|
|
||||||
// ListTypes gets list defined disk types
|
// ListTypes gets list defined disk types
|
||||||
func (d Disks) ListTypes(ctx context.Context, req ListTypesRequest) (*ListTypes, error) {
|
func (d Disks) ListTypes(ctx context.Context, req ListTypesRequest) (*ListTypes, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/listTypes"
|
url := "/cloudapi/disks/listTypes"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListUnattachedRequest struct to get list of unattached disk
|
// ListUnattachedRequest struct to get list of unattached disk
|
||||||
@@ -40,6 +42,10 @@ type ListUnattachedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -51,6 +57,11 @@ type ListUnattachedRequest struct {
|
|||||||
|
|
||||||
// ListUnattached gets list of unattached disks
|
// ListUnattached gets list of unattached disks
|
||||||
func (d Disks) ListUnattached(ctx context.Context, req ListUnattachedRequest) (*ListDisksUnattached, error) {
|
func (d Disks) ListUnattached(ctx context.Context, req ListUnattachedRequest) (*ListDisksUnattached, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/disks/listUnattached"
|
url := "/cloudapi/disks/listUnattached"
|
||||||
|
|
||||||
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -74,6 +74,9 @@ type ItemDisk struct {
|
|||||||
// Purge time
|
// Purge time
|
||||||
PurgeTime uint64 `json:"purgeTime"`
|
PurgeTime uint64 `json:"purgeTime"`
|
||||||
|
|
||||||
|
// Replication
|
||||||
|
Replication interface{} `json:"replication"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
@@ -403,6 +406,9 @@ type RecordDisk struct {
|
|||||||
// Purge time
|
// Purge time
|
||||||
PurgeTime uint64 `json:"purgeTime"`
|
PurgeTime uint64 `json:"purgeTime"`
|
||||||
|
|
||||||
|
// Replication
|
||||||
|
Replication interface{} `json:"replication"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
|
|||||||
52
pkg/cloudapi/disks/replicate.go
Normal file
52
pkg/cloudapi/disks/replicate.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicateRequest struct to create an empty disk in chosen SEP and pool combination.
|
||||||
|
type ReplicateRequest struct {
|
||||||
|
// Id of the disk to replicate. This disk will become master in replication
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Name of replica disk to create
|
||||||
|
// Required: true
|
||||||
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// ID of SEP to create slave disk
|
||||||
|
// Required: true
|
||||||
|
SepID uint64 `url:"sepId" json:"sepId" validate:"required"`
|
||||||
|
|
||||||
|
// Pool name to create slave disk in
|
||||||
|
// Required: true
|
||||||
|
PoolName string `url:"poolName" json:"poolName" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create an empty disk in chosen SEP and pool combination.
|
||||||
|
// Starts replication between chosen disk and newly created disk
|
||||||
|
// Note: only TATLIN type SEP are supported for replications between
|
||||||
|
func (d Disks) Replicate(ctx context.Context, req ReplicateRequest) (uint64, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicate"
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseUint(string(res), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
38
pkg/cloudapi/disks/replication_resume.go
Normal file
38
pkg/cloudapi/disks/replication_resume.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationResume struct to resume suspended replication
|
||||||
|
type ReplicationResumeRequest struct {
|
||||||
|
// Id of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationResume resume suspended replication
|
||||||
|
func (d Disks) ReplicationResume(ctx context.Context, req ReplicationResumeRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationResume"
|
||||||
|
|
||||||
|
res, err := d.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
|
||||||
|
}
|
||||||
38
pkg/cloudapi/disks/replication_reverse.go
Normal file
38
pkg/cloudapi/disks/replication_reverse.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationReverseRequest struct to change role between disks replications
|
||||||
|
type ReplicationReverseRequest struct {
|
||||||
|
// Id of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationReverse change role between disks replications
|
||||||
|
func (d Disks) ReplicationReverse(ctx context.Context, req ReplicationReverseRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationReverse"
|
||||||
|
|
||||||
|
res, err := d.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
|
||||||
|
}
|
||||||
43
pkg/cloudapi/disks/replication_start.go
Normal file
43
pkg/cloudapi/disks/replication_start.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationStartRequest struct to starts replication between two chosen disks
|
||||||
|
type ReplicationStartRequest struct {
|
||||||
|
// Id of the disk to replicate. Primary disk in replication
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// ID of target disk. Secondary disk in replication
|
||||||
|
// Required: true
|
||||||
|
TargetDiskID uint64 `url:"targetDiskId" json:"targetDiskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationStart starts replication between two chosen disks. It's required for both disks to have same size to avoid replication conflicts
|
||||||
|
// Note: Source disk's SEP and target SEP supported only of TATLIN type.
|
||||||
|
func (d Disks) ReplicationStart(ctx context.Context, req ReplicationStartRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationStart"
|
||||||
|
|
||||||
|
res, err := d.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
|
||||||
|
}
|
||||||
37
pkg/cloudapi/disks/replication_status.go
Normal file
37
pkg/cloudapi/disks/replication_status.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationStatusRequest struct to get replication status
|
||||||
|
type ReplicationStatusRequest struct {
|
||||||
|
// Id of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationStatus get replication status
|
||||||
|
func (d Disks) ReplicationStatus(ctx context.Context, req ReplicationStatusRequest) (interface{}, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationStatus"
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// result, err := strconv.ParseBool(string(res))
|
||||||
|
// if err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
38
pkg/cloudapi/disks/replication_stop.go
Normal file
38
pkg/cloudapi/disks/replication_stop.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationStopRequest struct to remove replication between disks completely
|
||||||
|
type ReplicationStopRequest struct {
|
||||||
|
// Id of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationStop remove replication between disks completely
|
||||||
|
func (d Disks) ReplicationStop(ctx context.Context, req ReplicationStopRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationStop"
|
||||||
|
|
||||||
|
res, err := d.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
|
||||||
|
}
|
||||||
38
pkg/cloudapi/disks/replication_suspend.go
Normal file
38
pkg/cloudapi/disks/replication_suspend.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplicationSuspendRequest struct to pause replication with possibility to resume from pause moment
|
||||||
|
type ReplicationSuspendRequest struct {
|
||||||
|
// Id of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplicationSuspend pause replication with possibility to resume from pause moment
|
||||||
|
func (d Disks) ReplicationSuspend(ctx context.Context, req ReplicationSuspendRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/replicationSuspend"
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -18,6 +18,14 @@ type SearchRequest struct {
|
|||||||
// If false, then disks having one of the statuses are not listed
|
// If false, then disks having one of the statuses are not listed
|
||||||
// Required: false
|
// Required: false
|
||||||
ShowAll bool `url:"show_all,omitempty" json:"show_all,omitempty"`
|
ShowAll bool `url:"show_all,omitempty" json:"show_all,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Search searches disks
|
// Search searches disks
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of external network
|
// ListRequest struct to get list of external network
|
||||||
@@ -36,6 +38,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of all available external networks as a ListExtNets struct
|
// List gets list of all available external networks as a ListExtNets struct
|
||||||
func (e ExtNet) List(ctx context.Context, req ListRequest) (*ListExtNets, error) {
|
func (e ExtNet) List(ctx context.Context, req ListRequest) (*ListExtNets, error) {
|
||||||
|
|
||||||
res, err := e.ListRaw(ctx, req)
|
res, err := e.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -64,6 +71,11 @@ func (e ExtNet) List(ctx context.Context, req ListRequest) (*ListExtNets, error)
|
|||||||
|
|
||||||
// ListRaw gets list of all available external networks as an array of bytes
|
// ListRaw gets list of all available external networks as an array of bytes
|
||||||
func (e ExtNet) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (e ExtNet) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/extnet/list"
|
url := "/cloudapi/extnet/list"
|
||||||
|
|
||||||
res, err := e.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := e.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ type ListComputesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ComputeID uint64 `url:"computeId,omitempty" json:"computeId,omitempty"`
|
ComputeID uint64 `url:"computeId,omitempty" json:"computeId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -33,6 +37,7 @@ type ListComputesRequest struct {
|
|||||||
|
|
||||||
// ListComputes gets computes from account with extnets
|
// ListComputes gets computes from account with extnets
|
||||||
func (e ExtNet) ListComputes(ctx context.Context, req ListComputesRequest) (*ListExtNetComputes, error) {
|
func (e ExtNet) ListComputes(ctx context.Context, req ListComputesRequest) (*ListExtNetComputes, 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))
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of FLIPGroup available to the current user
|
// ListRequest struct to get list of FLIPGroup available to the current user
|
||||||
@@ -28,6 +30,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ByIP string `url:"byIp,omitempty" json:"byIp,omitempty"`
|
ByIP string `url:"byIp,omitempty" json:"byIp,omitempty"`
|
||||||
|
|
||||||
|
// Find by accountId
|
||||||
|
// Required: false
|
||||||
|
AccountId uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
||||||
|
|
||||||
// Find by resource group ID
|
// Find by resource group ID
|
||||||
// Required: false
|
// Required: false
|
||||||
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||||
@@ -43,10 +49,23 @@ type ListRequest struct {
|
|||||||
// Page size
|
// Page size
|
||||||
// Required: false
|
// Required: false
|
||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
|
// Find by connId
|
||||||
|
// Required: false
|
||||||
|
ConnId uint64 `url:"connId,omitempty" json:"connId,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List gets list of FLIPGroup managed cluster instances available to the current user as a ListFLIPGroups struct
|
// List gets list of FLIPGroup managed cluster instances available to the current user as a ListFLIPGroups struct
|
||||||
func (f FLIPGroup) List(ctx context.Context, req ListRequest) (*ListFLIPGroups, error) {
|
func (f FLIPGroup) List(ctx context.Context, req ListRequest) (*ListFLIPGroups, error) {
|
||||||
|
|
||||||
res, err := f.ListRaw(ctx, req)
|
res, err := f.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -64,6 +83,11 @@ func (f FLIPGroup) List(ctx context.Context, req ListRequest) (*ListFLIPGroups,
|
|||||||
|
|
||||||
// ListRaw gets list of FLIPGroup managed cluster instances available to the current user as an array of bytes
|
// ListRaw gets list of FLIPGroup managed cluster instances available to the current user as an array of bytes
|
||||||
func (f FLIPGroup) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (f FLIPGroup) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/flipgroup/list"
|
url := "/cloudapi/flipgroup/list"
|
||||||
|
|
||||||
res, err := f.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := f.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -18,10 +18,6 @@ type CreateRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
URL string `url:"url" json:"url" validate:"required,url"`
|
URL string `url:"url" json:"url" validate:"required,url"`
|
||||||
|
|
||||||
// Grid (platform) ID where this template should be create in
|
|
||||||
// Required: true
|
|
||||||
GID uint64 `url:"gid" json:"gid" validate:"required"`
|
|
||||||
|
|
||||||
// Boot type of image bios or UEFI
|
// Boot type of image bios or UEFI
|
||||||
// Required: true
|
// Required: true
|
||||||
BootType string `url:"boottype" json:"boottype" validate:"required,imageBootType"`
|
BootType string `url:"boottype" json:"boottype" validate:"required,imageBootType"`
|
||||||
@@ -34,6 +30,17 @@ type CreateRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
ImageType string `url:"imagetype" json:"imagetype" validate:"required,imageType"`
|
ImageType string `url:"imagetype" json:"imagetype" validate:"required,imageType"`
|
||||||
|
|
||||||
|
// Account ID to make the image exclusive
|
||||||
|
// Required: true
|
||||||
|
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
|
||||||
|
// Select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming
|
||||||
|
// Should be:
|
||||||
|
// - eth
|
||||||
|
// - ens (default value)
|
||||||
|
// Required: false
|
||||||
|
NetworkInterfaceNaming string `url:"networkInterfaceNaming,omitempty" json:"networkInterfaceNaming,omitempty" validate:"omitempty,networkInterfaceNaming"`
|
||||||
|
|
||||||
// Does this machine supports hot resize
|
// Does this machine supports hot resize
|
||||||
// Required: false
|
// Required: false
|
||||||
HotResize bool `url:"hotresize,omitempty" json:"hotresize,omitempty"`
|
HotResize bool `url:"hotresize,omitempty" json:"hotresize,omitempty"`
|
||||||
@@ -46,10 +53,6 @@ type CreateRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Password string `url:"password,omitempty" json:"password,omitempty"`
|
Password string `url:"password,omitempty" json:"password,omitempty"`
|
||||||
|
|
||||||
// Account ID to make the image exclusive
|
|
||||||
// Required: false
|
|
||||||
AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`
|
|
||||||
|
|
||||||
// Username for upload binary media
|
// Username for upload binary media
|
||||||
// Required: false
|
// Required: false
|
||||||
UsernameDL string `url:"usernameDL,omitempty" json:"usernameDL,omitempty"`
|
UsernameDL string `url:"usernameDL,omitempty" json:"usernameDL,omitempty"`
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of available images
|
// ListRequest struct to get list of available images
|
||||||
@@ -56,6 +58,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Bootable bool `url:"bootable,omitempty" json:"bootable,omitempty"`
|
Bootable bool `url:"bootable,omitempty" json:"bootable,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -67,6 +73,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of available images as a ListImages struct, optionally filtering by account ID
|
// List gets list of available images as a ListImages struct, optionally filtering by account ID
|
||||||
func (i Image) List(ctx context.Context, req ListRequest) (*ListImages, error) {
|
func (i Image) List(ctx context.Context, req ListRequest) (*ListImages, error) {
|
||||||
|
|
||||||
res, err := i.ListRaw(ctx, req)
|
res, err := i.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -84,6 +91,11 @@ func (i Image) List(ctx context.Context, req ListRequest) (*ListImages, error) {
|
|||||||
|
|
||||||
// ListRaw gets list of available images as an array of bytes
|
// ListRaw gets list of available images as an array of bytes
|
||||||
func (i Image) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (i Image) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/image/list"
|
url := "/cloudapi/image/list"
|
||||||
|
|
||||||
res, err := i.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := i.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ type ItemImage struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NetworkInterfaceNaming
|
||||||
|
NetworkInterfaceNaming string `json:"networkInterfaceNaming"`
|
||||||
|
|
||||||
// Pool
|
// Pool
|
||||||
Pool string `json:"pool"`
|
Pool string `json:"pool"`
|
||||||
|
|
||||||
@@ -104,6 +107,9 @@ type RecordImage struct {
|
|||||||
// Bootable
|
// Bootable
|
||||||
Bootable bool `json:"bootable"`
|
Bootable bool `json:"bootable"`
|
||||||
|
|
||||||
|
// CdPresentedTo
|
||||||
|
CdPresentedTo interface{} `json:"cdPresentedTo"`
|
||||||
|
|
||||||
// ComputeCI ID
|
// ComputeCI ID
|
||||||
ComputeCIID uint64 `json:"computeciId"`
|
ComputeCIID uint64 `json:"computeciId"`
|
||||||
|
|
||||||
@@ -146,6 +152,9 @@ type RecordImage struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NetworkInterfaceNaming
|
||||||
|
NetworkInterfaceNaming string `json:"networkInterfaceNaming"`
|
||||||
|
|
||||||
// Password
|
// Password
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,15 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of information about images
|
// ListRequest struct to get list of information about images
|
||||||
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
|
||||||
@@ -36,6 +38,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDisabled bool `url:"includeDisabled,omitempty" json:"includeDisabled,omitempty"`
|
IncludeDisabled bool `url:"includeDisabled,omitempty" json:"includeDisabled,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of all k8ci catalog items available to the current user as a ListK8CI struct
|
// List gets list of all k8ci catalog items available to the current user as a ListK8CI struct
|
||||||
func (k K8CI) List(ctx context.Context, req ListRequest) (*ListK8CI, error) {
|
func (k K8CI) List(ctx context.Context, req ListRequest) (*ListK8CI, error) {
|
||||||
|
|
||||||
res, err := k.ListRaw(ctx, req)
|
res, err := k.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -64,6 +71,11 @@ func (k K8CI) List(ctx context.Context, req ListRequest) (*ListK8CI, error) {
|
|||||||
|
|
||||||
// ListRaw gets list of all k8ci catalog items available to the current user as an array of bytes
|
// ListRaw gets list of all k8ci catalog items available to the current user as an array of bytes
|
||||||
func (k K8CI) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (k K8CI) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/k8ci/list"
|
url := "/cloudapi/k8ci/list"
|
||||||
|
|
||||||
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list information about deleted images
|
// ListDeletedRequest struct to get list information about deleted k8ci items
|
||||||
type ListDeletedRequest struct {
|
type ListDeletedRequest struct {
|
||||||
// Find by ID
|
// Find by ID
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -28,6 +30,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
NetworkPlugins string `url:"netPlugins,omitempty" json:"netPlugins,omitempty"`
|
NetworkPlugins string `url:"netPlugins,omitempty" json:"netPlugins,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -39,6 +45,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list all deleted k8ci catalog items available to the current user
|
// ListDeleted gets list all deleted k8ci catalog items available to the current user
|
||||||
func (k K8CI) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListK8CI, error) {
|
func (k K8CI) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListK8CI, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/k8ci/listDeleted"
|
url := "/cloudapi/k8ci/listDeleted"
|
||||||
|
|
||||||
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// type Params []string
|
|
||||||
|
|
||||||
// CreateRequest struct to create kubernetes cluster
|
// CreateRequest struct to create kubernetes cluster
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// Name of Kubernetes cluster
|
// Name of Kubernetes cluster
|
||||||
@@ -29,7 +27,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"`
|
||||||
|
|
||||||
@@ -74,7 +72,7 @@ type CreateRequest struct {
|
|||||||
|
|
||||||
// Master node RAM volume in MB
|
// Master node RAM volume in MB
|
||||||
// Required: false
|
// Required: false
|
||||||
MasterRAM uint `url:"masterRam,omitempty" json:"masterRam,omitempty"`
|
MasterRAM uint64 `url:"masterRam,omitempty" json:"masterRam,omitempty"`
|
||||||
|
|
||||||
// Master node boot disk size in GB If 0 is specified, size is defined by the OS image size
|
// Master node boot disk size in GB If 0 is specified, size is defined by the OS image size
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -90,7 +88,7 @@ type CreateRequest struct {
|
|||||||
|
|
||||||
// Worker node RAM volume in MB
|
// Worker node RAM volume in MB
|
||||||
// Required: false
|
// Required: false
|
||||||
WorkerRAM uint `url:"workerRam,omitempty" json:"workerRam,omitempty"`
|
WorkerRAM uint64 `url:"workerRam,omitempty" json:"workerRam,omitempty"`
|
||||||
|
|
||||||
// Worker node boot disk size in GB. If 0 is specified, size is defined by the OS image size
|
// Worker node boot disk size in GB. If 0 is specified, size is defined by the OS image size
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -111,7 +109,7 @@ type CreateRequest struct {
|
|||||||
|
|
||||||
// Custom sysctl values for Load Balancer instance. Applied on boot
|
// Custom sysctl values for Load Balancer instance. Applied on boot
|
||||||
// Required: false
|
// Required: false
|
||||||
LbSysctlParams string `url:"lbSysctlParams,omitempty" json:"lbSysctlParams,omitempty"`
|
LbSysctlParams []map[string]interface{} `url:"lbSysctlParams,omitempty" json:"lbSysctlParams,omitempty"`
|
||||||
|
|
||||||
// Use Highly Available schema for LB deploy
|
// Use Highly Available schema for LB deploy
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -166,10 +164,16 @@ type CreateRequest struct {
|
|||||||
OidcCertificate string `url:"oidcCertificate,omitempty" json:"oidcCertificate,omitempty"`
|
OidcCertificate string `url:"oidcCertificate,omitempty" json:"oidcCertificate,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// type wrapperCreateRequest struct {
|
// GetRAM returns RAM field values
|
||||||
// CreateRequest
|
func (r CreateRequest) GetRAM() map[string]uint64 {
|
||||||
// Params []string `url:"lbSysctlParams,omitempty"`
|
|
||||||
// }
|
res := make(map[string]uint64, 2)
|
||||||
|
|
||||||
|
res["MasterRAM"] = r.MasterRAM
|
||||||
|
res["WorkerRAM"] = r.WorkerRAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// Create creates a new Kubernetes cluster in the specified Resource Group
|
// Create creates a new Kubernetes cluster in the specified Resource Group
|
||||||
func (k8s K8S) Create(ctx context.Context, req CreateRequest) (string, error) {
|
func (k8s K8S) Create(ctx context.Context, req CreateRequest) (string, error) {
|
||||||
@@ -178,31 +182,9 @@ func (k8s K8S) Create(ctx context.Context, req CreateRequest) (string, error) {
|
|||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
// var params []string
|
|
||||||
|
|
||||||
// if len(req.LbSysctlParams) != 0 {
|
|
||||||
// params = make([]string, 0, len(req.LbSysctlParams))
|
|
||||||
|
|
||||||
// for r := range req.LbSysctlParams {
|
|
||||||
// b, err := json.Marshal(req.LbSysctlParams[r])
|
|
||||||
// if err != nil {
|
|
||||||
// return "", err
|
|
||||||
// }
|
|
||||||
|
|
||||||
// params = append(params, string(b))
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// params = []string{"[]"}
|
|
||||||
// }
|
|
||||||
|
|
||||||
// reqWrapped := wrapperCreateRequest{
|
|
||||||
// CreateRequest: req,
|
|
||||||
// Params: params,
|
|
||||||
// }
|
|
||||||
|
|
||||||
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
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list information K8S
|
// ListRequest struct to get list information K8S
|
||||||
@@ -44,6 +46,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -55,6 +61,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of all kubernetes clusters the user has access to as a ListK8SClusters
|
// List gets list of all kubernetes clusters the user has access to as a ListK8SClusters
|
||||||
func (k8s K8S) List(ctx context.Context, req ListRequest) (*ListK8SClusters, error) {
|
func (k8s K8S) List(ctx context.Context, req ListRequest) (*ListK8SClusters, error) {
|
||||||
|
|
||||||
res, err := k8s.ListRaw(ctx, req)
|
res, err := k8s.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -72,6 +79,11 @@ func (k8s K8S) List(ctx context.Context, req ListRequest) (*ListK8SClusters, err
|
|||||||
|
|
||||||
// ListRaw gets list of all kubernetes clusters the user has access to as an array of bytes
|
// ListRaw gets list of all kubernetes clusters the user has access to as an array of bytes
|
||||||
func (k8s K8S) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (k8s K8S) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/k8s/list"
|
url := "/cloudapi/k8s/list"
|
||||||
|
|
||||||
res, err := k8s.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k8s.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list of deleted kubernetes cluster
|
// ListDeletedRequest struct to get list of deleted kubernetes cluster
|
||||||
@@ -36,6 +38,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
TechStatus string `url:"techStatus,omitempty" json:"techStatus,omitempty"`
|
TechStatus string `url:"techStatus,omitempty" json:"techStatus,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets all deleted kubernetes clusters the user has access to
|
// ListDeleted gets all deleted kubernetes clusters the user has access to
|
||||||
func (k8s K8S) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListK8SClusters, error) {
|
func (k8s K8S) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListK8SClusters, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/k8s/listDeleted"
|
url := "/cloudapi/k8s/listDeleted"
|
||||||
|
|
||||||
res, err := k8s.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := k8s.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -62,6 +62,16 @@ type WorkersGroupAddRequest struct {
|
|||||||
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r WorkersGroupAddRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["WorkerRAM"] = r.WorkerRAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// WorkersGroupAdd adds workers group to Kubernetes cluster
|
// WorkersGroupAdd adds workers group to Kubernetes cluster
|
||||||
func (k8s K8S) WorkersGroupAdd(ctx context.Context, req WorkersGroupAddRequest) (uint64, error) {
|
func (k8s K8S) WorkersGroupAdd(ctx context.Context, req WorkersGroupAddRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
|
|||||||
@@ -26,6 +26,35 @@ type Interface struct {
|
|||||||
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DataDisk detailed struct for DataDisks field in CreateRequest and CreateBlankRequest
|
||||||
|
type DataDisk struct {
|
||||||
|
// Name for disk
|
||||||
|
// Required: true
|
||||||
|
DiskName string `url:"diskName" json:"diskName" validate:"required"`
|
||||||
|
|
||||||
|
// Disk size in GB
|
||||||
|
// Required: true
|
||||||
|
Size uint64 `url:"size" json:"size" validate:"required"`
|
||||||
|
|
||||||
|
// Storage endpoint provider ID
|
||||||
|
// By default the same with boot disk
|
||||||
|
// Required: false
|
||||||
|
SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Pool name
|
||||||
|
// By default will be chosen automatically
|
||||||
|
// Required: false
|
||||||
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Optional description
|
||||||
|
// Required: false
|
||||||
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
|
|
||||||
|
// Specify image id for create disk from template
|
||||||
|
// Required: false
|
||||||
|
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// CreateRequest struct to create KVM PowerPC VM
|
// CreateRequest struct to create KVM PowerPC VM
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// ID of the resource group, which will own this VM
|
// ID of the resource group, which will own this VM
|
||||||
@@ -63,6 +92,12 @@ type CreateRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Slice of structs with data disk description. Each disk has parameters: required - diskName, size; optional - sepId, pool, desc and imageId.
|
||||||
|
// If not specified, compute will be created without disks.
|
||||||
|
// To create compute without disks, pass initialized empty slice .
|
||||||
|
// Required: false
|
||||||
|
DataDisks []DataDisk `url:"-" json:"dataDisks,omitempty" validate:"omitempty,dive"`
|
||||||
|
|
||||||
// Slice of structs with net interface description.
|
// Slice of structs with net interface description.
|
||||||
// If not specified, compute will be created with default interface from RG.
|
// If not specified, compute will be created with default interface from RG.
|
||||||
// To create compute without interfaces, pass initialized empty slice .
|
// To create compute without interfaces, pass initialized empty slice .
|
||||||
@@ -90,9 +125,20 @@ type CreateRequest struct {
|
|||||||
IPAType string `url:"ipaType,omitempty" json:"ipaType,omitempty"`
|
IPAType string `url:"ipaType,omitempty" json:"ipaType,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r CreateRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
type wrapperCreateRequest struct {
|
type wrapperCreateRequest struct {
|
||||||
CreateRequest
|
CreateRequest
|
||||||
Interfaces []string `url:"interfaces,omitempty"`
|
Interfaces []string `url:"interfaces,omitempty"`
|
||||||
|
DataDisks []string `url:"dataDisks,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create creates KVM PowerPC VM based on specified OS image
|
// Create creates KVM PowerPC VM based on specified OS image
|
||||||
@@ -119,9 +165,25 @@ func (k KVMPPC) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
|||||||
interfaces = []string{"[]"}
|
interfaces = []string{"[]"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var dataDisks []string
|
||||||
|
|
||||||
|
if req.DataDisks != nil && len(req.DataDisks) != 0 {
|
||||||
|
dataDisks = make([]string, 0, len(req.DataDisks))
|
||||||
|
|
||||||
|
for i := range req.DataDisks {
|
||||||
|
b, err := json.Marshal(req.DataDisks[i])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dataDisks = append(dataDisks, string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateRequest{
|
reqWrapped := wrapperCreateRequest{
|
||||||
CreateRequest: req,
|
CreateRequest: req,
|
||||||
Interfaces: interfaces,
|
Interfaces: interfaces,
|
||||||
|
DataDisks: dataDisks,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/kvmppc/create"
|
url := "/cloudapi/kvmppc/create"
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ type CreateBlankRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
Pool string `url:"pool" json:"pool" validate:"required"`
|
Pool string `url:"pool" json:"pool" validate:"required"`
|
||||||
|
|
||||||
|
// Slice of structs with data disk description. Each disk has parameters: required - diskName, size; optional - sepId, pool, desc and imageId.
|
||||||
|
// If not specified, compute will be created without disks.
|
||||||
|
// To create compute without disks, pass initialized empty slice .
|
||||||
|
// Required: false
|
||||||
|
DataDisks []DataDisk `url:"-" json:"dataDisks,omitempty" validate:"omitempty,dive"`
|
||||||
|
|
||||||
// Slice of structs with net interface description.
|
// Slice of structs with net interface description.
|
||||||
// If not specified, compute will be created with default interface from RG.
|
// If not specified, compute will be created with default interface from RG.
|
||||||
// To create compute without interfaces, pass initialized empty slice .
|
// To create compute without interfaces, pass initialized empty slice .
|
||||||
@@ -52,9 +58,20 @@ type CreateBlankRequest struct {
|
|||||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r CreateBlankRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
type wrapperCreateBlankRequest struct {
|
type wrapperCreateBlankRequest struct {
|
||||||
CreateBlankRequest
|
CreateBlankRequest
|
||||||
Interfaces []string `url:"interfaces,omitempty"`
|
Interfaces []string `url:"interfaces,omitempty"`
|
||||||
|
DataDisks []string `url:"dataDisks,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateBlank creates KVM PowerPC VM from scratch
|
// CreateBlank creates KVM PowerPC VM from scratch
|
||||||
@@ -81,9 +98,25 @@ func (k KVMPPC) CreateBlank(ctx context.Context, req CreateBlankRequest) (uint64
|
|||||||
interfaces = []string{"[]"}
|
interfaces = []string{"[]"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var dataDisks []string
|
||||||
|
|
||||||
|
if req.DataDisks != nil && len(req.DataDisks) != 0 {
|
||||||
|
dataDisks = make([]string, 0, len(req.DataDisks))
|
||||||
|
|
||||||
|
for i := range req.DataDisks {
|
||||||
|
b, err := json.Marshal(req.DataDisks[i])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dataDisks = append(dataDisks, string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateBlankRequest{
|
reqWrapped := wrapperCreateBlankRequest{
|
||||||
CreateBlankRequest: req,
|
CreateBlankRequest: req,
|
||||||
Interfaces: interfaces,
|
Interfaces: interfaces,
|
||||||
|
DataDisks: dataDisks,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/kvmppc/createBlank"
|
url := "/cloudapi/kvmppc/createBlank"
|
||||||
|
|||||||
@@ -26,6 +26,35 @@ type Interface struct {
|
|||||||
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DataDisk detailed struct for DataDisks field in CreateRequest and CreateBlankRequest
|
||||||
|
type DataDisk struct {
|
||||||
|
// Name for disk
|
||||||
|
// Required: true
|
||||||
|
DiskName string `url:"diskName" json:"diskName" validate:"required"`
|
||||||
|
|
||||||
|
// Disk size in GB
|
||||||
|
// Required: true
|
||||||
|
Size uint64 `url:"size" json:"size" validate:"required"`
|
||||||
|
|
||||||
|
// Storage endpoint provider ID
|
||||||
|
// By default the same with boot disk
|
||||||
|
// Required: false
|
||||||
|
SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`
|
||||||
|
|
||||||
|
// Pool name
|
||||||
|
// By default will be chosen automatically
|
||||||
|
// Required: false
|
||||||
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Optional description
|
||||||
|
// Required: false
|
||||||
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
|
|
||||||
|
// Specify image id for create disk from template
|
||||||
|
// Required: false
|
||||||
|
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// CreateRequest struct to create KVM x86 VM
|
// CreateRequest struct to create KVM x86 VM
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// ID of the resource group, which will own this VM
|
// ID of the resource group, which will own this VM
|
||||||
@@ -63,6 +92,12 @@ type CreateRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
Pool string `url:"pool,omitempty" json:"pool,omitempty"`
|
||||||
|
|
||||||
|
// Slice of structs with data disk description. Each disk has parameters: required - diskName, size; optional - sepId, pool, desc and imageId.
|
||||||
|
// If not specified, compute will be created without disks.
|
||||||
|
// To create compute without disks, pass initialized empty slice .
|
||||||
|
// Required: false
|
||||||
|
DataDisks []DataDisk `url:"-" json:"dataDisks,omitempty" validate:"omitempty,dive"`
|
||||||
|
|
||||||
// Slice of structs with net interface description.
|
// Slice of structs with net interface description.
|
||||||
// If not specified, compute will be created with default interface from RG.
|
// If not specified, compute will be created with default interface from RG.
|
||||||
// To create compute without interfaces, pass initialized empty slice .
|
// To create compute without interfaces, pass initialized empty slice .
|
||||||
@@ -98,9 +133,20 @@ type CreateRequest struct {
|
|||||||
Driver string `url:"driver,omitempty" json:"driver,omitempty" validate:"omitempty,computeDriver"`
|
Driver string `url:"driver,omitempty" json:"driver,omitempty" validate:"omitempty,computeDriver"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r CreateRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
type wrapperCreateRequest struct {
|
type wrapperCreateRequest struct {
|
||||||
CreateRequest
|
CreateRequest
|
||||||
Interfaces []string `url:"interfaces,omitempty"`
|
Interfaces []string `url:"interfaces,omitempty"`
|
||||||
|
DataDisks []string `url:"dataDisks,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create creates KVM x86 VM based on specified OS image
|
// Create creates KVM x86 VM based on specified OS image
|
||||||
@@ -127,9 +173,25 @@ func (k KVMX86) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
|||||||
interfaces = []string{"[]"}
|
interfaces = []string{"[]"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var dataDisks []string
|
||||||
|
|
||||||
|
if req.DataDisks != nil && len(req.DataDisks) != 0 {
|
||||||
|
dataDisks = make([]string, 0, len(req.DataDisks))
|
||||||
|
|
||||||
|
for i := range req.DataDisks {
|
||||||
|
b, err := json.Marshal(req.DataDisks[i])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dataDisks = append(dataDisks, string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateRequest{
|
reqWrapped := wrapperCreateRequest{
|
||||||
CreateRequest: req,
|
CreateRequest: req,
|
||||||
Interfaces: interfaces,
|
Interfaces: interfaces,
|
||||||
|
DataDisks: dataDisks,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/kvmx86/create"
|
url := "/cloudapi/kvmx86/create"
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ type CreateBlankRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
Pool string `url:"pool" json:"pool" validate:"required"`
|
Pool string `url:"pool" json:"pool" validate:"required"`
|
||||||
|
|
||||||
|
// Slice of structs with data disk description. Each disk has parameters: required - diskName, size; optional - sepId, pool, desc and imageId.
|
||||||
|
// If not specified, compute will be created without disks.
|
||||||
|
// To create compute without disks, pass initialized empty slice .
|
||||||
|
// Required: false
|
||||||
|
DataDisks []DataDisk `url:"-" json:"dataDisks,omitempty" validate:"omitempty,dive"`
|
||||||
|
|
||||||
// Slice of structs with net interface description.
|
// Slice of structs with net interface description.
|
||||||
// If not specified, compute will be created with default interface from RG.
|
// If not specified, compute will be created with default interface from RG.
|
||||||
// To create compute without interfaces, pass initialized empty slice .
|
// To create compute without interfaces, pass initialized empty slice .
|
||||||
@@ -56,9 +62,20 @@ type CreateBlankRequest struct {
|
|||||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r CreateBlankRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
type wrapperCreateBlankRequest struct {
|
type wrapperCreateBlankRequest struct {
|
||||||
CreateBlankRequest
|
CreateBlankRequest
|
||||||
Interfaces []string `url:"interfaces,omitempty"`
|
Interfaces []string `url:"interfaces,omitempty"`
|
||||||
|
DataDisks []string `url:"dataDisks,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateBlank creates KVM x86 VM from scratch
|
// CreateBlank creates KVM x86 VM from scratch
|
||||||
@@ -85,9 +102,25 @@ func (k KVMX86) CreateBlank(ctx context.Context, req CreateBlankRequest) (uint64
|
|||||||
interfaces = []string{"[]"}
|
interfaces = []string{"[]"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var dataDisks []string
|
||||||
|
|
||||||
|
if req.DataDisks != nil && len(req.DataDisks) != 0 {
|
||||||
|
dataDisks = make([]string, 0, len(req.DataDisks))
|
||||||
|
|
||||||
|
for i := range req.DataDisks {
|
||||||
|
b, err := json.Marshal(req.DataDisks[i])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dataDisks = append(dataDisks, string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateBlankRequest{
|
reqWrapped := wrapperCreateBlankRequest{
|
||||||
CreateBlankRequest: req,
|
CreateBlankRequest: req,
|
||||||
Interfaces: interfaces,
|
Interfaces: interfaces,
|
||||||
|
DataDisks: dataDisks,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/kvmx86/createBlank"
|
url := "/cloudapi/kvmx86/createBlank"
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Params []string
|
|
||||||
|
|
||||||
// CreateRequest struct to create load balancer
|
// CreateRequest struct to create load balancer
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// ID of the resource group where this load balancer instance will be located
|
// ID of the resource group where this load balancer instance will be located
|
||||||
@@ -33,7 +31,7 @@ type CreateRequest struct {
|
|||||||
|
|
||||||
// Custom sysctl values for Load Balancer instance. Applied on boot
|
// Custom sysctl values for Load Balancer instance. Applied on boot
|
||||||
// Required: false
|
// Required: false
|
||||||
SysctlParams Params `url:"-" json:"sysctlParams,omitempty" validate:"omitempty,dive"`
|
SysctlParams []map[string]interface{} `url:"-" json:"sysctlParams,omitempty" validate:"omitempty,dive"`
|
||||||
|
|
||||||
// Use Highly Available schema for LB deploy
|
// Use Highly Available schema for LB deploy
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -68,14 +66,12 @@ func (l LB) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
|||||||
|
|
||||||
if len(req.SysctlParams) != 0 {
|
if len(req.SysctlParams) != 0 {
|
||||||
params = make([]string, 0, len(req.SysctlParams))
|
params = make([]string, 0, len(req.SysctlParams))
|
||||||
|
for _, m := range req.SysctlParams {
|
||||||
for r := range req.SysctlParams {
|
encodeStr, err := json.Marshal(m)
|
||||||
b, err := json.Marshal(req.SysctlParams[r])
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
params = append(params, string(encodeStr))
|
||||||
params = append(params, string(b))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
params = []string{}
|
params = []string{}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of load balancers
|
// ListRequest struct to get list of load balancers
|
||||||
@@ -18,7 +20,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
|
||||||
@@ -44,6 +46,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -55,6 +61,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of all load balancers as a ListLB struct
|
// List gets list of all load balancers as a ListLB struct
|
||||||
func (l LB) List(ctx context.Context, req ListRequest) (*ListLB, error) {
|
func (l LB) List(ctx context.Context, req ListRequest) (*ListLB, error) {
|
||||||
|
|
||||||
res, err := l.ListRaw(ctx, req)
|
res, err := l.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -72,6 +79,11 @@ func (l LB) List(ctx context.Context, req ListRequest) (*ListLB, error) {
|
|||||||
|
|
||||||
// ListRaw gets list of all load balancers as an array of bytes
|
// ListRaw gets list of all load balancers as an array of bytes
|
||||||
func (l LB) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (l LB) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/lb/list"
|
url := "/cloudapi/lb/list"
|
||||||
|
|
||||||
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list of deleted load balancers
|
// ListDeletedRequest struct to get list of deleted load balancers
|
||||||
@@ -18,7 +20,7 @@ type ListDeletedRequest 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
|
||||||
@@ -36,6 +38,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
BackIP string `url:"backIp,omitempty" json:"backIp,omitempty"`
|
BackIP string `url:"backIp,omitempty" json:"backIp,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list of deleted load balancers
|
// ListDeleted gets list of deleted load balancers
|
||||||
func (l LB) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListLB, error) {
|
func (l LB) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListLB, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/lb/listDeleted"
|
url := "/cloudapi/lb/listDeleted"
|
||||||
|
|
||||||
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -50,6 +50,12 @@ type RecordLB struct {
|
|||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// ManagerId
|
||||||
|
ManagerId uint64 `json:"managerId"`
|
||||||
|
|
||||||
|
// ManagerType
|
||||||
|
ManagerType string `json:"managerType"`
|
||||||
|
|
||||||
// Image ID
|
// Image ID
|
||||||
ImageID uint64 `json:"imageId"`
|
ImageID uint64 `json:"imageId"`
|
||||||
|
|
||||||
@@ -89,6 +95,9 @@ type RecordLB struct {
|
|||||||
// Updated time
|
// Updated time
|
||||||
UpdatedTime uint64 `json:"updatedTime"`
|
UpdatedTime uint64 `json:"updatedTime"`
|
||||||
|
|
||||||
|
// UserManaged
|
||||||
|
UserManaged bool `json:"userManaged"`
|
||||||
|
|
||||||
// VINS ID
|
// VINS ID
|
||||||
VINSID uint64 `json:"vinsId"`
|
VINSID uint64 `json:"vinsId"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ func (l LB) Stop(ctx context.Context, req StopRequest) (bool, error) {
|
|||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/lb/start"
|
url := "/cloudapi/lb/stop"
|
||||||
|
|
||||||
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type UpdateSysctParamsRequest struct {
|
|||||||
|
|
||||||
// Custom sysctl values for Load Balancer instance. Applied on boot
|
// Custom sysctl values for Load Balancer instance. Applied on boot
|
||||||
// Required: true
|
// Required: true
|
||||||
SysctlParams Params `url:"-" json:"sysctlParams" validate:"required,dive"`
|
SysctlParams []map[string]interface{} `url:"-" json:"sysctlParams" validate:"required,dive"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type wrapperUpdateSysctParamsRequest struct {
|
type wrapperUpdateSysctParamsRequest struct {
|
||||||
@@ -26,7 +26,7 @@ type wrapperUpdateSysctParamsRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateSysctParams updates sysct paarams for lb
|
// UpdateSysctParams updates sysct paarams for lb
|
||||||
func (l LB) UpdateSysctParams(ctx context.Context, req UpdateSysctParamsRequest) (bool, error) {
|
func (l LB) UpdateSysctlParams(ctx context.Context, req UpdateSysctParamsRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -36,14 +36,12 @@ func (l LB) UpdateSysctParams(ctx context.Context, req UpdateSysctParamsRequest)
|
|||||||
|
|
||||||
if len(req.SysctlParams) != 0 {
|
if len(req.SysctlParams) != 0 {
|
||||||
params = make([]string, 0, len(req.SysctlParams))
|
params = make([]string, 0, len(req.SysctlParams))
|
||||||
|
for _, m := range req.SysctlParams {
|
||||||
for r := range req.SysctlParams {
|
encodeStr, err := json.Marshal(m)
|
||||||
b, err := json.Marshal(req.SysctlParams[r])
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
params = append(params, string(encodeStr))
|
||||||
params = append(params, string(b))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
params = []string{}
|
params = []string{}
|
||||||
@@ -54,7 +52,7 @@ func (l LB) UpdateSysctParams(ctx context.Context, req UpdateSysctParamsRequest)
|
|||||||
Params: params,
|
Params: params,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/lb/updateSysctParams"
|
url := "/cloudapi/lb/updateSysctlParams"
|
||||||
|
|
||||||
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of locations
|
// ListRequest struct to get list of locations
|
||||||
@@ -31,10 +33,15 @@ type ListRequest struct {
|
|||||||
// Find by code location
|
// Find by code location
|
||||||
// Required: false
|
// Required: false
|
||||||
LocationCode string `url:"locationCode,omitempty" json:"locationCode,omitempty"`
|
LocationCode string `url:"locationCode,omitempty" json:"locationCode,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List gets list of all locations as a ListLocations struct
|
// List gets list of all locations as a ListLocations struct
|
||||||
func (l Locations) List(ctx context.Context, req ListRequest) (*ListLocations, error) {
|
func (l Locations) List(ctx context.Context, req ListRequest) (*ListLocations, error) {
|
||||||
|
|
||||||
res, err := l.ListRaw(ctx, req)
|
res, err := l.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -52,6 +59,11 @@ func (l Locations) List(ctx context.Context, req ListRequest) (*ListLocations, e
|
|||||||
|
|
||||||
// ListRaw gets list of all locations as an array of bytes
|
// ListRaw gets list of all locations as an array of bytes
|
||||||
func (l Locations) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (l Locations) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/locations/list"
|
url := "/cloudapi/locations/list"
|
||||||
|
|
||||||
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := l.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -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"`
|
||||||
|
|
||||||
|
|||||||
8
pkg/cloudapi/pcidevice.go
Normal file
8
pkg/cloudapi/pcidevice.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package cloudapi
|
||||||
|
|
||||||
|
import "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/pcidevice"
|
||||||
|
|
||||||
|
// Accessing the PCI Device method group
|
||||||
|
func (ca *CloudAPI) PCIDevice() *pcidevice.PCIDevice {
|
||||||
|
return pcidevice.New(ca.client)
|
||||||
|
}
|
||||||
10
pkg/cloudapi/pcidevice/ids.go
Normal file
10
pkg/cloudapi/pcidevice/ids.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package pcidevice
|
||||||
|
|
||||||
|
// IDs gets array of PCIDeviceIDs from ListPCIDevices struct
|
||||||
|
func (lpd ListPCIDevices) IDs() []uint64 {
|
||||||
|
res := make([]uint64, 0, len(lpd.Data))
|
||||||
|
for _, lb := range lpd.Data {
|
||||||
|
res = append(res, lb.ID)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
76
pkg/cloudapi/pcidevice/list.go
Normal file
76
pkg/cloudapi/pcidevice/list.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
package pcidevice
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListRequest struct to get list of pci devices
|
||||||
|
type ListRequest struct {
|
||||||
|
// Find by id
|
||||||
|
// Required: false
|
||||||
|
ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by computeId
|
||||||
|
// Required: false
|
||||||
|
ComputeID uint64 `url:"computeId,omitempty" json:"computeId,omitempty"`
|
||||||
|
|
||||||
|
// Find by name
|
||||||
|
// Required: false
|
||||||
|
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||||
|
|
||||||
|
// Find by rgId
|
||||||
|
// Required: false
|
||||||
|
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||||
|
|
||||||
|
// Find by status
|
||||||
|
// Required: false
|
||||||
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List gets list of all pci devices as a ListPCIDevices struct
|
||||||
|
func (p PCIDevice) List(ctx context.Context, req ListRequest) (*ListPCIDevices, error) {
|
||||||
|
|
||||||
|
res, err := p.ListRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
list := ListPCIDevices{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &list)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &list, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRaw gets list of all pci devices as an array of bytes
|
||||||
|
func (p PCIDevice) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/pcidevice/list"
|
||||||
|
|
||||||
|
res, err := p.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
50
pkg/cloudapi/pcidevice/models.go
Normal file
50
pkg/cloudapi/pcidevice/models.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package pcidevice
|
||||||
|
|
||||||
|
// Main information about PCI device
|
||||||
|
type ItemPCIDevice struct {
|
||||||
|
// CKey
|
||||||
|
CKey string `json:"_ckey"`
|
||||||
|
|
||||||
|
// Meta
|
||||||
|
Meta []interface{} `json:"_meta"`
|
||||||
|
|
||||||
|
// Compute ID
|
||||||
|
ComputeID uint64 `json:"computeId"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"description"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HwPath
|
||||||
|
HwPath string `json:"hwPath"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Name
|
||||||
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Resource group ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// Stack ID
|
||||||
|
StackID uint64 `json:"stackId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// System name
|
||||||
|
SystemName string `json:"systemName"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List PCI devices
|
||||||
|
type ListPCIDevices struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemPCIDevice `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
15
pkg/cloudapi/pcidevice/pcidevice.go
Normal file
15
pkg/cloudapi/pcidevice/pcidevice.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package pcidevice
|
||||||
|
|
||||||
|
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
|
||||||
|
// Structure for creating request to PCI device
|
||||||
|
type PCIDevice struct {
|
||||||
|
client interfaces.Caller
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builder for PCI device endpoints
|
||||||
|
func New(client interfaces.Caller) *PCIDevice {
|
||||||
|
return &PCIDevice{
|
||||||
|
client: client,
|
||||||
|
}
|
||||||
|
}
|
||||||
42
pkg/cloudapi/pcidevice/serialize.go
Normal file
42
pkg/cloudapi/pcidevice/serialize.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package pcidevice
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||||
|
//
|
||||||
|
// In order to serialize with indent make sure to follow these guidelines:
|
||||||
|
// - First argument -> prefix
|
||||||
|
// - Second argument -> indent
|
||||||
|
func (l ListPCIDevices) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(l.Data) == 0 {
|
||||||
|
return []byte{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(l, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(l)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize returns JSON-serialized []byte. Used as a wrapper over json.Marshal and json.MarshalIndent functions.
|
||||||
|
//
|
||||||
|
// In order to serialize with indent make sure to follow these guidelines:
|
||||||
|
// - First argument -> prefix
|
||||||
|
// - Second argument -> indent
|
||||||
|
func (i ItemPCIDevice) Serialize(params ...string) (serialization.Serialized, error) {
|
||||||
|
if len(params) > 1 {
|
||||||
|
prefix := params[0]
|
||||||
|
indent := params[1]
|
||||||
|
|
||||||
|
return json.MarshalIndent(i, prefix, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(i)
|
||||||
|
}
|
||||||
@@ -53,3 +53,12 @@ func (lrc ListResourceConsumption) IDs() []uint64 {
|
|||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IDs gets array of ResourceGroupIDs from ListAffinityGroup struct
|
||||||
|
func (lag ListAffinityGroup) IDs() []uint64 {
|
||||||
|
res := make([]uint64, 0, len(lag))
|
||||||
|
for _, ag := range lag {
|
||||||
|
res = append(res, ag.ID)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of resource groups
|
// ListRequest struct to get list of resource groups
|
||||||
@@ -44,6 +46,10 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -55,6 +61,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of all resource groups the user has access to as a ListResourceGroups struct
|
// List gets list of all resource groups the user has access to as a ListResourceGroups struct
|
||||||
func (r RG) List(ctx context.Context, req ListRequest) (*ListResourceGroups, error) {
|
func (r RG) List(ctx context.Context, req ListRequest) (*ListResourceGroups, error) {
|
||||||
|
|
||||||
res, err := r.ListRaw(ctx, req)
|
res, err := r.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -72,6 +79,11 @@ func (r RG) List(ctx context.Context, req ListRequest) (*ListResourceGroups, err
|
|||||||
|
|
||||||
// ListRaw gets list of all resource groups the user has access to as an array of bytes
|
// ListRaw gets list of all resource groups the user has access to as an array of bytes
|
||||||
func (r RG) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (r RG) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/rg/list"
|
url := "/cloudapi/rg/list"
|
||||||
|
|
||||||
res, err := r.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := r.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ type ListComputesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -57,6 +61,7 @@ type ListComputesRequest struct {
|
|||||||
|
|
||||||
// ListComputes gets list of all compute instances under specified resource group, accessible by the user
|
// ListComputes gets list of all compute instances under specified resource group, accessible by the user
|
||||||
func (r RG) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
func (r RG) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, 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))
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list deleted resource groups
|
// ListDeletedRequest struct to get list deleted resource groups
|
||||||
@@ -36,6 +38,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
LockStatus string `url:"lockStatus,omitempty" json:"lockStatus,omitempty"`
|
LockStatus string `url:"lockStatus,omitempty" json:"lockStatus,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -47,6 +53,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list all deleted resource groups the user has access to
|
// ListDeleted gets list all deleted resource groups the user has access to
|
||||||
func (r RG) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListResourceGroups, error) {
|
func (r RG) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListResourceGroups, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/rg/listDeleted"
|
url := "/cloudapi/rg/listDeleted"
|
||||||
|
|
||||||
res, err := r.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := r.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user