Compare commits
1 Commits
v1.8.0
...
1.5.9branc
| Author | SHA1 | Date | |
|---|---|---|---|
| 082f577e17 |
194
CHANGELOG.md
194
CHANGELOG.md
@@ -1,197 +1,7 @@
|
|||||||
## Version 1.8.0
|
## Version 1.5.9
|
||||||
|
|
||||||
### Feature
|
|
||||||
|
|
||||||
#### 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
|
### Bugfix
|
||||||
|
- Refactored clients to fix the problems with retries
|
||||||
|
|
||||||
#### 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
|
|
||||||
829
README.md
829
README.md
@@ -10,65 +10,34 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- Версия 1.3.x Decort-SDK соответствует 3.8.5 версии платформы
|
- Версия 1.3.x Decort-SDK соответствует 3.8.5 версии платформы
|
||||||
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
||||||
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
||||||
- Версия 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-конфигурации)
|
||||||
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
- [Создание клиента](#создание-клиента)
|
||||||
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
||||||
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
- [Создание клиента](#создание-клиента)
|
- [Фильтрация](#фильтрация)
|
||||||
- [Пример](#пример)
|
- [Сортировка](#сортировка)
|
||||||
- [Создание структуры запроса](#создание-структуры-запроса)
|
- [Сериализация](#сериализация)
|
||||||
- [Пример комментариев структуры](#пример-комментариев-структуры)
|
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
||||||
- [Пример создания запроса для развертывания виртуальной машины:](#пример-создания-запроса-для-развертывания-виртуальной-машины)
|
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
||||||
- [Пример выполнения запроса](#пример-выполнения-запроса)
|
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
||||||
- [Пример выполнения GetRaw и ListRaw запросов](#пример-выполнения-getraw-и-listraw-запросов)
|
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
||||||
- [Фильтрация](#фильтрация)
|
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
||||||
- [Использование на примере `compute.FilterByK8SID`:](#использование-на-примере-computefilterbyk8sid)
|
- [Создание legacy клиента](#создание-legacy-клиента)
|
||||||
- [Сортировка](#сортировка)
|
- [Создание структуры запроса](#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)
|
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
@@ -105,9 +74,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
- `Locations` - получение информации о grid площадки;
|
- `Locations` - получение информации о grid площадки;
|
||||||
- `RG` - управление ресурсными группами аккаунта;
|
- `RG` - управление ресурсными группами аккаунта;
|
||||||
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
|
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
|
||||||
- `Stack` - получение информации о вычислительных узлах;
|
|
||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
- `VFPool` - управление пулом виртуальных сетевых функций;
|
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `VINS` - управление виртуальными изолированными сетями.
|
||||||
|
|
||||||
### Cloudbroker
|
### Cloudbroker
|
||||||
@@ -130,15 +97,13 @@ 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);
|
||||||
- `Stack` - получение информации о вычислительных узлах;
|
- `Stack` - получение информации о стеках;
|
||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
- `User` - управление пользователями (индивидуально);
|
- `User` - управление пользователями (индивидуально);
|
||||||
- `VGPU` - управление виртуальными графическими процессорами;
|
- `VGPU` - управление виртуальными графическими процессорами;
|
||||||
- `VFPool` - управление пулом виртуальных сетевых функций;
|
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `VINS` - управление виртуальными изолированными сетями.
|
||||||
|
|
||||||
## Работа с библиотекой
|
## Работа с библиотекой
|
||||||
@@ -146,8 +111,8 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
Алгоритм работы с библиотекой выглядит следующим образом:
|
Алгоритм работы с библиотекой выглядит следующим образом:
|
||||||
|
|
||||||
1. Выполнение одного из действий:
|
1. Выполнение одного из действий:
|
||||||
- настройка конфигурации клиента;
|
- настройка конфигурации клиента;
|
||||||
- парсинг конфигурации из файла.
|
- парсинг конфигурации из файла.
|
||||||
2. Создание клиента.
|
2. Создание клиента.
|
||||||
3. Создание структуры запроса.
|
3. Создание структуры запроса.
|
||||||
4. Выполнение запроса.
|
4. Выполнение запроса.
|
||||||
@@ -189,7 +154,7 @@ func main(){
|
|||||||
|
|
||||||
#### Парсинг конфигурации из файла
|
#### Парсинг конфигурации из файла
|
||||||
|
|
||||||
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigJSON` (или `ParseConfigYAML`) из пакета config.
|
||||||
<br>
|
<br>
|
||||||
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
@@ -200,7 +165,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из JSON-файла
|
// Парсинг конфигурации из JSON-файла
|
||||||
cfg, _ := config.ParseConfigJSON("<PATH>")
|
cfg := config.ParseConfigJSON("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -271,51 +236,47 @@ 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` - для `RG`
|
||||||
- `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/node` - для `Node`
|
- `pkg/cloudbroker/pcidevice` - для `PCIDevice`
|
||||||
- `pkg/cloudbroker/pcidevice` - для `PCIDevice`
|
- `pkg/cloudbroker/rg` - для `RG`
|
||||||
- `pkg/cloudbroker/rg` - для `RG`
|
- `pkg/cloudbroker/sep` - для `SEP`
|
||||||
- `pkg/cloudbroker/sep` - для `SEP`
|
- `pkg/cloudbroker/stack` - для `Stack`
|
||||||
- `pkg/cloudbroker/stack` - для `Stack`
|
- `pkg/cloudbroker/tasks` - для `Tasks`
|
||||||
- `pkg/cloudbroker/tasks` - для `Tasks`
|
- `pkg/cloudbroker/user` - для `User`
|
||||||
- `pkg/cloudbroker/user` - для `User`
|
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
||||||
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
- `pkg/cloudbroker/vins` - для `VINS`
|
||||||
- `pkg/cloudbroker/vfpool` - для `VFPool`
|
|
||||||
- `pkg/cloudbroker/vins` - для `VINS`
|
|
||||||
|
|
||||||
Все поля структуры имеют описание, в которых содержится:
|
Все поля структуры имеют описание, в которых содержится:
|
||||||
|
|
||||||
@@ -451,64 +412,60 @@ func main() {
|
|||||||
|
|
||||||
Чтобы выполнить запрос, необходимо:
|
Чтобы выполнить запрос, необходимо:
|
||||||
|
|
||||||
1. Вызвать у клиента метод, отвечаеющий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, либо `.CloudBroker()`. Данные методы возвращаеют соответствующие структуры, с помощью которых можно совершать запросы.
|
1. Вызвать у клиента метод, отвечаеющий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, либо `.CloudBroker()`. Данные методы возвращаеют соответствующие структуры, с помощью которых можно соверать запросы.
|
||||||
2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия.
|
2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия.
|
||||||
|
|
||||||
Доступные методы для `.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`
|
- `.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`
|
||||||
- `.Node()` - для работы с `Node`
|
- `.PCIDevice()` - для работы с `PCIDevice`
|
||||||
- `.PCIDevice()` - для работы с `PCIDevice`
|
- `.RG()` - для работы с `RG`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.SEP()` - для работы с `SEP`
|
||||||
- `.SEP()` - для работы с `SEP`
|
- `.Stack()` - для работы с `Stack`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.User()` - для работы с `User`
|
||||||
- `.User()` - для работы с `User`
|
- `.VGPU()` - для работы с `VGPU`
|
||||||
- `.VGPU()` - для работы с `VGPU`
|
- `.VINS()` - для работы с `VINS`
|
||||||
- `.VFPool()` - для работы с `VFPool`
|
|
||||||
- `.VINS()` - для работы с `VINS`
|
|
||||||
|
|
||||||
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||||
|
|
||||||
- контекст;
|
- контекст;
|
||||||
- структуру запроса.
|
- структуру запроса.
|
||||||
У каждой группы ручек API имеются свои доступные методы, которые определяются платформой.
|
У кождой группы ручек API имеются свои доступные методы, которые определяются платформой.
|
||||||
|
|
||||||
4. Обработать результат и ошибки.
|
4. Обработать результат и ошибки.
|
||||||
|
|
||||||
@@ -566,56 +523,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Для запросов Get и List реализованы запросы GetRaw и ListRaw, которые возвращают ответ не в виде соответствующей структуры, а в виде массива байт (JSON).
|
|
||||||
Выполнение таких запросов происходит аналогично.
|
|
||||||
|
|
||||||
#### Пример выполнения GetRaw и ListRaw запросов
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
|
||||||
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// Настройка конфигурации
|
|
||||||
cfg := config.Config{
|
|
||||||
AppID: "<APPID>",
|
|
||||||
AppSecret: "<APPSECRET>",
|
|
||||||
SSOURL: "https://sso.digitalenergy.online",
|
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
|
||||||
Retries: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Создание клиента
|
|
||||||
client := decort.New(cfg)
|
|
||||||
|
|
||||||
// 1. Создание структуры запроса GetRequest на получение информации об аккаунте и выполнение GetRaw запроса с помощью конвейера
|
|
||||||
req1 := account.GetRequest{
|
|
||||||
AccountID: 123,
|
|
||||||
}
|
|
||||||
res1, err := client.CloudAPI().Account().GetRaw(context.Background(), req1)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Println(string(res1))
|
|
||||||
|
|
||||||
// 2. Создание структуры запроса ListRequest на получение информации об аккаунтах и выполнение ListRaw запроса с помощью конвейера
|
|
||||||
req2 := account.ListRequest{}
|
|
||||||
res2, err := client.CloudAPI().Account().ListRaw(context.Background(), req2)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Println(string(res2))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Фильтрация
|
### Фильтрация
|
||||||
|
|
||||||
Для каждого `ListRequest` в SDK есть группа функций для фильтрации ответа платформы. Для того чтобы произвести фильтрацию по заданным полям, достаточно описать анонимную функцию (предикат) в `.FilterFunc()`, например:
|
Для каждого `ListRequest` в SDK есть группа функций для фильтрации ответа платформы. Для того чтобы произвести фильтрацию по заданным полям, достаточно описать анонимную функцию (предикат) в `.FilterFunc()`, например:
|
||||||
@@ -673,7 +580,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)
|
||||||
@@ -805,133 +712,6 @@ func main() {
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Получение списка уникальных идентификаторов ID объекта
|
|
||||||
|
|
||||||
Для всех структур, имеющих поля со списками объектов с уникальными числовыми идентификаторами (ID), добавлены методы IDs(), возвращающие массивы уникальных идентификаторов объектов в этих списках.
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
|
||||||
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// Настройка конфигурации
|
|
||||||
cfg := config.Config{
|
|
||||||
AppID: "<APPID>",
|
|
||||||
AppSecret: "<APPSECRET>",
|
|
||||||
SSOURL: "https://sso.digitalenergy.online",
|
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
|
||||||
Retries: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Создание клиента
|
|
||||||
client := decort.New(cfg)
|
|
||||||
|
|
||||||
// Создание структуры запроса GetRequest на получение информации о сервисе и выполнение запроса с помощью конвейера
|
|
||||||
req := bservice.GetRequest{
|
|
||||||
ServiceID: 123,
|
|
||||||
}
|
|
||||||
res, err := client.CloudAPI().BService().Get(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Получение списков ID ComputeIDs и GroupIDs экземпляра res типа RecordBasicService по полям Computes и Groups, соответственно
|
|
||||||
computeIDs := res.Computes.IDs()
|
|
||||||
groupIDs := res.Groups.IDs()
|
|
||||||
fmt.Println(computeIDs)
|
|
||||||
fmt.Println(groupIDs)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Методы поля 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.
|
||||||
@@ -983,7 +763,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Парсинг конфигурации из YAML-файла
|
// Парсинг конфигурации из YAML-файла
|
||||||
legacyCfg, _ := config.ParseLegacyConfigYAML("<PATH>")
|
legacyCfg := config.ParseLegacyConfigYAML("<PATH>")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1035,7 +815,7 @@ func main() {
|
|||||||
legacyCfg.SetTimeout(5 * time.Minute)
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
// Создание клиента
|
// Создание клиента
|
||||||
legacyClient := decort.NewLegacy(legacyCfg)
|
legacyClient := decort.NewLegacy(cfg)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1056,13 +836,12 @@ 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(legacyCfg)
|
legacyClient := decort.NewLegacy(cfg)
|
||||||
|
|
||||||
// Создание структуры запроса
|
// Создание структуры запроса
|
||||||
// CreateRequest - реквест на создание виртуальной машины
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
@@ -1075,384 +854,10 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Выполнение запроса
|
// Выполнение запроса
|
||||||
res, err := legacyClient.CloudAPI().KVMX86().Create(context.Background(), req)
|
res, err := client.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)
|
|
||||||
|
|
||||||
}
|
|
||||||
```
|
|
||||||
305
client.go
305
client.go
@@ -4,25 +4,22 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/json"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"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/cloudapi"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
|
|
||||||
|
"github.com/google/go-querystring/query"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DecortClient is HTTP-client for platform
|
// HTTP-client for platform
|
||||||
type DecortClient struct {
|
type DecortClient struct {
|
||||||
decortURL string
|
decortURL string
|
||||||
client *http.Client
|
client *http.Client
|
||||||
@@ -76,275 +73,91 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBufferString(values.Encode())
|
body := strings.NewReader(values.Encode())
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+"/restmachine"+url, body)
|
||||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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
|
resp, err := dc.do(req)
|
||||||
respBytes, err := dc.do(req, "")
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBytes, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return respBytes, err
|
if resp.StatusCode != 200 {
|
||||||
}
|
return nil, errors.New(string(respBytes))
|
||||||
|
|
||||||
// DecortApiCallMP method for sending requests to the platform
|
|
||||||
func (dc *DecortClient) DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
|
||||||
body, ctype, err := multiPartReq(params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
return respBytes, nil
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// get token
|
|
||||||
if err = dc.getToken(ctx); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// perform request
|
|
||||||
respBytes, err := dc.do(req, ctype)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return respBytes, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dc *DecortClient) getToken(ctx context.Context) error {
|
func (dc *DecortClient) getToken(ctx context.Context) error {
|
||||||
dc.mutex.Lock()
|
dc.mutex.Lock()
|
||||||
defer dc.mutex.Unlock()
|
defer dc.mutex.Unlock()
|
||||||
|
|
||||||
// new token is not needed
|
if dc.cfg.Token == "" || time.Now().After(dc.expiryTime) {
|
||||||
if dc.cfg.Token != "" && !time.Now().After(dc.expiryTime) {
|
body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&response_type=id_token", dc.cfg.AppID, dc.cfg.AppSecret)
|
||||||
return nil
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
dc.cfg.SSOURL = strings.TrimSuffix(dc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", dc.cfg.SSOURL+"/v1/oauth/access_token", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := string(tokenBytes)
|
||||||
|
|
||||||
|
dc.cfg.Token = token
|
||||||
|
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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.
|
func (dc *DecortClient) do(req *http.Request) (*http.Response, error) {
|
||||||
// In any other cases do returns nil response and error.
|
|
||||||
// Retries are implemented in case of connection reset errors.
|
|
||||||
func (dc *DecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
|
||||||
// set up request headers and body
|
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
if ctype != "" {
|
|
||||||
req.Header.Set("Content-Type", ctype)
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
req.Header.Add("Authorization", "bearer "+dc.cfg.Token)
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
buf, err := io.ReadAll(req.Body)
|
// var resp *http.Response
|
||||||
if err != nil {
|
// var err error
|
||||||
return nil, err
|
buf, _ := io.ReadAll(req.Body)
|
||||||
}
|
|
||||||
|
|
||||||
req.Body.Close()
|
// for i := uint64(0); i < dc.cfg.Retries; i++ {
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
// req = req.Clone(req.Context())
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
resp, err := dc.client.Do(req)
|
||||||
|
|
||||||
resp, err := dc.client.Do(req)
|
// if err == nil {
|
||||||
if resp != nil {
|
if resp.StatusCode == 200 {
|
||||||
defer resp.Body.Close()
|
return resp, err
|
||||||
}
|
}
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
|
resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
// retries logic GOES HERE
|
|
||||||
// get http response
|
|
||||||
//var resp *http.Response
|
|
||||||
//for i := uint64(0); i < dc.cfg.Retries; i++ {
|
|
||||||
// req := req.Clone(req.Context())
|
|
||||||
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
|
||||||
//
|
|
||||||
// if i > 0 {
|
|
||||||
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// resp, err = dc.client.Do(req)
|
|
||||||
//
|
|
||||||
// // stop retries on success and close response body
|
|
||||||
// if resp != nil {
|
|
||||||
// defer resp.Body.Close()
|
|
||||||
// }
|
|
||||||
// if err == nil {
|
|
||||||
// break
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // retries in case of connection errors with time sleep
|
|
||||||
// if isConnectionError(err) {
|
|
||||||
// continue
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // return error in case of non-connection error
|
|
||||||
// return nil, err
|
|
||||||
//}
|
|
||||||
|
|
||||||
// handle http request errors
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if resp == nil {
|
|
||||||
return nil, fmt.Errorf("got empty response without error")
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle successful request
|
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return respBytes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle errors with status code other than 200
|
|
||||||
err = fmt.Errorf("%s", respBytes)
|
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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{}
|
|
||||||
writer := multipart.NewWriter(reqBody)
|
|
||||||
values := reflect.ValueOf(params)
|
|
||||||
types := values.Type()
|
|
||||||
defer writer.Close()
|
|
||||||
for i := 0; i < values.NumField(); i++ {
|
|
||||||
if !values.Field(i).IsValid() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if values.Field(i).IsZero() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if file, ok := constants.FileName[types.Field(i).Name]; ok {
|
|
||||||
part, err := writer.CreateFormFile(trimString(types.Field(i)), file)
|
|
||||||
if err != nil {
|
|
||||||
return &bytes.Buffer{}, "", err
|
|
||||||
}
|
|
||||||
_, err = io.Copy(part, strings.NewReader(valueToString(values.Field(i).Interface())))
|
|
||||||
if err != nil {
|
|
||||||
return &bytes.Buffer{}, "", err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if values.Field(i).Type().Kind() == reflect.Slice {
|
|
||||||
switch slice := values.Field(i).Interface().(type) {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ct := writer.FormDataContentType()
|
|
||||||
return reqBody, ct, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func valueToString(a any) string {
|
|
||||||
switch str := a.(type) {
|
|
||||||
case string:
|
|
||||||
return str
|
|
||||||
case uint:
|
|
||||||
return strconv.FormatUint(uint64(str), 10)
|
|
||||||
case uint64:
|
|
||||||
return strconv.FormatUint(str, 10)
|
|
||||||
case bool:
|
|
||||||
return strconv.FormatBool(str)
|
|
||||||
default:
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimString(el reflect.StructField) string {
|
|
||||||
return strings.TrimSuffix(el.Tag.Get("url"), ",omitempty")
|
|
||||||
}
|
|
||||||
|
|||||||
380
client_bvs.go
380
client_bvs.go
@@ -1,380 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -42,7 +42,7 @@ type Config struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Retries uint64 `json:"retries" yaml:"retries"`
|
Retries uint64 `json:"retries" yaml:"retries"`
|
||||||
|
|
||||||
// Skip verify
|
// Skip verify, true by default
|
||||||
// Required: false
|
// Required: false
|
||||||
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||||
|
|
||||||
@@ -72,7 +72,9 @@ func ParseConfigJSON(path string) (Config, error) {
|
|||||||
|
|
||||||
err = validators.ValidateConfig(config)
|
err = validators.ValidateConfig(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return Config{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
@@ -94,7 +96,9 @@ func ParseConfigYAML(path string) (Config, error) {
|
|||||||
|
|
||||||
err = validators.ValidateConfig(config)
|
err = validators.ValidateConfig(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return Config{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
|
|||||||
@@ -1,216 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -36,7 +36,7 @@ type LegacyConfig struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Retries uint64 `json:"retries" yaml:"retries"`
|
Retries uint64 `json:"retries" yaml:"retries"`
|
||||||
|
|
||||||
// Skip verify
|
// Skip verify, true by default
|
||||||
// Required: false
|
// Required: false
|
||||||
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`
|
||||||
|
|
||||||
@@ -66,7 +66,9 @@ func ParseLegacyConfigJSON(path string) (LegacyConfig, error) {
|
|||||||
|
|
||||||
err = validators.ValidateConfig(config)
|
err = validators.ValidateConfig(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
@@ -88,7 +90,9 @@ func ParseLegacyConfigYAML(path string) (LegacyConfig, error) {
|
|||||||
|
|
||||||
err = validators.ValidateConfig(config)
|
err = validators.ValidateConfig(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return LegacyConfig{}, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return LegacyConfig{}, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
|
|||||||
@@ -22,10 +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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,10 +40,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,17 +5,15 @@ 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.15.0 // indirect
|
golang.org/x/crypto v0.5.0 // indirect
|
||||||
golang.org/x/sys v0.14.0 // indirect
|
golang.org/x/sys v0.4.0 // indirect
|
||||||
golang.org/x/text v0.14.0 // indirect
|
golang.org/x/text v0.6.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
17
go.sum
17
go.sum
@@ -8,13 +8,10 @@ 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=
|
||||||
@@ -26,12 +23,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.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
|
golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
|
||||||
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
|
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
|
||||||
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
||||||
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
|||||||
@@ -6,7 +6,4 @@ 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)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package interfaces
|
|
||||||
|
|
||||||
// Interface to valiate RAM values
|
|
||||||
type RequestWithRAM interface {
|
|
||||||
// GetRAM returns RAM values
|
|
||||||
GetRAM() map[string]uint64
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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,41 +0,0 @@
|
|||||||
package multierror
|
|
||||||
|
|
||||||
func Join(errs ...error) error {
|
|
||||||
n := 0
|
|
||||||
for _, err := range errs {
|
|
||||||
if err != nil {
|
|
||||||
n++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if n == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
e := &joinError{
|
|
||||||
errs: make([]error, 0, n),
|
|
||||||
}
|
|
||||||
for _, err := range errs {
|
|
||||||
if err != nil {
|
|
||||||
e.errs = append(e.errs, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
|
|
||||||
type joinError struct {
|
|
||||||
errs []error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *joinError) Error() string {
|
|
||||||
var b []byte
|
|
||||||
for i, err := range e.errs {
|
|
||||||
if i > 0 {
|
|
||||||
b = append(b, '\n')
|
|
||||||
}
|
|
||||||
b = append(b, err.Error()...)
|
|
||||||
}
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *joinError) Unwrap() []error {
|
|
||||||
return e.errs
|
|
||||||
}
|
|
||||||
@@ -1,35 +1,31 @@
|
|||||||
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 IsInSlice(fieldValue, computeDriverValues)
|
return StringInSlice(fieldValue, computeDriverValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// protoValidator is used to validate Proto fields.
|
// protoValidator is used to validate Proto fields.
|
||||||
func protoValidator(fe validator.FieldLevel) bool {
|
func protoValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return IsInSlice(fieldValue, protoValues)
|
return StringInSlice(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 IsInSlice(fieldValue, accessTypeValues)
|
return StringInSlice(fieldValue, accessTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// resTypesValidator is used to validate ResTypes fields.
|
// resTypesValidator is used to validate ResTypes fields.
|
||||||
@@ -40,7 +36,7 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !IsInSlice(value, resTypesValues) {
|
if !StringInSlice(value, resTypesValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,56 +48,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 IsInSlice(fieldValue, driverValues)
|
return StringInSlice(fieldValue, driverValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// accountCUTypeValidator is used to validate CUType field.
|
// accountCUTypeValidator is used to validate CUType field.
|
||||||
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return IsInSlice(fieldValue, accountCUTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, bserviceModeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, computeTopologyValues)
|
return StringInSlice(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 IsInSlice(fieldValue, computePolicyValues)
|
return StringInSlice(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 IsInSlice(fieldValue, computeModeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, computeDiskTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, computeNetTypeValues)
|
return StringInSlice(fieldValue, computeNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeOrderValidator is used to validate Order field.
|
// computeOrderValidator is used to validate Order field.
|
||||||
@@ -112,7 +108,7 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !IsInSlice(value, computeOrderValues) {
|
if !StringInSlice(value, computeOrderValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,70 +120,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 IsInSlice(fieldValue, computeDataDisksValues)
|
return StringInSlice(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 IsInSlice(fieldValue, diskTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, flipgroupClientTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, kvmNetTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, lbAlgorithmValues)
|
return StringInSlice(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 IsInSlice(fieldValue, rgDefNetValues)
|
return StringInSlice(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 IsInSlice(fieldValue, rgNetTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, vinsTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, imageBootTypeValues)
|
return StringInSlice(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 IsInSlice(fieldValue, imageTypeValues)
|
return StringInSlice(fieldValue, imageTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageDriversValidator is used to validate Drivers field.
|
// imageDriversValidator is used to validate Drivers field.
|
||||||
@@ -198,7 +194,7 @@ func imageDriversValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, item := range fieldSlice {
|
for _, item := range fieldSlice {
|
||||||
if !IsInSlice(item, imageDriversValues) {
|
if !StringInSlice(item, imageDriversValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -210,14 +206,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 IsInSlice(fieldValue, imageArchitectureValues)
|
return StringInSlice(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 IsInSlice(fieldValue, sepFieldTypeValues)
|
return StringInSlice(fieldValue, sepFieldTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// hwPathValidator is used to validate HWPath field.
|
// hwPathValidator is used to validate HWPath field.
|
||||||
@@ -234,7 +230,7 @@ func networkPluginValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return IsInSlice(fieldValue, networkPluginValues)
|
return StringInSlice(fieldValue, networkPluginValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// networkPluginsValidator is used to validate NetworkPlugins field
|
// networkPluginsValidator is used to validate NetworkPlugins field
|
||||||
@@ -247,7 +243,7 @@ func networkPluginsValidator(fe validator.FieldLevel) bool {
|
|||||||
for _, item := range fieldSlice {
|
for _, item := range fieldSlice {
|
||||||
item = strings.ToLower(item)
|
item = strings.ToLower(item)
|
||||||
|
|
||||||
if !IsInSlice(item, networkPluginValues) {
|
if !StringInSlice(item, networkPluginValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -259,14 +255,14 @@ func interfaceStateValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return IsInSlice(fieldValue, interfaceStateValues)
|
return StringInSlice(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 IsInSlice(fieldValue, strictLooseValues)
|
return StringInSlice(fieldValue, strictLooseValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// name workerGroup must be more 3 symbol
|
// name workerGroup must be more 3 symbol
|
||||||
@@ -276,60 +272,3 @@ 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...)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package validators
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/multierror"
|
|
||||||
|
|
||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
)
|
)
|
||||||
@@ -21,20 +20,12 @@ func ValidationError(fe validator.FieldError) error {
|
|||||||
return errors.New(errorMessage(fe))
|
return errors.New(errorMessage(fe))
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidationErrors(fes []validator.FieldError) error {
|
|
||||||
errs := make([]error, 0, len(fes))
|
|
||||||
for _, fe := range fes {
|
|
||||||
errs = append(errs, ValidationError(fe))
|
|
||||||
}
|
|
||||||
return multierror.Join(errs...)
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:errorlint
|
//nolint:errorlint
|
||||||
func GetErrors(err error) validator.ValidationErrors {
|
func GetErrors(err error) validator.ValidationErrors {
|
||||||
return err.(validator.ValidationErrors)
|
return err.(validator.ValidationErrors)
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsInSlice(str string, target []string) bool {
|
func StringInSlice(str string, target []string) bool {
|
||||||
for _, v := range target {
|
for _, v := range target {
|
||||||
if v == str {
|
if v == str {
|
||||||
return true
|
return true
|
||||||
@@ -42,12 +33,3 @@ func IsInSlice(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,35 +229,6 @@ 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,7 +25,6 @@ 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
|
||||||
@@ -186,30 +185,5 @@ 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,17 +39,9 @@ var (
|
|||||||
|
|
||||||
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
||||||
|
|
||||||
networkPluginValues = []string{"flannel", "weavenet", "calico"}
|
networkPluginValues = []string{"flannel", "weawenet", "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"}
|
|
||||||
)
|
)
|
||||||
|
|||||||
195
legacy-client.go
195
legacy-client.go
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -14,12 +15,11 @@ 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"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
|
||||||
)
|
)
|
||||||
|
|
||||||
// LegacyDecortClient is Legacy HTTP-client for platform
|
// Legacy HTTP-client for platform
|
||||||
type LegacyDecortClient struct {
|
type LegacyDecortClient struct {
|
||||||
decortURL string
|
decortURL string
|
||||||
client *http.Client
|
client *http.Client
|
||||||
@@ -68,168 +68,93 @@ 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 {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
values, err := query.Values(params)
|
values, err := query.Values(params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// perform request
|
|
||||||
respBytes, err := ldc.do(req, "")
|
|
||||||
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 {
|
if err = ldc.getToken(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// perform request
|
body := strings.NewReader(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
respBytes, err := ldc.do(req, ctype)
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+"/restmachine"+url, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return respBytes, err
|
resp, err := ldc.do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBytes, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return nil, errors.New(string(respBytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
||||||
ldc.mutex.Lock()
|
ldc.mutex.Lock()
|
||||||
defer ldc.mutex.Unlock()
|
defer ldc.mutex.Unlock()
|
||||||
|
|
||||||
// new token is not needed
|
if ldc.cfg.Token == "" || time.Now().After(ldc.expiryTime) {
|
||||||
if ldc.cfg.Token != "" && !time.Now().After(ldc.expiryTime) {
|
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||||
return nil
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
||||||
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to get token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("unable to get token: %s", tokenBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := string(tokenBytes)
|
||||||
|
ldc.cfg.Token = token
|
||||||
|
ldc.expiryTime = time.Now().AddDate(0, 0, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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.
|
func (ldc *LegacyDecortClient) do(req *http.Request) (*http.Response, error) {
|
||||||
// In any other cases do returns nil response and error.
|
|
||||||
// Retries are implemented in case of connection reset errors.
|
|
||||||
func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, error) {
|
|
||||||
// set up request headers and body
|
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
if ctype != "" {
|
|
||||||
req.Header.Set("Content-Type", ctype)
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
buf, err := io.ReadAll(req.Body)
|
// var resp *http.Response
|
||||||
if err != nil {
|
// var err error
|
||||||
return nil, err
|
buf, _ := io.ReadAll(req.Body)
|
||||||
}
|
|
||||||
|
|
||||||
req.Body.Close()
|
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
// req = req.Clone(req.Context())
|
||||||
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
resp, err := ldc.client.Do(req)
|
||||||
|
|
||||||
resp, err := ldc.client.Do(req)
|
// if err == nil {
|
||||||
if resp != nil {
|
if resp.StatusCode == 200 {
|
||||||
defer resp.Body.Close()
|
return resp, err
|
||||||
}
|
}
|
||||||
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
|
err = fmt.Errorf("%s", respBytes)
|
||||||
|
resp.Body.Close()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
// retries logic GOES HERE
|
|
||||||
// get http response
|
|
||||||
//var resp *http.Response
|
|
||||||
//for i := uint64(0); i < ldc.cfg.Retries; i++ {
|
|
||||||
// req := req.Clone(req.Context())
|
|
||||||
// req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
|
||||||
//
|
|
||||||
// if i > 0 {
|
|
||||||
// time.Sleep(5 * time.Second) // no time sleep for the first request
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// resp, err = ldc.client.Do(req)
|
|
||||||
//
|
|
||||||
// // stop retries on success and close response body
|
|
||||||
// if resp != nil {
|
|
||||||
// defer resp.Body.Close()
|
|
||||||
// }
|
|
||||||
// if err == nil {
|
|
||||||
// break
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // retries in case of connection errors with time sleep
|
|
||||||
// if isConnectionError(err) {
|
|
||||||
// continue
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // return error in case of non-connection error
|
|
||||||
// return nil, err
|
|
||||||
//}
|
|
||||||
|
|
||||||
// handle http request errors
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if resp == nil {
|
|
||||||
return nil, fmt.Errorf("got empty response without error")
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle successful request
|
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return respBytes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle errors with status code other than 200
|
|
||||||
err = fmt.Errorf("%s", respBytes)
|
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AddUserRequest struct to add permission to access account for a user
|
// Request struct for adding permission to access to account for a user
|
||||||
type AddUserRequest struct {
|
type AddUserRequest struct {
|
||||||
// ID of account to add to
|
// ID of account to add to
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,7 +30,9 @@ type AddUserRequest struct {
|
|||||||
func (a Account) AddUser(ctx context.Context, req AddUserRequest) (bool, error) {
|
func (a Account) AddUser(ctx context.Context, req AddUserRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/addUser"
|
url := "/cloudapi/account/addUser"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AuditsRequest struct to give list of account audits
|
// Request struct for give list account audits
|
||||||
type AuditsRequest struct {
|
type AuditsRequest struct {
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AuditsRequest struct {
|
|||||||
func (a Account) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
func (a Account) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/audits"
|
url := "/cloudapi/account/audits"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateRequest struct for creating account
|
// Request struct for creating account
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// Display name
|
// Display name
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -56,7 +56,9 @@ type CreateRequest struct {
|
|||||||
func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/create"
|
url := "/cloudapi/account/create"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteRequest struct to delete account
|
// Request struct for delete account
|
||||||
type DeleteRequest struct {
|
type DeleteRequest struct {
|
||||||
// ID of account to delete
|
// ID of account to delete
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -22,7 +22,9 @@ type DeleteRequest struct {
|
|||||||
func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/delete"
|
url := "/cloudapi/account/delete"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteUserRequest struct to revoke access to account
|
// Request struct for revoke access to account
|
||||||
type DeleteUserRequest struct {
|
type DeleteUserRequest struct {
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -20,14 +20,16 @@ type DeleteUserRequest struct {
|
|||||||
|
|
||||||
// Recursively revoke access rights from owned cloudspaces and vmachines
|
// Recursively revoke access rights from owned cloudspaces and vmachines
|
||||||
// Required: false
|
// Required: false
|
||||||
RecursiveDelete bool `url:"recursivedelete" json:"recursivedelete"`
|
RecursiveDelete bool `url:"recursivedelete,omitempty" json:"recursivedelete,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteUser revokes user access from the account
|
// DeleteUser revokes user access from the account
|
||||||
func (a Account) DeleteUser(ctx context.Context, req DeleteUserRequest) (bool, error) {
|
func (a Account) DeleteUser(ctx context.Context, req DeleteUserRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/deleteUser"
|
url := "/cloudapi/account/deleteUser"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DisableEnableRequest struct to change status of account
|
// Request struct for change status of account
|
||||||
type DisableEnableRequest struct {
|
type DisableEnableRequest struct {
|
||||||
// ID of account
|
// ID of account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type DisableEnableRequest struct {
|
|||||||
func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/disable"
|
url := "/cloudapi/account/disable"
|
||||||
@@ -41,7 +43,9 @@ func (a Account) Disable(ctx context.Context, req DisableEnableRequest) (bool, e
|
|||||||
func (a Account) Enable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
func (a Account) Enable(ctx context.Context, req DisableEnableRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/enable"
|
url := "/cloudapi/account/enable"
|
||||||
|
|||||||
@@ -8,16 +8,25 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetRequest struct to get information about account
|
// Request struct for get information about account
|
||||||
type GetRequest struct {
|
type GetRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get gets account details as a RecordAccount struct
|
// Get gets account details
|
||||||
func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error) {
|
func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error) {
|
||||||
res, err := a.GetRaw(ctx, req)
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/account/get"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -32,16 +41,3 @@ func (a Account) Get(ctx context.Context, req GetRequest) (*RecordAccount, error
|
|||||||
return &info, nil
|
return &info, nil
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRaw gets account details as an array of bytes
|
|
||||||
func (a Account) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/account/get"
|
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetConsumedAccountUnitsRequest struct to calculate the currently consumed units for all cloudspaces and resource groups in the account
|
// Request struct for calculate the currently consumed units for all cloudspaces and resource groups in the account
|
||||||
type GetConsumedAccountUnitsRequest struct {
|
type GetConsumedAccountUnitsRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -25,7 +25,9 @@ type GetConsumedAccountUnitsRequest struct {
|
|||||||
func (a Account) GetConsumedAccountUnits(ctx context.Context, req GetConsumedAccountUnitsRequest) (*ResourceLimits, error) {
|
func (a Account) GetConsumedAccountUnits(ctx context.Context, req GetConsumedAccountUnitsRequest) (*ResourceLimits, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumedAccountUnits"
|
url := "/cloudapi/account/getConsumedAccountUnits"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetConsumedCloudUnitsByTypeRequest struct to calculate the currently consumed cloud units of the specified type for all cloudspaces and resource groups in the account
|
// Request struct for calculate the currently consumed cloud units of the specified type for all cloudspaces and resource groups in the account
|
||||||
type GetConsumedCloudUnitsByTypeRequest struct {
|
type GetConsumedCloudUnitsByTypeRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -35,7 +35,9 @@ type GetConsumedCloudUnitsByTypeRequest struct {
|
|||||||
func (a Account) GetConsumedCloudUnitsByType(ctx context.Context, req GetConsumedCloudUnitsByTypeRequest) (float64, error) {
|
func (a Account) GetConsumedCloudUnitsByType(ctx context.Context, req GetConsumedCloudUnitsByTypeRequest) (float64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumedCloudUnitsByType"
|
url := "/cloudapi/account/getConsumedCloudUnitsByType"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetConsumptionRequest struct to download the resources tracking files for an account
|
// Request struct for download the resources tracking files for an account
|
||||||
type GetConsumptionRequest struct {
|
type GetConsumptionRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -15,18 +15,20 @@ type GetConsumptionRequest struct {
|
|||||||
|
|
||||||
// Epoch represents the start time
|
// Epoch represents the start time
|
||||||
// Required: true
|
// Required: true
|
||||||
Start float64 `url:"start" json:"start" validate:"required"`
|
Start uint64 `url:"start" json:"start" validate:"required"`
|
||||||
|
|
||||||
// Epoch represents the end time
|
// Epoch represents the end time
|
||||||
// Required: true
|
// Required: true
|
||||||
End float64 `url:"end" json:"end" validate:"required"`
|
End uint64 `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
|
||||||
func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return "", validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumption"
|
url := "/cloudapi/account/getConsumption"
|
||||||
@@ -44,7 +46,9 @@ func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest)
|
|||||||
func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return "", validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumption"
|
url := "/cloudapi/account/getConsumption"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetReservedAccountUnitsRequest struct to calculate the reserved units for all cloudspaces and resource groups in the account
|
// Request struct for calculate the reserved units for all cloudspaces and resource groups in the account
|
||||||
type GetReservedAccountUnitsRequest struct {
|
type GetReservedAccountUnitsRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -26,7 +26,9 @@ type GetReservedAccountUnitsRequest struct {
|
|||||||
func (a Account) GetReservedAccountUnits(ctx context.Context, req GetReservedAccountUnitsRequest) (*ResourceLimits, error) {
|
func (a Account) GetReservedAccountUnits(ctx context.Context, req GetReservedAccountUnitsRequest) (*ResourceLimits, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getReservedAccountUnits"
|
url := "/cloudapi/account/getReservedAccountUnits"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetResourceConsumptionRequest struct to get resource consumption
|
// Request struct for getting resource consumption
|
||||||
type GetResourceConsumptionRequest struct {
|
type GetResourceConsumptionRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type GetResourceConsumptionRequest struct {
|
|||||||
func (a Account) GetResourceConsumption(ctx context.Context, req GetResourceConsumptionRequest) (*RecordResourceConsumption, error) {
|
func (a Account) GetResourceConsumption(ctx context.Context, req GetResourceConsumptionRequest) (*RecordResourceConsumption, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/getResourceConsumption"
|
url := "/cloudapi/account/getResourceConsumption"
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
package account
|
|
||||||
|
|
||||||
// IDs gets array of AccountIDs from ListAccounts struct
|
|
||||||
func (la ListAccounts) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(la.Data))
|
|
||||||
for _, acc := range la.Data {
|
|
||||||
res = append(res, acc.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of ComputeIDs from ListComputes struct
|
|
||||||
func (lc ListComputes) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lc.Data))
|
|
||||||
for _, c := range lc.Data {
|
|
||||||
res = append(res, c.ComputeID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of DiskIDs from ListDisks struct
|
|
||||||
func (ld ListDisks) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(ld.Data))
|
|
||||||
for _, d := range ld.Data {
|
|
||||||
res = append(res, d.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of FLIPGroupIDs from ListFLIPGroups struct
|
|
||||||
func (fg ListFLIPGroups) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(fg.Data))
|
|
||||||
for _, g := range fg.Data {
|
|
||||||
res = append(res, g.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of AccountIDs from ListResourceConsumption struct
|
|
||||||
func (rc ListResourceConsumption) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(rc.Data))
|
|
||||||
for _, r := range rc.Data {
|
|
||||||
res = append(res, r.AccountID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of RGIDs from ListRG struct
|
|
||||||
func (rg ListRG) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(rg.Data))
|
|
||||||
for _, g := range rg.Data {
|
|
||||||
res = append(res, g.RGID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of TemplateIDs from ListTemplates struct
|
|
||||||
func (lt ListTemplates) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lt.Data))
|
|
||||||
for _, t := range lt.Data {
|
|
||||||
res = append(res, t.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of VINSIDs from ListVINS struct
|
|
||||||
func (lv ListVINS) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lv.Data))
|
|
||||||
for _, v := range lv.Data {
|
|
||||||
res = append(res, v.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
@@ -4,11 +4,9 @@ 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
|
// Request struct for get list of accounts
|
||||||
type ListRequest struct {
|
type ListRequest struct {
|
||||||
// Find by ID
|
// Find by ID
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -26,10 +24,6 @@ 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"`
|
||||||
@@ -39,10 +33,11 @@ type ListRequest struct {
|
|||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List gets a list of all accounts the user has access to a ListAccounts struct
|
// List gets list all accounts the user has access to
|
||||||
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
||||||
|
url := "/cloudapi/account/list"
|
||||||
|
|
||||||
res, err := a.ListRaw(ctx, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -56,16 +51,3 @@ func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, erro
|
|||||||
|
|
||||||
return &list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
|
||||||
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
|
||||||
|
|
||||||
if err := validators.ValidateRequest(req); err != nil {
|
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/account/list"
|
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListComputesRequest struct to get a list of compute instances
|
// Request struct for a get list compute instances
|
||||||
type ListComputesRequest struct {
|
type ListComputesRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -46,10 +46,6 @@ 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"`
|
||||||
@@ -61,10 +57,11 @@ 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))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listComputes"
|
url := "/cloudapi/account/listComputes"
|
||||||
|
|||||||
@@ -4,11 +4,9 @@ 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
|
// Request struct for get list deleted accounts
|
||||||
type ListDeletedRequest struct {
|
type ListDeletedRequest struct {
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -29,20 +27,10 @@ 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 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)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDisksRequest struct to get a list of deleted disks
|
// Request struct for get list deleted disks
|
||||||
type ListDisksRequest struct {
|
type ListDisksRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,10 +30,6 @@ 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"`
|
||||||
@@ -45,10 +41,11 @@ 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))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listDisks"
|
url := "/cloudapi/account/listDisks"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListFLIPGroupsRequest struct to get a list of FLIPGroups
|
// Request struct for get list FLIPGroups
|
||||||
type ListFLIPGroupsRequest struct {
|
type ListFLIPGroupsRequest struct {
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -49,10 +49,11 @@ 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))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listFlipGroups"
|
url := "/cloudapi/account/listFlipGroups"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRGRequest struct to get a list of resource groups
|
// Request struct for get list resource groups
|
||||||
type ListRGRequest struct {
|
type ListRGRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -41,18 +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 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))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listRG"
|
url := "/cloudapi/account/listRG"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListTemplatesRequest struct to get a list of templates
|
// Request struct for get list templates
|
||||||
type ListTemplatesRequest struct {
|
type ListTemplatesRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,10 +30,6 @@ 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"`
|
||||||
@@ -43,12 +39,13 @@ type ListTemplatesRequest struct {
|
|||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListTemplates gets list of templates which can be managed by this account
|
// ListTemplates gets list templates which can be managed by this account
|
||||||
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listTemplates"
|
url := "/cloudapi/account/listTemplates"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListVINSRequest struct to get a list of VINS
|
// Request struct for get list VINS
|
||||||
type ListVINSRequest struct {
|
type ListVINSRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,10 +30,6 @@ 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"`
|
||||||
@@ -43,12 +39,13 @@ type ListVINSRequest struct {
|
|||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
// ListVINS gets list all ViNSes under specified account, accessible by the user
|
||||||
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listVins"
|
url := "/cloudapi/account/listVins"
|
||||||
|
|||||||
@@ -53,9 +53,6 @@ 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"`
|
||||||
|
|
||||||
@@ -91,7 +88,7 @@ type Resource struct {
|
|||||||
DiskSize float64 `json:"disksize"`
|
DiskSize float64 `json:"disksize"`
|
||||||
|
|
||||||
// Max disk size
|
// Max disk size
|
||||||
DiskSizeMax float64 `json:"disksizemax"`
|
DiskSizeMax uint64 `json:"disksizemax"`
|
||||||
|
|
||||||
// Number of External IPs
|
// Number of External IPs
|
||||||
ExtIPs int64 `json:"extips"`
|
ExtIPs int64 `json:"extips"`
|
||||||
@@ -129,10 +126,10 @@ type RecordResourceConsumption struct {
|
|||||||
// Information about resources
|
// Information about resources
|
||||||
type ItemResourceConsumption struct {
|
type ItemResourceConsumption struct {
|
||||||
// Current information about resources
|
// Current information about resources
|
||||||
Consumed Resource `json:"consumed"`
|
Current Resource `json:"Current"`
|
||||||
|
|
||||||
// Reserved information about resources
|
// Reserved information about resources
|
||||||
Reserved Resource `json:"reserved"`
|
Reserved Resource `json:"Reserved"`
|
||||||
|
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64 `json:"id"`
|
AccountID uint64 `json:"id"`
|
||||||
@@ -179,9 +176,6 @@ 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"`
|
||||||
|
|
||||||
@@ -380,12 +374,6 @@ 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"`
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RestoreRequest struct to restore a deleted account
|
// Request struct for restore a deleted account
|
||||||
type RestoreRequest struct {
|
type RestoreRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -17,7 +17,9 @@ type RestoreRequest struct {
|
|||||||
func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/restore"
|
url := "/cloudapi/account/restore"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UpdateRequest struct to update account
|
// Request struct for updaate account
|
||||||
type UpdateRequest struct {
|
type UpdateRequest struct {
|
||||||
// ID an account
|
// ID an account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -51,7 +51,9 @@ type UpdateRequest struct {
|
|||||||
func (a Account) Update(ctx context.Context, req UpdateRequest) (bool, error) {
|
func (a Account) Update(ctx context.Context, req UpdateRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/update"
|
url := "/cloudapi/account/update"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UpdateUserRequest struct to update user access rights
|
// Request struct for update user access rights
|
||||||
type UpdateUserRequest struct {
|
type UpdateUserRequest struct {
|
||||||
// ID of the account
|
// ID of the account
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,7 +30,9 @@ type UpdateUserRequest struct {
|
|||||||
func (a Account) UpdateUser(ctx context.Context, req UpdateUserRequest) (bool, error) {
|
func (a Account) UpdateUser(ctx context.Context, req UpdateUserRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/updateUser"
|
url := "/cloudapi/account/updateUser"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateRequest struct for BasicService
|
// Request struct for BasicService
|
||||||
type CreateRequest struct {
|
type CreateRequest struct {
|
||||||
// Name of the service
|
// Name of the service
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -31,7 +31,9 @@ type CreateRequest struct {
|
|||||||
func (b BService) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
func (b BService) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/create"
|
url := "/cloudapi/bservice/create"
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteRequest struct to delete basic service
|
// Request struct for delete basic service
|
||||||
type DeleteRequest struct {
|
type DeleteRequest struct {
|
||||||
// ID of the BasicService to be delete
|
// ID of the BasicService to be delete
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// If set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately
|
// If set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -23,7 +23,9 @@ type DeleteRequest struct {
|
|||||||
func (b BService) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
func (b BService) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/delete"
|
url := "/cloudapi/bservice/delete"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DisableRequest struct for disable service
|
// Request struct for disable service
|
||||||
type DisableRequest struct {
|
type DisableRequest struct {
|
||||||
// ID of the service to disable
|
// ID of the service to disable
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -21,10 +21,12 @@ type DisableRequest struct {
|
|||||||
func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error) {
|
func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/disable"
|
url := "/cloudapi/bservice/delete"
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// EnableRequest struct to disable service
|
// Request struct for disable service
|
||||||
type EnableRequest struct {
|
type EnableRequest struct {
|
||||||
// ID of the service to enable
|
// ID of the service to enable
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -22,7 +22,9 @@ type EnableRequest struct {
|
|||||||
func (b BService) Enable(ctx context.Context, req EnableRequest) (bool, error) {
|
func (b BService) Enable(ctx context.Context, req EnableRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/enable"
|
url := "/cloudapi/bservice/enable"
|
||||||
|
|||||||
@@ -8,39 +8,35 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetRequest struct to get detailed information about service
|
// Request struct for get detailed information about service
|
||||||
type GetRequest struct {
|
type GetRequest struct {
|
||||||
// ID of the service to query information
|
// ID of the service to query information
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get gets detailed specifications for the BasicService as a RecordBasicService struct
|
// Get gets detailed specifications for the BasicService.
|
||||||
func (b BService) Get(ctx context.Context, req GetRequest) (*RecordBasicService, error) {
|
func (b BService) Get(ctx context.Context, req GetRequest) (*RecordBasicService, error) {
|
||||||
res, err := b.GetRaw(ctx, req)
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/bservice/get"
|
||||||
|
|
||||||
|
bsRaw, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
info := RecordBasicService{}
|
info := RecordBasicService{}
|
||||||
|
|
||||||
err = json.Unmarshal(res, &info)
|
err = json.Unmarshal(bsRaw, &info)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &info, nil
|
return &info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRaw gets detailed specifications for the BasicService as an array of bytes
|
|
||||||
func (b BService) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/bservice/get"
|
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,42 +8,42 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupAddRequest struct to create new compute group within BasicService
|
// Request struct for create new compute group within BasicService
|
||||||
type GroupAddRequest struct {
|
type GroupAddRequest struct {
|
||||||
// ID of the Basic Service to add a group to
|
// ID of the Basic Service to add a group to
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// Name of the Compute Group to add
|
// Name of the Compute Group to add
|
||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name" validate:"required"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
// Computes number. Defines how many computes must be there in the group
|
// Computes number. Defines how many computes must be there in the group
|
||||||
// Required: true
|
// Required: true
|
||||||
Count uint64 `url:"count" json:"count" validate:"required"`
|
Count uint64 `url:"count" json:"count" validate:"required"`
|
||||||
|
|
||||||
// Compute CPU number. All computes in the group have the same CPU count
|
// Compute CPU number. All computes in the group have the same CPU count
|
||||||
// Required: true
|
// Required: true
|
||||||
CPU uint64 `url:"cpu" json:"cpu" validate:"required"`
|
CPU uint64 `url:"cpu" json:"cpu" validate:"required"`
|
||||||
|
|
||||||
// Compute RAM volume in MB. All computes in the group have the same RAM volume
|
// Compute RAM volume in MB. All computes in the group have the same RAM volume
|
||||||
// Required: true
|
// Required: true
|
||||||
RAM uint64 `url:"ram" json:"ram" validate:"required"`
|
RAM uint64 `url:"ram" json:"ram" validate:"required"`
|
||||||
|
|
||||||
// Compute boot disk size in GB
|
// Compute boot disk size in GB
|
||||||
// Required: true
|
// Required: true
|
||||||
Disk uint64 `url:"disk" json:"disk" validate:"required"`
|
Disk uint64 `url:"disk" json:"disk" validate:"required"`
|
||||||
|
|
||||||
// OS image ID to create computes from
|
// OS image ID to create computes from
|
||||||
// Required: true
|
// Required: true
|
||||||
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
||||||
|
|
||||||
// Compute driver
|
// Compute driver
|
||||||
// should be one of:
|
// should be one of:
|
||||||
// - KVM_X86
|
// - KVM_X86
|
||||||
// - KVM_PPC
|
// - KVM_PPC
|
||||||
// Required: true
|
// Required: true
|
||||||
Driver string `url:"driver" json:"driver" validate:"driver"`
|
Driver string `url:"driver" json:"driver" validate:"driver"`
|
||||||
|
|
||||||
// Storage endpoint provider ID
|
// Storage endpoint provider ID
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -68,20 +68,6 @@ type GroupAddRequest struct {
|
|||||||
// Time of Compute Group readiness
|
// Time of Compute Group readiness
|
||||||
// Required: false
|
// Required: false
|
||||||
TimeoutStart uint64 `url:"timeoutStart,omitempty" json:"timeoutStart,omitempty"`
|
TimeoutStart uint64 `url:"timeoutStart,omitempty" json:"timeoutStart,omitempty"`
|
||||||
|
|
||||||
// Meta data for working group computes, format YAML "user_data": 1111
|
|
||||||
// Required: false
|
|
||||||
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.
|
||||||
@@ -90,7 +76,9 @@ func (r GroupAddRequest) GetRAM() map[string]uint64 {
|
|||||||
func (b BService) GroupAdd(ctx context.Context, req GroupAddRequest) (uint64, error) {
|
func (b BService) GroupAdd(ctx context.Context, req GroupAddRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupAdd"
|
url := "/cloudapi/bservice/groupAdd"
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupComputeRemoveRequest struct to remove group compute
|
// Request struct for remove group compute
|
||||||
type GroupComputeRemoveRequest struct {
|
type GroupComputeRemoveRequest struct {
|
||||||
// ID of the Basic Service
|
// ID of the Basic Service
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute GROUP
|
// ID of the Compute GROUP
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +27,9 @@ type GroupComputeRemoveRequest struct {
|
|||||||
func (b BService) GroupComputeRemove(ctx context.Context, req GroupComputeRemoveRequest) (bool, error) {
|
func (b BService) GroupComputeRemove(ctx context.Context, req GroupComputeRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupComputeRemove"
|
url := "/cloudapi/bservice/groupComputeRemove"
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupGetRequest struct to get detailed information about Compute Group
|
// Request struct for get detailed information about Compute Group
|
||||||
type GroupGetRequest struct {
|
type GroupGetRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute Group
|
// ID of the Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type GroupGetRequest struct {
|
|||||||
func (b BService) GroupGet(ctx context.Context, req GroupGetRequest) (*RecordGroup, error) {
|
func (b BService) GroupGet(ctx context.Context, req GroupGetRequest) (*RecordGroup, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupGet"
|
url := "/cloudapi/bservice/groupGet"
|
||||||
|
|||||||
@@ -8,11 +8,12 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupParentAddRequest struct to add parent Compute Group relation to the specified Compute Group
|
// Request struct for add parent Compute Group relation emove parent Compute Group
|
||||||
|
// relation to the specified Compute Group
|
||||||
type GroupParentAddRequest struct {
|
type GroupParentAddRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute Group
|
// ID of the Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +28,9 @@ type GroupParentAddRequest struct {
|
|||||||
func (b BService) GroupParentAdd(ctx context.Context, req GroupParentAddRequest) (bool, error) {
|
func (b BService) GroupParentAdd(ctx context.Context, req GroupParentAddRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupParentAdd"
|
url := "/cloudapi/bservice/groupParentAdd"
|
||||||
|
|||||||
@@ -8,28 +8,30 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupParentRemoveRequest struct to remove parent Compute Group
|
// Request struct for remove parent Compute Group
|
||||||
// relation from the specified Compute Group
|
// relation to the specified Compute Group
|
||||||
type GroupParentRemoveRequest struct {
|
type GroupParentRemoveRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute Group
|
// ID of the Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||||
|
|
||||||
// ID of the parent Compute Group
|
// ID of the parent Compute Group
|
||||||
// to remove from the current Compute Group
|
// to remove from the current Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ParentID uint64 `url:"parentId" json:"parentId" validate:"required"`
|
ParentID uint64 `url:"parentId" json:"parentId" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GroupParentRemove removes parent Compute Group relation to the specified Compute Group
|
// GroupParentRemove removes parent Compute Group relation to the specified Compute Group
|
||||||
func (b BService) GroupParentRemove(ctx context.Context, req GroupParentRemoveRequest) (bool, error) {
|
func (b BService) GroupParentRemove(ctx context.Context, req GroupParentRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupParentRemove"
|
url := "/cloudapi/bservice/groupParentRemove"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupRemoveRequest struct for destroy the specified Compute Group
|
// Request struct for destroy the specified Compute Group
|
||||||
type GroupRemoveRequest struct {
|
type GroupRemoveRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type GroupRemoveRequest struct {
|
|||||||
func (b BService) GroupRemove(ctx context.Context, req GroupRemoveRequest) (bool, error) {
|
func (b BService) GroupRemove(ctx context.Context, req GroupRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupRemove"
|
url := "/cloudapi/bservice/groupRemove"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupResizeRequest struct to resize the group
|
// Request struct for resize the group
|
||||||
type GroupResizeRequest struct {
|
type GroupResizeRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -34,7 +34,9 @@ type GroupResizeRequest struct {
|
|||||||
func (b BService) GroupResize(ctx context.Context, req GroupResizeRequest) (uint64, error) {
|
func (b BService) GroupResize(ctx context.Context, req GroupResizeRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupResize"
|
url := "/cloudapi/bservice/groupResize"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupStartRequest struct to start the specified Compute Group
|
// Request struct for start the specified Compute Group
|
||||||
type GroupStartRequest struct {
|
type GroupStartRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type GroupStartRequest struct {
|
|||||||
func (b BService) GroupStart(ctx context.Context, req GroupStartRequest) (bool, error) {
|
func (b BService) GroupStart(ctx context.Context, req GroupStartRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupStart"
|
url := "/cloudapi/bservice/groupStart"
|
||||||
|
|||||||
@@ -8,15 +8,15 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupStopRequest struct to stop the specified Compute Group
|
// Request struct for stop the specified Compute Group
|
||||||
type GroupStopRequest struct {
|
type GroupStopRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute Group to stop
|
// ID of the Compute Group to stop
|
||||||
// Required: true
|
// Required: true
|
||||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||||
|
|
||||||
// Force stop Compute Group
|
// Force stop Compute Group
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -27,7 +27,9 @@ type GroupStopRequest struct {
|
|||||||
func (b BService) GroupStop(ctx context.Context, req GroupStopRequest) (bool, error) {
|
func (b BService) GroupStop(ctx context.Context, req GroupStopRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupStop"
|
url := "/cloudapi/bservice/groupStop"
|
||||||
|
|||||||
@@ -8,15 +8,15 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupUpdateRequest struct to update existing Compute group
|
// Request struct for update existing Compute group
|
||||||
type GroupUpdateRequest struct {
|
type GroupUpdateRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
// ID of the Compute Group
|
// ID of the Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
CompGroupID uint64 `url:"compgroupId" json:"compgroupId" validate:"required"`
|
||||||
|
|
||||||
// Specify non-empty string to update Compute Group name
|
// Specify non-empty string to update Compute Group name
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -43,21 +43,13 @@ 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)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupUpdate"
|
url := "/cloudapi/bservice/groupUpdate"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupUpdateExtNetRequest struct to update External Network settings
|
// Request struct for update External Network settings
|
||||||
type GroupUpdateExtNetRequest struct {
|
type GroupUpdateExtNetRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +27,9 @@ type GroupUpdateExtNetRequest struct {
|
|||||||
func (b BService) GroupUpdateExtNet(ctx context.Context, req GroupUpdateExtNetRequest) (bool, error) {
|
func (b BService) GroupUpdateExtNet(ctx context.Context, req GroupUpdateExtNetRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupUpdateExtnet"
|
url := "/cloudapi/bservice/groupUpdateExtnet"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GroupUpdateVINSRequest struct to update VINS settings
|
// Request struct for update VINS settings
|
||||||
type GroupUpdateVINSRequest struct {
|
type GroupUpdateVINSRequest struct {
|
||||||
// ID of the Basic Service of Compute Group
|
// ID of the Basic Service of Compute Group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +27,9 @@ type GroupUpdateVINSRequest struct {
|
|||||||
func (b BService) GroupUpdateVINS(ctx context.Context, req GroupUpdateVINSRequest) (bool, error) {
|
func (b BService) GroupUpdateVINS(ctx context.Context, req GroupUpdateVINSRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/groupUpdateVins"
|
url := "/cloudapi/bservice/groupUpdateVins"
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
package bservice
|
|
||||||
|
|
||||||
// IDs gets array of BasicServiceIDs from ListBasicServices struct
|
|
||||||
func (lbs ListBasicServices) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lbs.Data))
|
|
||||||
for _, bs := range lbs.Data {
|
|
||||||
res = append(res, bs.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of ComputeIDs from ListComputes struct
|
|
||||||
func (lc ListComputes) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lc))
|
|
||||||
for _, c := range lc {
|
|
||||||
res = append(res, c.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of GroupIDs from ListGroups struct
|
|
||||||
func (lg ListGroups) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lg))
|
|
||||||
for _, g := range lg {
|
|
||||||
res = append(res, g.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs gets array of GroupComputeIDs from ListGroupComputes struct
|
|
||||||
func (lgc ListGroupComputes) IDs() []uint64 {
|
|
||||||
res := make([]uint64, 0, len(lgc))
|
|
||||||
for _, gc := range lgc {
|
|
||||||
res = append(res, gc.ID)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
@@ -4,11 +4,9 @@ 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
|
// Request struct for get list BasicService instances
|
||||||
type ListRequest struct {
|
type ListRequest struct {
|
||||||
// Find by ID
|
// Find by ID
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -42,10 +40,6 @@ 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"`
|
||||||
@@ -55,10 +49,11 @@ type ListRequest struct {
|
|||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
// List gets list BasicService instances associated with the specified Resource Group
|
||||||
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
||||||
|
url := "/cloudapi/bservice/list"
|
||||||
|
|
||||||
res, err := b.ListRaw(ctx, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -72,16 +67,3 @@ func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices
|
|||||||
|
|
||||||
return &list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
|
||||||
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
|
||||||
|
|
||||||
if err := validators.ValidateRequest(req); err != nil {
|
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/bservice/list"
|
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,11 +4,9 @@ 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
|
// Request struct for get list of deleted BasicService instances
|
||||||
type ListDeletedRequest struct {
|
type ListDeletedRequest struct {
|
||||||
// ID of the account to query for BasicService instances
|
// ID of the account to query for BasicService instances
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -18,10 +16,6 @@ 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"`
|
||||||
@@ -31,13 +25,8 @@ type ListDeletedRequest struct {
|
|||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
// ListDeleted gets list 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 `json:"accountId"`
|
AccountID uint64
|
||||||
|
|
||||||
// Architecture
|
// Architecture
|
||||||
Architecture string `json:"arch"`
|
Architecture string `json:"arch"`
|
||||||
@@ -168,17 +168,8 @@ type ItemSnapshot struct {
|
|||||||
Valid bool `json:"valid"`
|
Valid bool `json:"valid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of Snapshot
|
|
||||||
type ListSnapshots []ItemSnapshot
|
|
||||||
|
|
||||||
// List of Snapshots
|
// List of Snapshots
|
||||||
type ListInfoSnapshots struct {
|
type ListSnapshots []ItemSnapshot
|
||||||
// Data
|
|
||||||
Data ListSnapshots `json:"data"`
|
|
||||||
|
|
||||||
// EntryCount
|
|
||||||
EntryCount uint64 `json:"entryCount"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Main information about Group
|
// Main information about Group
|
||||||
type RecordGroup struct {
|
type RecordGroup struct {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RestoreRequest struct to restore BasicService instance
|
// Request struct for restores BasicService instance
|
||||||
type RestoreRequest struct {
|
type RestoreRequest struct {
|
||||||
// ID of the BasicService to be restored
|
// ID of the BasicService to be restored
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type RestoreRequest struct {
|
|||||||
func (b BService) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
func (b BService) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/restore"
|
url := "/cloudapi/bservice/restore"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotCreateRequest struct to create snapshot
|
// Request struct for create snapshot
|
||||||
type SnapshotCreateRequest struct {
|
type SnapshotCreateRequest struct {
|
||||||
// ID of the Basic Service
|
// ID of the Basic Service
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type SnapshotCreateRequest struct {
|
|||||||
func (b BService) SnapshotCreate(ctx context.Context, req SnapshotCreateRequest) (bool, error) {
|
func (b BService) SnapshotCreate(ctx context.Context, req SnapshotCreateRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/snapshotCreate"
|
url := "/cloudapi/bservice/snapshotCreate"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotDeleteRequest struct to delete snapshot
|
// Request struct for delete snapshot
|
||||||
type SnapshotDeleteRequest struct {
|
type SnapshotDeleteRequest struct {
|
||||||
// ID of the Basic Service
|
// ID of the Basic Service
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type SnapshotDeleteRequest struct {
|
|||||||
func (b BService) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) {
|
func (b BService) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/snapshotDelete"
|
url := "/cloudapi/bservice/snapshotDelete"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotListRequest struct to get list of existing snapshots
|
// Request struct for get list existing snapshots
|
||||||
type SnapshotListRequest struct {
|
type SnapshotListRequest struct {
|
||||||
// ID of the Basic Service
|
// ID of the Basic Service
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -16,10 +16,12 @@ 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) (*ListInfoSnapshots, error) {
|
func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (ListSnapshots, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/snapshotList"
|
url := "/cloudapi/bservice/snapshotList"
|
||||||
@@ -29,12 +31,12 @@ func (b BService) SnapshotList(ctx context.Context, req SnapshotListRequest) (*L
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
list := ListInfoSnapshots{}
|
list := ListSnapshots{}
|
||||||
|
|
||||||
err = json.Unmarshal(res, &list)
|
err = json.Unmarshal(res, &list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &list, nil
|
return list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotRollbackRequest struct to rollback snapshot
|
// Request struct for rollback snapshot
|
||||||
type SnapshotRollbackRequest struct {
|
type SnapshotRollbackRequest struct {
|
||||||
// ID of the Basic Service
|
// ID of the Basic Service
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type SnapshotRollbackRequest struct {
|
|||||||
func (b BService) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
|
func (b BService) SnapshotRollback(ctx context.Context, req SnapshotRollbackRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/snapshotRollback"
|
url := "/cloudapi/bservice/snapshotRollback"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// StartRequest struct to start service
|
// Request struct for start service
|
||||||
type StartRequest struct {
|
type StartRequest struct {
|
||||||
// ID of the service to start
|
// ID of the service to start
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -21,7 +21,9 @@ type StartRequest struct {
|
|||||||
func (b BService) Start(ctx context.Context, req StartRequest) (bool, error) {
|
func (b BService) Start(ctx context.Context, req StartRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/start"
|
url := "/cloudapi/bservice/start"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// StopRequest struct to stop service
|
// Request struct for stop service
|
||||||
type StopRequest struct {
|
type StopRequest struct {
|
||||||
// ID of the service to stop
|
// ID of the service to stop
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -21,7 +21,9 @@ type StopRequest struct {
|
|||||||
func (b BService) Stop(ctx context.Context, req StopRequest) (bool, error) {
|
func (b BService) Stop(ctx context.Context, req StopRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/stop"
|
url := "/cloudapi/bservice/stop"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityGroupCheckStartRequest struct to check all computes with current affinity label can start
|
// Request struct for check all computes with current affinity label can start
|
||||||
type AffinityGroupCheckStartRequest struct {
|
type AffinityGroupCheckStartRequest struct {
|
||||||
// ID of the resource group
|
// ID of the resource group
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -22,7 +22,9 @@ type AffinityGroupCheckStartRequest struct {
|
|||||||
func (c Compute) AffinityGroupCheckStart(ctx context.Context, req AffinityGroupCheckStartRequest) (string, error) {
|
func (c Compute) AffinityGroupCheckStart(ctx context.Context, req AffinityGroupCheckStartRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return "", validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityGroupCheckStart"
|
url := "/cloudapi/compute/affinityGroupCheckStart"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityLabelRemoveRequest struct to clear affinity label for compute
|
// Request struct for clear affinity label for compute
|
||||||
type AffinityLabelRemoveRequest struct {
|
type AffinityLabelRemoveRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AffinityLabelRemoveRequest struct {
|
|||||||
func (c Compute) AffinityLabelRemove(ctx context.Context, req AffinityLabelRemoveRequest) (bool, error) {
|
func (c Compute) AffinityLabelRemove(ctx context.Context, req AffinityLabelRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityLabelRemove"
|
url := "/cloudapi/compute/affinityLabelRemove"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityLabelSetRequest struct to set affinity label for compute
|
// Request struct for set affinity label for compute
|
||||||
type AffinityLabelSetRequest struct {
|
type AffinityLabelSetRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type AffinityLabelSetRequest struct {
|
|||||||
func (c Compute) AffinityLabelSet(ctx context.Context, req AffinityLabelSetRequest) (bool, error) {
|
func (c Compute) AffinityLabelSet(ctx context.Context, req AffinityLabelSetRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityLabelSet"
|
url := "/cloudapi/compute/affinityLabelSet"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityRelationsRequest struct to get dict of computes
|
// Request struct for get dict of computes
|
||||||
type AffinityRelationsRequest struct {
|
type AffinityRelationsRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AffinityRelationsRequest struct {
|
|||||||
func (c Compute) AffinityRelations(ctx context.Context, req AffinityRelationsRequest) (*RecordAffinityRelations, error) {
|
func (c Compute) AffinityRelations(ctx context.Context, req AffinityRelationsRequest) (*RecordAffinityRelations, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityRelations"
|
url := "/cloudapi/compute/affinityRelations"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityRuleAddRequest struct to add affinity rule
|
// Request struct for add affinity rule
|
||||||
type AffinityRuleAddRequest struct {
|
type AffinityRuleAddRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -38,16 +38,17 @@ type AffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: false
|
// Required: true
|
||||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
Value string `url:"value" json:"value" validate:"required"`
|
||||||
Value string `url:"value" json:"value"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleAdd add affinity rule
|
// AffinityRuleAdd add affinity rule
|
||||||
func (c Compute) AffinityRuleAdd(ctx context.Context, req AffinityRuleAddRequest) (bool, error) {
|
func (c Compute) AffinityRuleAdd(ctx context.Context, req AffinityRuleAddRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityRuleAdd"
|
url := "/cloudapi/compute/affinityRuleAdd"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityRuleRemoveRequest struct to remove affinity rule
|
// Request struct for remove affinity rule
|
||||||
type AffinityRuleRemoveRequest struct {
|
type AffinityRuleRemoveRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -38,16 +38,17 @@ type AffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: false
|
// Required: true
|
||||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
Value string `url:"value" json:"value" validate:"required"`
|
||||||
Value string `url:"value" json:"value"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleRemove remove affinity rule
|
// AffinityRuleRemove remove affinity rule
|
||||||
func (c Compute) AffinityRuleRemove(ctx context.Context, req AffinityRuleRemoveRequest) (bool, error) {
|
func (c Compute) AffinityRuleRemove(ctx context.Context, req AffinityRuleRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityRuleRemove"
|
url := "/cloudapi/compute/affinityRuleRemove"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AffinityRulesClearRequest struct to clear affinity rules
|
// Request struct for clear affinity rules
|
||||||
type AffinityRulesClearRequest struct {
|
type AffinityRulesClearRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AffinityRulesClearRequest struct {
|
|||||||
func (c Compute) AffinityRulesClear(ctx context.Context, req AffinityRulesClearRequest) (bool, error) {
|
func (c Compute) AffinityRulesClear(ctx context.Context, req AffinityRulesClearRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/affinityRulesClear"
|
url := "/cloudapi/compute/affinityRulesClear"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AntiAffinityRuleAddRequest struct to add anti affinity rule
|
// Request struct for add anti affinity rule
|
||||||
type AntiAffinityRuleAddRequest struct {
|
type AntiAffinityRuleAddRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -38,16 +38,17 @@ type AntiAffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: false
|
// Required: true
|
||||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
Value string `url:"value" json:"value" validate:"required"`
|
||||||
Value string `url:"value" json:"value"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleAdd add anti affinity rule
|
// AntiAffinityRuleAdd add anti affinity rule
|
||||||
func (c Compute) AntiAffinityRuleAdd(ctx context.Context, req AntiAffinityRuleAddRequest) (bool, error) {
|
func (c Compute) AntiAffinityRuleAdd(ctx context.Context, req AntiAffinityRuleAddRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/antiAffinityRuleAdd"
|
url := "/cloudapi/compute/antiAffinityRuleAdd"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AntiAffinityRuleRemoveRequest struct to remove anti affinity rule
|
// Request struct for remove anti affinity rule
|
||||||
type AntiAffinityRuleRemoveRequest struct {
|
type AntiAffinityRuleRemoveRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -38,16 +38,17 @@ type AntiAffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: false
|
// Required: true
|
||||||
// Not required on purpose: despite required tag on platform, empty string is allowed
|
Value string `url:"value" json:"value" validate:"required"`
|
||||||
Value string `url:"value" json:"value"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleRemove remove anti affinity rule
|
// AntiAffinityRuleRemove remove anti affinity rule
|
||||||
func (c Compute) AntiAffinityRuleRemove(ctx context.Context, req AntiAffinityRuleRemoveRequest) (bool, error) {
|
func (c Compute) AntiAffinityRuleRemove(ctx context.Context, req AntiAffinityRuleRemoveRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/antiAffinityRuleRemove"
|
url := "/cloudapi/compute/antiAffinityRuleRemove"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AntiAffinityRulesClearRequest struct to clear anti affinity rules
|
// Request struct for clear anti affinity rules
|
||||||
type AntiAffinityRulesClearRequest struct {
|
type AntiAffinityRulesClearRequest struct {
|
||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AntiAffinityRulesClearRequest struct {
|
|||||||
func (c Compute) AntiAffinityRulesClear(ctx context.Context, req AntiAffinityRulesClearRequest) (bool, error) {
|
func (c Compute) AntiAffinityRulesClear(ctx context.Context, req AntiAffinityRulesClearRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/antiAffinityRulesClear"
|
url := "/cloudapi/compute/antiAffinityRulesClear"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AttachGPURequest struct to attach GPU for compute
|
// Request struct for attach GPU for compute
|
||||||
type AttachGPURequest struct {
|
type AttachGPURequest struct {
|
||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type AttachGPURequest struct {
|
|||||||
func (c Compute) AttachGPU(ctx context.Context, req AttachGPURequest) (uint64, error) {
|
func (c Compute) AttachGPU(ctx context.Context, req AttachGPURequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/attachGpu"
|
url := "/cloudapi/compute/attachGpu"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AttachPCIDeviceRequest struct to attach PCI device
|
// Request struct for atttach PCI device
|
||||||
type AttachPCIDeviceRequest struct {
|
type AttachPCIDeviceRequest struct {
|
||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type AttachPCIDeviceRequest struct {
|
|||||||
func (c Compute) AttachPCIDevice(ctx context.Context, req AttachPCIDeviceRequest) (bool, error) {
|
func (c Compute) AttachPCIDevice(ctx context.Context, req AttachPCIDeviceRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/attachPciDevice"
|
url := "/cloudapi/compute/attachPciDevice"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AuditsRequest struct to get audit records
|
// Request struct for get audit records
|
||||||
type AuditsRequest struct {
|
type AuditsRequest struct {
|
||||||
// ID of the compute
|
// ID of the compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type AuditsRequest struct {
|
|||||||
func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/audits"
|
url := "/cloudapi/compute/audits"
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BootOrderGetRequest struct to get boot order
|
// Request struct for getting boot order
|
||||||
type BootOrderGetRequest struct {
|
type BootOrderGetRequest struct {
|
||||||
// Compute ID
|
// Compute ID
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -18,7 +18,9 @@ type BootOrderGetRequest struct {
|
|||||||
func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) {
|
func (c Compute) BootOrderGet(ctx context.Context, req BootOrderGetRequest) ([]string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/bootOrderGet"
|
url := "/cloudapi/compute/bootOrderGet"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BootOrderSetRequest struct to set boot order
|
// Request struct for setting boot order
|
||||||
type BootOrderSetRequest struct {
|
type BootOrderSetRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -26,7 +26,9 @@ type BootOrderSetRequest struct {
|
|||||||
func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) {
|
func (c Compute) BootOrderSet(ctx context.Context, req BootOrderSetRequest) ([]string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return nil, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/bootOrderSet"
|
url := "/cloudapi/compute/bootOrderSet"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CDEjectRequest struct to eject CD image
|
// Request struct for eject CD image
|
||||||
type CDEjectRequest struct {
|
type CDEjectRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type CDEjectRequest struct {
|
|||||||
func (c Compute) CDEject(ctx context.Context, req CDEjectRequest) (bool, error) {
|
func (c Compute) CDEject(ctx context.Context, req CDEjectRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/cdEject"
|
url := "/cloudapi/compute/cdEject"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CDInsertRequest struct to insert new CD image
|
// Request struct for insert new CD image
|
||||||
type CDInsertRequest struct {
|
type CDInsertRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type CDInsertRequest struct {
|
|||||||
func (c Compute) CDInsert(ctx context.Context, req CDInsertRequest) (bool, error) {
|
func (c Compute) CDInsert(ctx context.Context, req CDInsertRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/cdInsert"
|
url := "/cloudapi/compute/cdInsert"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ChangeLinkStateRequest struct to change link state
|
// Request struct for changing link state
|
||||||
type ChangeLinkStateRequest struct {
|
type ChangeLinkStateRequest struct {
|
||||||
// Compute ID
|
// Compute ID
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +27,9 @@ type ChangeLinkStateRequest struct {
|
|||||||
func (c Compute) ChangeLinkState(ctx context.Context, req ChangeLinkStateRequest) (bool, error) {
|
func (c Compute) ChangeLinkState(ctx context.Context, req ChangeLinkStateRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/changeLinkState"
|
url := "/cloudapi/compute/changeLinkState"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CloneRequest struct to clone compute instance
|
// Request struct for clone compute instance
|
||||||
type CloneRequest struct {
|
type CloneRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -31,7 +31,9 @@ type CloneRequest struct {
|
|||||||
func (c Compute) Clone(ctx context.Context, req CloneRequest) (uint64, error) {
|
func (c Compute) Clone(ctx context.Context, req CloneRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/clone"
|
url := "/cloudapi/compute/clone"
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateTemplateRequest struct to create template
|
// Request struct for create template
|
||||||
type CreateTemplateRequest struct {
|
type CreateTemplateRequest struct {
|
||||||
// ID of the compute to create template from
|
// ID of the compute to create template from
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -30,7 +30,9 @@ type wrapperCreateTemplateRequest struct {
|
|||||||
func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (uint64, error) {
|
func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (uint64, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return 0, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateTemplateRequest{
|
reqWrapped := wrapperCreateTemplateRequest{
|
||||||
@@ -57,7 +59,9 @@ func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest)
|
|||||||
func (c Compute) CreateTemplateAsync(ctx context.Context, req CreateTemplateRequest) (string, error) {
|
func (c Compute) CreateTemplateAsync(ctx context.Context, req CreateTemplateRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return "", validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateTemplateRequest{
|
reqWrapped := wrapperCreateTemplateRequest{
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteRequest struct to delete compute
|
// Request struct for delete compute
|
||||||
type DeleteRequest struct {
|
type DeleteRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -27,7 +27,9 @@ type DeleteRequest struct {
|
|||||||
func (c Compute) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
func (c Compute) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/delete"
|
url := "/cloudapi/compute/delete"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteCustomFieldsRequest struct to delete compute's custom fields
|
// Request struct for deleting compute's custome fields
|
||||||
type DeleteCustomFieldsRequest struct {
|
type DeleteCustomFieldsRequest struct {
|
||||||
// ID of the compute
|
// ID of the compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type DeleteCustomFieldsRequest struct {
|
|||||||
func (c Compute) DeleteCustomFields(ctx context.Context, req DeleteCustomFieldsRequest) (bool, error) {
|
func (c Compute) DeleteCustomFields(ctx context.Context, req DeleteCustomFieldsRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/deleteCustomFields"
|
url := "/cloudapi/compute/deleteCustomFields"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DetachGPURequest struct to detach vgpu for compute
|
// Request struct for detach vgpu for compute
|
||||||
type DetachGPURequest struct {
|
type DetachGPURequest struct {
|
||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -24,7 +24,9 @@ type DetachGPURequest struct {
|
|||||||
func (c Compute) DetachGPU(ctx context.Context, req DetachGPURequest) (bool, error) {
|
func (c Compute) DetachGPU(ctx context.Context, req DetachGPURequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/detachGpu"
|
url := "/cloudapi/compute/detachGpu"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DetachPCIDeviceRequest struct to detach PCI device
|
// Request struct for detach PCI device
|
||||||
type DetachPCIDeviceRequest struct {
|
type DetachPCIDeviceRequest struct {
|
||||||
// Identifier compute
|
// Identifier compute
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -23,7 +23,9 @@ type DetachPCIDeviceRequest struct {
|
|||||||
func (c Compute) DetachPCIDevice(ctx context.Context, req DetachPCIDeviceRequest) (bool, error) {
|
func (c Compute) DetachPCIDevice(ctx context.Context, req DetachPCIDeviceRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/detachPciDevice"
|
url := "/cloudapi/compute/detachPciDevice"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DisableRequest struct to disable compute
|
// Request struct for disable compute
|
||||||
type DisableRequest struct {
|
type DisableRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
@@ -19,7 +19,9 @@ type DisableRequest struct {
|
|||||||
func (c Compute) Disable(ctx context.Context, req DisableRequest) (bool, error) {
|
func (c Compute) Disable(ctx context.Context, req DisableRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
for _, validationError := range validators.GetErrors(err) {
|
||||||
|
return false, validators.ValidationError(validationError)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/disable"
|
url := "/cloudapi/compute/disable"
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user