Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
095a18f27a | ||
|
|
84a090f9e8 | ||
| befff7acd9 | |||
|
|
abd35f858c | ||
|
|
825b1a0a00 | ||
|
|
e10ee7f801 | ||
|
|
7dacf35cd6 | ||
|
|
1f8637400f | ||
| 89831894df | |||
| 92431c5c65 | |||
|
|
c7a2c4ed5a | ||
| 0c44daa241 | |||
|
|
650b1c158b | ||
| 8a101c6fcb | |||
|
|
3f21a89e80 | ||
| cbce7f434f | |||
| e04dc42d2b | |||
|
|
88eb9e8898 | ||
| 9ec34c6bfc | |||
| 80491ed643 | |||
| f1e0f7abb6 | |||
| 8eeef825c0 | |||
| 9a7a7b6f36 | |||
| 3393934456 | |||
| e7c968797b | |||
| bc264c4d90 | |||
| d137c7507a | |||
| 55027a1605 | |||
| de9cca4053 | |||
| 83bf1fb1fa | |||
| 16cad7a3e7 | |||
| 96273d2a12 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -3,3 +3,8 @@ cmd/
|
|||||||
.vscode/
|
.vscode/
|
||||||
.fleet/
|
.fleet/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
tests/platform_upgrade/.env
|
||||||
|
tests/platform_upgrade/input.json
|
||||||
|
tests/platform_upgrade/*.txt
|
||||||
|
tests/platform_upgrade/*.log
|
||||||
|
*.env
|
||||||
|
|||||||
35
CHANGELOG.md
35
CHANGELOG.md
@@ -1,7 +1,32 @@
|
|||||||
## Version 1.7.3
|
## Version 1.12.6
|
||||||
|
|
||||||
## Bugfix
|
Методы `Audits` в cloudapi/compute, cloudbroker/compute, cloudapi/account, cloudbroker/account, cloudapi/vins, cloudbroker/vins, cloudapi/rg и cloudbroker/rg стали deprecated и в следующих версиях будут удалены, вместо них необходимо использовать метод `List` в cloudapi/audit и cloudbroker/audit с соответствующими фильтрами
|
||||||
|
Метод `ListStacks` в cloudbroker/image стал deprecated и в следующих версиях будет удалён
|
||||||
|
Методы `AccessGrant`, `AccessGrantToPool`, `AccessRevoke`, `AccessRevokeToPool` в cloudbroker/sep стали deprecated и в следующих версиях будут удалены
|
||||||
|
|
||||||
- Refactoring clients
|
### Добавлено
|
||||||
- Add fields FrontendHAIP and BackendHAIP in model ItemLB in cloudbroker/rg and RecordLoadBalancer in cloudapi/rg
|
|
||||||
- Add field AuthBroker in ItemLocation model in cloudapi/locations
|
#### общее
|
||||||
|
| Идентификатор<br>задачи | Описание |
|
||||||
|
| --- | --- |
|
||||||
|
| BGOS-638 | Добавлена поддержка версий 4.1.0 и 4.2.0 в функцию check |
|
||||||
|
|
||||||
|
#### image
|
||||||
|
| Идентификатор<br>задачи | Описание |
|
||||||
|
| --- | --- |
|
||||||
|
| BGOS-481 | Метод `AsyncCreateCDROMImage` в cloudbroker/image |
|
||||||
|
|
||||||
|
#### node
|
||||||
|
| Идентификатор<br>задачи | Описание |
|
||||||
|
| --- | --- |
|
||||||
|
| BGOS-634 | Метод `UpdateDescription` и структура запроса `UpdateDescriptionRequest` в cloudbroker/node |
|
||||||
|
|
||||||
|
#### stpolicy
|
||||||
|
| Идентификатор<br>задачи | Описание |
|
||||||
|
| --- | --- |
|
||||||
|
| BGOS-636 | Вычисляемое поле `StoragePolicyID` в структуры ответа `InfoStoragePolicy` и `ItemStoragePolicy` в `cloudapi/stpolicy` и в cloudbroker/stpolicy |
|
||||||
|
|
||||||
|
#### vins
|
||||||
|
| Идентификатор<br>задачи | Описание |
|
||||||
|
| --- | --- |
|
||||||
|
| BGOS-637 | Вычисляемое поле `LiveMigrationJobID` в структуры ответа `RecordVNFDev` в cloudapi/vins и в `VNFDev` cloudbroker/vins |
|
||||||
|
|||||||
2
LICENSE
2
LICENSE
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
|||||||
same "printed page" as the copyright notice for easier
|
same "printed page" as the copyright notice for easier
|
||||||
identification within third-party archives.
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
Copyright 2022 Basis LTD
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
476
README.md
476
README.md
@@ -1,6 +1,6 @@
|
|||||||
# Decort SDK
|
# Decort SDK
|
||||||
|
|
||||||
Decort SDK - это библиотека, написанная на языке GO, позволяющая взаимодействовать с API облачной платформы **DECORT**. Библиотека содеражит в себе структуры и методы, необходимые для отправки запросов. Decort SDK имеет встроенный http-клиент и поддерживает разные способы авторизации на платформе. Библиотека так же содержит в себе модели ответов от платформы.
|
Decort SDK - это библиотека, написанная на языке GO, позволяющая взаимодействовать с API облачной платформы **DECORT**. Библиотека содержит в себе структуры и методы, необходимые для отправки запросов. Decort SDK имеет встроенный http-клиент и поддерживает разные способы авторизации на платформе. Библиотека так же содержит в себе модели ответов от платформы.
|
||||||
|
|
||||||
## Версии
|
## Версии
|
||||||
|
|
||||||
@@ -12,49 +12,76 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
||||||
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
||||||
- Версия 1.7.х Decort-SDK соответствует 3.8.9 версии платформы
|
- Версия 1.7.х Decort-SDK соответствует 3.8.9 версии платформы
|
||||||
|
- Версия 1.8.х Decort-SDK соответствует 4.0.0 версии платформы
|
||||||
|
- Версия 1.9.х Decort-SDK соответствует 4.1.0 версии платформы
|
||||||
|
- Версия 1.10.х Decort-SDK соответствует 4.2.0 версии платформы
|
||||||
|
- Версия 1.11.х Decort-SDK соответствует 4.3.0 версии платформы
|
||||||
|
- Версия 1.12.х Decort-SDK соответствует 4.4.0 версии платформы
|
||||||
|
|
||||||
## Оглавление
|
## Оглавление
|
||||||
|
|
||||||
- [Установка](#установка)
|
- [Decort SDK](#decort-sdk)
|
||||||
- [Список API](#список-api)
|
- [Версии](#версии)
|
||||||
|
- [Оглавление](#оглавление)
|
||||||
|
- [Установка](#установка)
|
||||||
|
- [Список API](#список-api)
|
||||||
- [Cloudapi](#cloudapi)
|
- [Cloudapi](#cloudapi)
|
||||||
- [Cloudbroker](#cloudbroker)
|
- [Cloudbroker](#cloudbroker)
|
||||||
- [Работа с библиотекой](#работа-с-библиотекой)
|
- [Работа с библиотекой](#работа-с-библиотекой)
|
||||||
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
- [Настройка конфигурации клиента](#настройка-конфигурации-клиента)
|
||||||
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
- [Пример конфигурации клиента](#пример-конфигурации-клиента)
|
||||||
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
- [Парсинг конфигурации из файла](#парсинг-конфигурации-из-файла)
|
||||||
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
- [Пример JSON конфигурации](#пример-json-конфигурации)
|
||||||
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
- [Пример YAML конфигурации](#пример-yaml-конфигурации)
|
||||||
- [Создание клиента](#создание-клиента)
|
- [Создание клиента](#создание-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Пример](#пример)
|
||||||
|
- [Создание структуры запроса](#создание-структуры-запроса)
|
||||||
|
- [Пример комментариев структуры](#пример-комментариев-структуры)
|
||||||
|
- [Пример создания запроса для развертывания виртуальной машины:](#пример-создания-запроса-для-развертывания-виртуальной-машины)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Выполнение запроса](#выполнение-запроса)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса)
|
||||||
|
- [Пример выполнения GetRaw и ListRaw запросов](#пример-выполнения-getraw-и-listraw-запросов)
|
||||||
- [Фильтрация](#фильтрация)
|
- [Фильтрация](#фильтрация)
|
||||||
|
- [Использование на примере `compute.FilterByK8SID`:](#использование-на-примере-computefilterbyk8sid)
|
||||||
- [Сортировка](#сортировка)
|
- [Сортировка](#сортировка)
|
||||||
- [Сериализация](#сериализация)
|
- [Сериализация](#сериализация)
|
||||||
- [Получение списка уникальных идентификаторов (ID) объекта](#получение-списка-уникальных-идентификаторов-id-объекта)
|
- [Комплексный пример](#комплексный-пример)
|
||||||
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
- [Получение списка уникальных идентификаторов ID объекта](#получение-списка-уникальных-идентификаторов-id-объекта)
|
||||||
|
- [Методы поля Result для группы tasks](#методы-поля-result-для-группы-tasks)
|
||||||
|
- [Работа с legacy клиентом](#работа-с-legacy-клиентом)
|
||||||
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
- [Настройка конфигурации legacy клиента](#настройка-конфигурации-legacy-клиента)
|
||||||
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
- [Пример конфигурации legacy клиента](#пример-конфигурации-legacy-клиента)
|
||||||
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
- [Парсинг legacy конфигурации из файла](#парсинг-legacy-конфигурации-из-файла)
|
||||||
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
- [Пример legacy JSON конфигурации](#пример-legacy-json-конфигурации)
|
||||||
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
- [Пример legacy YAML конфигурации](#пример-legacy-yaml-конфигурации)
|
||||||
- [Создание legacy клиента](#создание-legacy-клиента)
|
- [Создание legacy клиента](#создание-legacy-клиента)
|
||||||
- [Создание структуры запроса](#cоздание-структуры-запроса)
|
- [Пример создания legacy клиента](#пример-создания-legacy-клиента)
|
||||||
- [Выполнение запроса](#выполнение-запроса)
|
- [Пример выполнения запроса](#пример-выполнения-запроса-1)
|
||||||
- [Работа с BVS клиентом](#работа-с-bvs-клиентом)
|
- [Работа с BVS клиентом](#работа-с-bvs-клиентом)
|
||||||
- [Настройка параметров BVS в кабинете администратора](#настройка-параметров-bvs-в-кабинете-администратора)
|
- [Настройка параметров BVS в кабинете администратора](#настройка-параметров-bvs-в-кабинете-администратора)
|
||||||
- [Настройка конфигурации BVS клиента](#настройка-конфигурации-bvs-клиента)
|
- [Настройка конфигурации BVS клиента](#настройка-конфигурации-bvs-клиента)
|
||||||
- [Описание структуры token](#описание-структуры-token)
|
- [Описание структуры token](#описание-структуры-token)
|
||||||
- [Пример конфигурации BVS клиента](#пример-конфигурации-bvs-клиента)
|
- [Пример конфигурации BVS клиента](#пример-конфигурации-bvs-клиента)
|
||||||
- [Парсинг BVS конфигурации из файла](#парсинг-bvs-конфигурации-из-файла)
|
- [Парсинг BVS конфигурации из файла](#парсинг-bvs-конфигурации-из-файла)
|
||||||
- [Парсинг BVS токена из файла](#парсинг-bvs-токена-из-файла)
|
- [Парсинг BVS токена из файла](#парсинг-bvs-токена-из-файла)
|
||||||
- [Пример BVS JSON конфигурации](#пример-bvs-json-конфигурации)
|
- [Пример BVS JSON конфигурации](#пример-bvs-json-конфигурации)
|
||||||
- [Пример BVS YAML конфигурации](#пример-bvs-yaml-конфигурации)
|
- [Пример BVS YAML конфигурации](#пример-bvs-yaml-конфигурации)
|
||||||
- [Создание BVS клиента](#создание-bvs-клиента)
|
- [Создание BVS клиента](#создание-bvs-клиента)
|
||||||
- [Пример создания BVS клиента](#пример-создания-bvs-клиента)
|
- [Пример создания BVS клиента](#пример-создания-bvs-клиента)
|
||||||
- [Пример получения BVS токена](#пример-получения-bvs-токена)
|
- [Пример получения BVS токена](#пример-получения-bvs-токена)
|
||||||
- [Пример обновления BVS токена](#пример-обновления-bvs-токена)
|
- [Пример обновления BVS токена](#пример-обновления-bvs-токена)
|
||||||
- [Пример выполнения запроса](#пример-выполнения-запроса)
|
- [Пример выполнения запроса](#пример-выполнения-запроса-2)
|
||||||
|
- [Пример валидации запросов, имеющих в своей структуре поле RAM (или MasterRam/WorkerRAM)](#пример-валидации-запросов-имеющих-в-своей-структуре-поле-ram-или-masterramworkerram)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-3)
|
||||||
|
- [Работа с универсальным клиентом](#работа-с-универсальным-клиентом)
|
||||||
|
- [Настройка конфигурации универсального клиента](#настройка-конфигурации-универсального-клиента)
|
||||||
|
- [Пример конфигурации универсального клиента](#пример-конфигурации-универсального-клиента)
|
||||||
|
- [Парсинг универсальной конфигурации из файла](#парсинг-универсальной-конфигурации-из-файла)
|
||||||
|
- [Создание универсального клиента](#создание-универсального-клиента)
|
||||||
|
- [Пример создания универсального клиента](#пример-создания-универсального-клиента)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-4)
|
||||||
|
- [Проверка соответствия версии платформы и версии dynamix](#проверка-соответствия-версии-платформы-и-версии-dynamix)
|
||||||
|
- [Пример выполнения запроса](#пример-выполнения-запроса-5)
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
@@ -70,6 +97,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
|
|
||||||
- `cloudapi` - пользовательская группа, которая позволяет воспользоваться всем стардартным функционалом платформы;
|
- `cloudapi` - пользовательская группа, которая позволяет воспользоваться всем стардартным функционалом платформы;
|
||||||
- `cloudbroker` - административная группа, которая позволяет воспользоваться всем стандартным функционалом платформы и расширенными возможностями, включающими в себя управление пользователями, ресурсами, платформами размещения ресурсов и т.д.
|
- `cloudbroker` - административная группа, которая позволяет воспользоваться всем стандартным функционалом платформы и расширенными возможностями, включающими в себя управление пользователями, ресурсами, платформами размещения ресурсов и т.д.
|
||||||
|
- `sdn` - группа для работы с SDN;
|
||||||
|
|
||||||
### Cloudapi
|
### Cloudapi
|
||||||
|
|
||||||
@@ -77,23 +105,30 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
||||||
|
|
||||||
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
||||||
|
- `Audit` - получение информации о событиях системы;
|
||||||
- `BService` - управление группами виртуальных машин (computes);
|
- `BService` - управление группами виртуальных машин (computes);
|
||||||
- `Compute` - управление виртуальными машинами (индивидуально);
|
- `Compute` - управление виртуальными машинами (индивидуально);
|
||||||
- `Disks` - управление виртуальными дисками;
|
- `Disks` - управление виртуальными дисками;
|
||||||
|
- `DPDK` - управление виртуальными сетями DPDK;
|
||||||
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
||||||
- `FLIPgroup` - управление группами "плавающими" ip - адресами;
|
- `FLIPgroup` - управление группами "плавающими" ip - адресами;
|
||||||
- `Image` - управление образами операционных систем;
|
- `Image` - управление образами операционных систем;
|
||||||
- `K8CI` - получение информации о конвейере для создания кластера;
|
- `K8CI` - получение информации о конвейере для создания кластера;
|
||||||
- `K8S` - управление кластерами kubernetes;
|
- `K8S` - управление кластерами kubernetes;
|
||||||
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
|
||||||
- `KVMx86` - создание виртуальной машины x86;
|
- `KVMx86` - создание виртуальной машины x86;
|
||||||
- `LB` - управление балансировщиками нагрузки;
|
- `LB` - управление балансировщиками нагрузки;
|
||||||
- `Locations` - получение информации о grid площадки;
|
- `Locations` - получение информации о grid площадки;
|
||||||
|
- `Prometheus` - получение статистики prometheus;
|
||||||
- `RG` - управление ресурсными группами аккаунта;
|
- `RG` - управление ресурсными группами аккаунта;
|
||||||
- `Sizes` - получение информации о потребляемых ресурсах виртуальными машинами и дисками;
|
- `Security group` – управление группами безопасности;
|
||||||
|
- `SEP` - управление storage endpoint (sep);
|
||||||
- `Stack` - получение информации о вычислительных узлах;
|
- `Stack` - получение информации о вычислительных узлах;
|
||||||
|
- `Storage policy` – получение информации о политиках хранения;
|
||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `Trunk` - получение информации о транковых портах;
|
||||||
|
- `VFPool` - управление пулом виртуальных сетевых функций;
|
||||||
|
- `VINS` - управление виртуальными изолированными сетями;
|
||||||
|
- `Zone` - управление зонами.
|
||||||
|
|
||||||
### Cloudbroker
|
### Cloudbroker
|
||||||
|
|
||||||
@@ -101,10 +136,13 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
||||||
|
|
||||||
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
- `Account` - управление аккаунтами - внутренними учетными записями платформы, которые являются владельцами вычислительных ресурсов;
|
||||||
|
- `Audit` - получение информации о событиях системы;
|
||||||
- `APIAccess` - управление доступом к API и его объектам;
|
- `APIAccess` - управление доступом к API и его объектам;
|
||||||
- `Backup` - управление резервным копированием;
|
- `Backup` - управление резервным копированием;
|
||||||
|
- `BService` - управление группами виртуальных машин (computes);
|
||||||
- `Compute` - управление виртуальными машинами (индивидуально);
|
- `Compute` - управление виртуальными машинами (индивидуально);
|
||||||
- `Disks` - управление виртуальными дисками;
|
- `Disks` - управление виртуальными дисками;
|
||||||
|
- `DPDK` - управление виртуальными сетями DPDK;
|
||||||
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
- `ExtNet` - управление виртуальными сетями, отвечающими за внешний доступ;
|
||||||
- `FLIPGroup` - управление группами с «плавающими» ip адресами;
|
- `FLIPGroup` - управление группами с «плавающими» ip адресами;
|
||||||
- `Grid` - управление площадками;
|
- `Grid` - управление площадками;
|
||||||
@@ -112,17 +150,31 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
- `Image` - управление образами операционных систем;
|
- `Image` - управление образами операционных систем;
|
||||||
- `K8CI` - управление конвейром для создания кластера;
|
- `K8CI` - управление конвейром для создания кластера;
|
||||||
- `K8S` - управление кластерами kubernetes;
|
- `K8S` - управление кластерами kubernetes;
|
||||||
- `KVMPPC` - создание виртуальной машины Power PC (IBM);
|
|
||||||
- `KVMx86` - создание виртуальной машины x86;
|
- `KVMx86` - создание виртуальной машины x86;
|
||||||
- `LB` - управление балансировщиками нагрузки;
|
- `LB` - управление балансировщиками нагрузки;
|
||||||
|
- `Node` - управление нодами платформы;
|
||||||
- `PCIDevice` - управление устройствами;
|
- `PCIDevice` - управление устройствами;
|
||||||
|
- `Prometheus` - получение статистики prometheus;
|
||||||
|
- `Resmon` - получение статистики resource monitoring;
|
||||||
- `RG` - управление ресурсными группами аккаунта;
|
- `RG` - управление ресурсными группами аккаунта;
|
||||||
|
- `Security group` – управление группами безопасности;
|
||||||
- `SEP` - управление storage endpoint (sep);
|
- `SEP` - управление storage endpoint (sep);
|
||||||
- `Stack` - получение информации о вычислительных узлах;
|
- `Stack` - получение информации о вычислительных узлах;
|
||||||
|
- `Storage policy` – управление политиками хранения;
|
||||||
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
- `Tasks` - получение информации о ходе выполнения асинхронных задач (например, создание кластера);
|
||||||
|
- `Trunk` - управление транковыми портами;
|
||||||
- `User` - управление пользователями (индивидуально);
|
- `User` - управление пользователями (индивидуально);
|
||||||
- `VGPU` - управление виртуальными графическими процессорами;
|
- `VGPU` - управление виртуальными графическими процессорами;
|
||||||
|
- `VFPool` - управление пулом виртуальных сетевых функций;
|
||||||
- `VINS` - управление виртуальными изолированными сетями.
|
- `VINS` - управление виртуальными изолированными сетями.
|
||||||
|
- `Zone` - управление зонами.
|
||||||
|
|
||||||
|
### SDN
|
||||||
|
|
||||||
|
`SDN` позволяет выполнять запросы к группе пользовательских конечных точек
|
||||||
|
Данная группа ручек позволяет выполнять следующие операции в платформе:
|
||||||
|
|
||||||
|
- `AccessGroup` - управление группами доступа
|
||||||
|
|
||||||
## Работа с библиотекой
|
## Работа с библиотекой
|
||||||
|
|
||||||
@@ -149,7 +201,7 @@ go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|||||||
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||||
| Token | string | Нет | JWT токен |
|
| Token | string | Нет | JWT токен |
|
||||||
|
|
||||||
#### Пример конфигурации клиента
|
##### Пример конфигурации клиента
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
@@ -250,34 +302,45 @@ func main() {
|
|||||||
|
|
||||||
- `pkg/cloudapi` - для `cloudapi`
|
- `pkg/cloudapi` - для `cloudapi`
|
||||||
- `pkg/cloudbroker` - для `cloudbroker`
|
- `pkg/cloudbroker` - для `cloudbroker`
|
||||||
|
- `pkg/sdn` - для `sdn`
|
||||||
|
|
||||||
В каждом пакете находятся пакеты групп API:
|
В каждом пакете находятся пакеты групп API:
|
||||||
|
|
||||||
- **cloudapi**:
|
- **cloudapi**:
|
||||||
- `pkg/cloudapi/account` - для `Account`
|
- `pkg/cloudapi/account` - для `Account`
|
||||||
|
- `pkg/cloudapi/audit` - для `Audit`
|
||||||
- `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/dpdknet` - для `DPDK`
|
||||||
- `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/kvmx86` - для `KVMX86`
|
- `pkg/cloudapi/kvmx86` - для `KVMX86`
|
||||||
- `pkg/cloudapi/lb` - для `LB`
|
- `pkg/cloudapi/lb` - для `LB`
|
||||||
- `pkg/cloudapi/locations` - для `Locations`
|
- `pkg/cloudapi/locations` - для `Locations`
|
||||||
|
- `pkg/cloudapi/prometheus` - для `Prometheus`
|
||||||
- `pkg/cloudapi/rg` - для `RG`
|
- `pkg/cloudapi/rg` - для `RG`
|
||||||
- `pkg/cloudapi/sizes` - для `Sizes`
|
- `pkg/cloudapi/secgroup` - для `Security group`
|
||||||
|
- `pkg/cloudapi/sep` - для `SEP`
|
||||||
- `pkg/cloudapi/stack` - для `Stack`
|
- `pkg/cloudapi/stack` - для `Stack`
|
||||||
|
- `pkg/cloudapi/stpolicy` - для `Storage policy`
|
||||||
- `pkg/cloudapi/tasks` - для `Tasks`
|
- `pkg/cloudapi/tasks` - для `Tasks`
|
||||||
|
- `pkg/cloudapi/trunk` - для `Trunk`
|
||||||
|
- `pkg/cloudapi/vfpool` - для `VFPool`
|
||||||
- `pkg/cloudapi/vins` - для `VINS`
|
- `pkg/cloudapi/vins` - для `VINS`
|
||||||
|
- `pkg/cloudapi/zone` - для `Zone`
|
||||||
- **cloudbroker**:
|
- **cloudbroker**:
|
||||||
- `pkg/cloudbroker/account` - для `Account`
|
- `pkg/cloudbroker/account` - для `Account`
|
||||||
|
- `pkg/cloudbroker/audit` - для `Audit`
|
||||||
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
|
- `pkg/cloudbroker/apiaccess` - для `APIAccess`
|
||||||
- `pkg/cloudbroker/backup` - для `Backup`
|
- `pkg/cloudbroker/backup` - для `Backup`
|
||||||
|
- `pkg/cloudbroker/bservice` - для `Basic Service`
|
||||||
- `pkg/cloudbroker/compute` - для `Compute`
|
- `pkg/cloudbroker/compute` - для `Compute`
|
||||||
- `pkg/cloudbroker/disks` - для `Disks`
|
- `pkg/cloudbroker/disks` - для `Disks`
|
||||||
|
- `pkg/cloudbroker/dpdknet` - для `DPDK`
|
||||||
- `pkg/cloudbroker/extnet` - для `ExtNet`
|
- `pkg/cloudbroker/extnet` - для `ExtNet`
|
||||||
- `pkg/cloudbroker/flipgroup` - для `FLIPGroup`
|
- `pkg/cloudbroker/flipgroup` - для `FLIPGroup`
|
||||||
- `pkg/cloudbroker/grid` - для `Grid`
|
- `pkg/cloudbroker/grid` - для `Grid`
|
||||||
@@ -285,17 +348,26 @@ func main() {
|
|||||||
- `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/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/prometheus` - для `Prometheus`
|
||||||
|
- `pkg/cloudbroker/resmon` - для `Resmon`
|
||||||
- `pkg/cloudbroker/rg` - для `RG`
|
- `pkg/cloudbroker/rg` - для `RG`
|
||||||
|
- `pkg/cloudbroker/secgroup` - для `Security group`
|
||||||
- `pkg/cloudbroker/sep` - для `SEP`
|
- `pkg/cloudbroker/sep` - для `SEP`
|
||||||
- `pkg/cloudbroker/stack` - для `Stack`
|
- `pkg/cloudbroker/stack` - для `Stack`
|
||||||
|
- `pkg/cloudbroker/stpolicy` - для `Storage policy`
|
||||||
- `pkg/cloudbroker/tasks` - для `Tasks`
|
- `pkg/cloudbroker/tasks` - для `Tasks`
|
||||||
|
- `pkg/cloudbroker/trunk` - для `Trunk`
|
||||||
- `pkg/cloudbroker/user` - для `User`
|
- `pkg/cloudbroker/user` - для `User`
|
||||||
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
- `pkg/cloudbroker/vgpu` - для `VGPU`
|
||||||
|
- `pkg/cloudbroker/vfpool` - для `VFPool`
|
||||||
- `pkg/cloudbroker/vins` - для `VINS`
|
- `pkg/cloudbroker/vins` - для `VINS`
|
||||||
|
- `pkg/cloudbroker/zone` - для `Zone`
|
||||||
|
- **sdn**:
|
||||||
|
- `pkg/sdn/access_groups` - для `AccessGroups`
|
||||||
|
|
||||||
Все поля структуры имеют описание, в которых содержится:
|
Все поля структуры имеют описание, в которых содержится:
|
||||||
|
|
||||||
@@ -385,9 +457,7 @@ type CreateRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IPAType string `url:"ipaType,omitempty" json:"ipaType,omitempty"`
|
IPAType string `url:"ipaType,omitempty" json:"ipaType,omitempty"`
|
||||||
|
|
||||||
// Reason for action
|
|
||||||
// Required: false
|
|
||||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -431,37 +501,47 @@ func main() {
|
|||||||
|
|
||||||
Чтобы выполнить запрос, необходимо:
|
Чтобы выполнить запрос, необходимо:
|
||||||
|
|
||||||
1. Вызвать у клиента метод, отвечаеющий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, либо `.CloudBroker()`. Данные методы возвращаеют соответствующие структуры, с помощью которых можно совершать запросы.
|
1. Вызвать у клиента метод, отвечающий за определение группы API для взаимодействия, это может быть `.CloudAPI()`, `.CloudBroker()` или `.SDN()`. Данные методы возвращают соответствующие структуры, с помощью которых можно совершать запросы.
|
||||||
2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия.
|
2. Вызвать у возвращенной структуры метод, определяющий группу ручек для взаимодействия.
|
||||||
|
|
||||||
Доступные методы для `.CloudAPI()`:
|
Доступные методы для `.CloudAPI()`:
|
||||||
|
|
||||||
- `.Account()` - для работы с `Account`
|
- `.Account()` - для работы с `Account`
|
||||||
|
- `.Audit()` - для работы с `Audit`
|
||||||
- `.BService()` - для работы с `BService`
|
- `.BService()` - для работы с `BService`
|
||||||
- `.Compute()` - для работы с `Compute`
|
- `.Compute()` - для работы с `Compute`
|
||||||
- `.Disks()` - для работы с `Disks`
|
- `.Disks()` - для работы с `Disks`
|
||||||
|
- `.DPDKNet()` - для работы с `DPDK`
|
||||||
- `.ExtNet()` - для работы с `ExtNet`
|
- `.ExtNet()` - для работы с `ExtNet`
|
||||||
- `.FLIPgroup()` - для работы с `FLIPGroup`
|
- `.FLIPgroup()` - для работы с `FLIPGroup`
|
||||||
- `.Image()` - для работы с `Image`
|
- `.Image()` - для работы с `Image`
|
||||||
- `.K8CI()` - для работы с `K8CI`
|
- `.K8CI()` - для работы с `K8CI`
|
||||||
- `.K8S()` - для работы с `K8S`
|
- `.K8S()` - для работы с `K8S`
|
||||||
- `.KVMPPC()` - для работы с `KVMPPC`
|
|
||||||
- `.KVMx86()` - для работы с `KVMX86`
|
- `.KVMx86()` - для работы с `KVMX86`
|
||||||
- `.LB()` - для работы с `LB`
|
- `.LB()` - для работы с `LB`
|
||||||
- `.Locations()` - для работы с `Locations`
|
- `.Locations()` - для работы с `Locations`
|
||||||
|
- `.Prometheus()` - для работы с `Prometheus`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.RG()` - для работы с `RG`
|
||||||
- `.Sizes()` - для работы с `Sizes`
|
- `.SecurityGroup()` - для работы с `Security Group`
|
||||||
|
- `.SEP()` - для работы с `SEP`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.Stack()` - для работы с `Stack`
|
||||||
|
- `.StPolicy()` - для работы с `Storage Policy`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
|
- `.Trunk()` - для работы с `Trunk`
|
||||||
|
- `.VFPool()` - для работы с `VFPool`
|
||||||
- `.VINS()` - для работы с `VINS`
|
- `.VINS()` - для работы с `VINS`
|
||||||
|
- `.Zone()` - для работы с `Zone`
|
||||||
|
|
||||||
Доступные методы для `.CloudBroker()`:
|
Доступные методы для `.CloudBroker()`:
|
||||||
|
|
||||||
- `.Account()` - для работы с `Account`
|
- `.Account()` - для работы с `Account`
|
||||||
|
- `.Audit()` - для работы с `Audit`
|
||||||
- `.APIAccess()` - для работы с `APIAccess`
|
- `.APIAccess()` - для работы с `APIAccess`
|
||||||
- `.Backup()` - для работы с `Backup`
|
- `.Backup()` - для работы с `Backup`
|
||||||
|
- `.BService()` - для работы с `BService`
|
||||||
- `.Compute()` - для работы с `Compute`
|
- `.Compute()` - для работы с `Compute`
|
||||||
- `.Disks()` - для работы с `Disks`
|
- `.Disks()` - для работы с `Disks`
|
||||||
|
- `.DPDKNet()` - для работы с `DPDK`
|
||||||
- `.ExtNet()` - для работы с `ExtNet`
|
- `.ExtNet()` - для работы с `ExtNet`
|
||||||
- `.FLIPGroup()` - для работы с `FLIPGroup`
|
- `.FLIPGroup()` - для работы с `FLIPGroup`
|
||||||
- `.Grid()` - для работы с `Grid`
|
- `.Grid()` - для работы с `Grid`
|
||||||
@@ -469,17 +549,28 @@ func main() {
|
|||||||
- `.Image()` - для работы с `Image`
|
- `.Image()` - для работы с `Image`
|
||||||
- `.K8CI()` - для работы с `K8CI`
|
- `.K8CI()` - для работы с `K8CI`
|
||||||
- `.K8S()` - для работы с `K8S`
|
- `.K8S()` - для работы с `K8S`
|
||||||
- `.KVMPPC()` - для работы с `KVMPPC`
|
|
||||||
- `.KVMx86()` - для работы с `KVMX86`
|
- `.KVMx86()` - для работы с `KVMX86`
|
||||||
- `.LB()` - для работы с `LB`
|
- `.LB()` - для работы с `LB`
|
||||||
|
- `.Node()` - для работы с `Node`
|
||||||
- `.PCIDevice()` - для работы с `PCIDevice`
|
- `.PCIDevice()` - для работы с `PCIDevice`
|
||||||
|
- `.Prometheus()` - для работы с `Prometheus`
|
||||||
|
- `.Resmon()` - для работы с `Resmon`
|
||||||
- `.RG()` - для работы с `RG`
|
- `.RG()` - для работы с `RG`
|
||||||
|
- `.SecurityGroup()` - для работы с `Security Group`
|
||||||
- `.SEP()` - для работы с `SEP`
|
- `.SEP()` - для работы с `SEP`
|
||||||
- `.Stack()` - для работы с `Stack`
|
- `.Stack()` - для работы с `Stack`
|
||||||
|
- `.StPolicy()` - для работы с `Storage Policy`
|
||||||
- `.Tasks()` - для работы с `Tasks`
|
- `.Tasks()` - для работы с `Tasks`
|
||||||
|
- `.Trunk()` - для работы с `Trunk`
|
||||||
- `.User()` - для работы с `User`
|
- `.User()` - для работы с `User`
|
||||||
- `.VGPU()` - для работы с `VGPU`
|
- `.VGPU()` - для работы с `VGPU`
|
||||||
|
- `.VFPool()` - для работы с `VFPool`
|
||||||
- `.VINS()` - для работы с `VINS`
|
- `.VINS()` - для работы с `VINS`
|
||||||
|
- `.Zone()` - для работы с `Zone`
|
||||||
|
|
||||||
|
Доступные методы для `.SDN()`:
|
||||||
|
|
||||||
|
- `.AccessGroup()` - для работы с `AccessGroup`
|
||||||
|
|
||||||
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
3. Вызвать метод, отвечающий за выполнение запроса и передать в него:
|
||||||
|
|
||||||
@@ -828,6 +919,87 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Методы поля Result для группы tasks
|
||||||
|
|
||||||
|
Поле Result внутри структур группы tasks имеет тип интерфейс и может содержать:
|
||||||
|
- строку о результате выполнения задачи, например `true`
|
||||||
|
- массив, содержащий ID и имя созданного ресурса, например `[12345, "resource_name"]`
|
||||||
|
- массив, содержащий информацию о восстновленных дисках, например `[{"computeId": 123, "diskId": 456}, {"computeId": 789, "diskId": 10}]`
|
||||||
|
|
||||||
|
Соответственно, для получения информации из поля Result доступны следующие методы:
|
||||||
|
- ToString(): строковое представление результата выполнения задачи
|
||||||
|
- ID() и Name(): получение ID и имени созданного в результате выполнения задачи ресурса
|
||||||
|
- ToMaps(): получение списка карт, содержащих информацию о дисках, восстановленных в результате выполнения задачи.
|
||||||
|
Все методы оборудованы возвратом ошибок. Непустая ошибка означает, что из поля Result нельзя получить информацию, которую предоставляет метод.
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
|
||||||
|
tasks_cb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/tasks"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
cfg := config.Config{
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://sso.digitalenergy.online",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
client := decort.New(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса GetRequest на получение информации о конкретной задаче и выполнение запроса с помощью конвейера
|
||||||
|
getReq := tasks.GetRequest{
|
||||||
|
AuditID: "b6316",
|
||||||
|
}
|
||||||
|
task, err := client.CloudAPI().Tasks().Get(context.Background(), getReq)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Получение списка карт с информацией о восстановленных дисках
|
||||||
|
maps, err := task.Result.ToMaps()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
fmt.Println(maps)
|
||||||
|
|
||||||
|
// Получение строкового результата выполнения задачи task
|
||||||
|
res, _ := task.Result.ToString()
|
||||||
|
fmt.Println(res)
|
||||||
|
|
||||||
|
// Создание структуры запроса ListRequest на получение информации о всех задачах и выполнение запроса с помощью конвейера
|
||||||
|
listReq := tasks_cb.ListRequest{}
|
||||||
|
tasks, err := client.CloudBroker().Tasks().List(context.Background(), listReq)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, t := range tasks {
|
||||||
|
// Получение id ресурса, созданного в результате выполнения задачи t
|
||||||
|
id, err := task.Result.ID()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
fmt.Println(id)
|
||||||
|
|
||||||
|
// Получение имени ресурса, созданного в результате выполнения задачи t
|
||||||
|
name, _ := task.Result.Name()
|
||||||
|
fmt.Println(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Работа с legacy клиентом
|
## Работа с legacy клиентом
|
||||||
|
|
||||||
Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o.
|
Работа с legacy клиентом применяется для пользователей, которые не используют для авторизации decs3o.
|
||||||
@@ -1290,3 +1462,223 @@ func main() {
|
|||||||
fmt.Println(res)
|
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)
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Работа с универсальным клиентом
|
||||||
|
|
||||||
|
Работа с универсальным клиентом позволяет использовать любой тип авторизации
|
||||||
|
|
||||||
|
### Настройка конфигурации универсального клиента
|
||||||
|
|
||||||
|
| Параметр | Тип | Обязательный | Описание |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Decs3oConfig | *Config | Нет | Конфигурация Decs3o |
|
||||||
|
| BVSConfig | *BVSConfig | Нет | Конфигурация BVS |
|
||||||
|
| LegacyConfig | string | Нет | Конфигурация Legacy |
|
||||||
|
|
||||||
|
В универсальном клиенте можно использовать только один тип конфигурации одновременно.
|
||||||
|
|
||||||
|
#### Пример конфигурации универсального клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main(){
|
||||||
|
// Настройка конфигурации
|
||||||
|
BVSConfig := config.BVSConfig{
|
||||||
|
AppID: "<APP_ID>",
|
||||||
|
AppSecret: "<APP_SECRET>",
|
||||||
|
SSOURL: "https://sso.digitalenergy.online",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Username: "<Username>",
|
||||||
|
Password: "<Password>",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
BVSConfig.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
|
cfg := config.UniversalConfig{
|
||||||
|
BVSConfig: &BVScfg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Создание универсального клиента
|
||||||
|
|
||||||
|
Создание клиента происходит с помощью функции-строителя `NewUniversal` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `ClientInterface`, с помощью которой можно взаимодействовать с платформой.
|
||||||
|
|
||||||
|
#### Пример создания универсального клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
legacyCfg := config.LegacyConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
|
cfg := config.UniversalConfig{
|
||||||
|
LegacyConfig: &legacyCfg,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
universalClient := decort.NewUniversal(cfg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример выполнения запроса
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
legacyCfg := config.LegacyConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
Domain: "dynamix",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
legacyCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
|
cfg := config.UniversalConfig{
|
||||||
|
LegacyConfig: &legacyCfg,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
universalClient := decort.NewUniversal(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса
|
||||||
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
|
req := kvmx86.CreateRequest{
|
||||||
|
RGID: 123,
|
||||||
|
Name: "compute",
|
||||||
|
CPU: 4,
|
||||||
|
RAM: 4096,
|
||||||
|
ImageID: 321,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выполнение запроса
|
||||||
|
res, err := universalClient.CloudAPI().KVMX86().Create(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Проверка соответствия версии платформы и версии dynamix
|
||||||
|
|
||||||
|
С версии 1.11.5 для каждого клиента добавлен метод `Check` для проверки соответствия decort-sdk и платформы dynamix.
|
||||||
|
В случае соответсвия decort-sdk и платформы dynamix возвращается структура, содержащая информацию о версии и актуальном билде платформы.
|
||||||
|
|
||||||
|
#### Пример выполнения запроса
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main(){
|
||||||
|
// Настройка конфигурации
|
||||||
|
config := config.Config{
|
||||||
|
AppID: "<APP_ID>",
|
||||||
|
AppSecret: "<APP_SECRET>",
|
||||||
|
SSOURL: "https://sso.digitalenergy.online",
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Retries: 5,
|
||||||
|
SSLSkipVerify: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
client := decort.New(config)
|
||||||
|
|
||||||
|
// Проверка соответствия версии
|
||||||
|
checkInfo, err := client.Check()
|
||||||
|
}
|
||||||
|
```
|
||||||
62
README_EN.md
62
README_EN.md
@@ -1,62 +0,0 @@
|
|||||||
# Decort SDK
|
|
||||||
|
|
||||||
Decort SDK is a library, written in GO (Golang) for interact with the **DECORT** API.
|
|
||||||
The library contents structures and methods for requesting to an user (cloudapi) and admin (cloudbroker) groups of API.
|
|
||||||
Also the library have structures for responses.
|
|
||||||
|
|
||||||
## Contents
|
|
||||||
|
|
||||||
- [Install](#install)
|
|
||||||
- [API List](#api-list)
|
|
||||||
- [Examples](#examples)
|
|
||||||
- [Examples2](#examples2)
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go get -u repository.basistech.ru/BASIS/decort-golang-sdk
|
|
||||||
```
|
|
||||||
|
|
||||||
## API List
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/kvmx86"
|
|
||||||
)
|
|
||||||
|
|
||||||
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)
|
|
||||||
req := kvmx86.CreateRequest{
|
|
||||||
RGID: 123,
|
|
||||||
Name: "compute",
|
|
||||||
CPU: 4,
|
|
||||||
RAM: 4096,
|
|
||||||
ImageID: 321,
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := client.KVMX86().Create(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println(res)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Examples2
|
|
||||||
106
check.go
Normal file
106
check.go
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
package decortsdk
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CheckInfo struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Build uint64 `json:"build"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const versionURL = "/system/info/version"
|
||||||
|
|
||||||
|
func (de DecortClient) Check() (*CheckInfo, error) {
|
||||||
|
res, err := de.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := CheckInfo{}
|
||||||
|
|
||||||
|
err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
|
||||||
|
if err != nil {
|
||||||
|
var v string
|
||||||
|
json.Unmarshal([]byte(res), &v)
|
||||||
|
if _, exists := constants.VersionMap[v]; exists {
|
||||||
|
info.Version = v
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("platform version isn't supported")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if v, ok := constants.VersionMap[info.Version]; ok {
|
||||||
|
if v == "-" {
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bvs BVSDecortClient) Check() (*CheckInfo, error) {
|
||||||
|
res, err := bvs.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := CheckInfo{}
|
||||||
|
|
||||||
|
err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
|
||||||
|
if err != nil {
|
||||||
|
var v string
|
||||||
|
json.Unmarshal([]byte(res), &v)
|
||||||
|
if _, exists := constants.VersionMap[v]; exists {
|
||||||
|
info.Version = v
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("platform version isn't supported")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if v, ok := constants.VersionMap[info.Version]; ok {
|
||||||
|
if v == "-" {
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ldc LegacyDecortClient) Check() (*CheckInfo, error) {
|
||||||
|
res, err := ldc.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := CheckInfo{}
|
||||||
|
|
||||||
|
err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
|
||||||
|
if err != nil {
|
||||||
|
var v string
|
||||||
|
json.Unmarshal([]byte(res), &v)
|
||||||
|
if _, exists := constants.VersionMap[v]; exists {
|
||||||
|
info.Version = v
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("platform version isn't supported")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if v, ok := constants.VersionMap[info.Version]; ok {
|
||||||
|
if v == "-" {
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
|
||||||
|
}
|
||||||
154
client.go
154
client.go
@@ -4,6 +4,8 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
@@ -17,8 +19,10 @@ 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/internal/constants"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
"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"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/sdn"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DecortClient is HTTP-client for platform
|
// DecortClient is HTTP-client for platform
|
||||||
@@ -36,12 +40,6 @@ func New(cfg config.Config) *DecortClient {
|
|||||||
cfg.Retries = 5
|
cfg.Retries = 5
|
||||||
}
|
}
|
||||||
|
|
||||||
var expiryTime time.Time
|
|
||||||
|
|
||||||
if cfg.Token != "" {
|
|
||||||
expiryTime = time.Now().AddDate(0, 0, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &DecortClient{
|
return &DecortClient{
|
||||||
decortURL: cfg.DecortURL,
|
decortURL: cfg.DecortURL,
|
||||||
client: &http.Client{
|
client: &http.Client{
|
||||||
@@ -52,9 +50,8 @@ func New(cfg config.Config) *DecortClient {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
cfg: cfg,
|
cfg: trimConfig(&cfg),
|
||||||
expiryTime: expiryTime,
|
mutex: &sync.Mutex{},
|
||||||
mutex: &sync.Mutex{},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,16 +65,31 @@ func (dc *DecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
|||||||
return cloudbroker.New(dc)
|
return cloudbroker.New(dc)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SDN builder
|
||||||
|
func (dc *DecortClient) SDN() *sdn.SDN {
|
||||||
|
return sdn.New(dc)
|
||||||
|
}
|
||||||
|
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
values, err := query.Values(params)
|
|
||||||
if err != nil {
|
var body *bytes.Buffer
|
||||||
return nil, err
|
var ctype string
|
||||||
|
|
||||||
|
byteSlice, ok := params.([]byte)
|
||||||
|
if ok {
|
||||||
|
body = bytes.NewBuffer(byteSlice)
|
||||||
|
// ctype = "application/x-iso9660-image"
|
||||||
|
ctype = "application/octet-stream"
|
||||||
|
} else {
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBufferString(values.Encode())
|
||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBufferString(values.Encode())
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.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
|
||||||
}
|
}
|
||||||
@@ -86,9 +98,49 @@ func (dc *DecortClient) DecortApiCall(ctx context.Context, method, url string, p
|
|||||||
if err = dc.getToken(ctx); err != nil {
|
if err = dc.getToken(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// perform request
|
// perform request
|
||||||
respBytes, err := dc.do(req, "")
|
respBytes, err := dc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecortApiCallCtype method for sending requests to the platform with content type
|
||||||
|
func (dc *DecortClient) DecortApiCallCtype(ctx context.Context, method, url, ctype string, params interface{}) ([]byte, error) {
|
||||||
|
|
||||||
|
var body *bytes.Buffer
|
||||||
|
|
||||||
|
switch ctype {
|
||||||
|
case constants.MIMESTREAM:
|
||||||
|
body = bytes.NewBuffer(params.([]byte))
|
||||||
|
case constants.MIMEJSON:
|
||||||
|
jsonBody, err := json.Marshal(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBuffer(jsonBody)
|
||||||
|
default:
|
||||||
|
ctype = constants.MIMEPOSTForm
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBufferString(values.Encode())
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// get token
|
||||||
|
if err = dc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// perform request
|
||||||
|
respBytes, err := dc.do(req, ctype)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -103,7 +155,7 @@ func (dc *DecortClient) DecortApiCallMP(ctx context.Context, method, url string,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, dc.decortURL+constants.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
|
||||||
}
|
}
|
||||||
@@ -159,8 +211,13 @@ func (dc *DecortClient) getToken(ctx context.Context) error {
|
|||||||
|
|
||||||
// save token in config
|
// save token in config
|
||||||
token := string(tokenBytes)
|
token := string(tokenBytes)
|
||||||
|
expiryTime, err := getTokenExp(token)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot get expiry time: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
dc.cfg.Token = token
|
dc.cfg.Token = token
|
||||||
dc.expiryTime = time.Now().AddDate(0, 0, 1)
|
dc.expiryTime = expiryTime
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -283,11 +340,22 @@ func multiPartReq(params interface{}) (*bytes.Buffer, string, error) {
|
|||||||
if values.Field(i).Type().Kind() == reflect.Slice {
|
if values.Field(i).Type().Kind() == reflect.Slice {
|
||||||
switch slice := values.Field(i).Interface().(type) {
|
switch slice := values.Field(i).Interface().(type) {
|
||||||
case []string:
|
case []string:
|
||||||
for _, val := range slice {
|
if validators.IsInSlice(trimString(types.Field(i)), constants.K8sValues) {
|
||||||
err := writer.WriteField(trimString(types.Field(i)), val)
|
code, err := json.Marshal(slice)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return &bytes.Buffer{}, "", err
|
return &bytes.Buffer{}, "", err
|
||||||
}
|
}
|
||||||
|
err = writer.WriteField(trimString(types.Field(i)), string(code))
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, val := range slice {
|
||||||
|
err := writer.WriteField(trimString(types.Field(i)), val)
|
||||||
|
if err != nil {
|
||||||
|
return &bytes.Buffer{}, "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case []uint:
|
case []uint:
|
||||||
for _, val := range slice {
|
for _, val := range slice {
|
||||||
@@ -303,10 +371,20 @@ func multiPartReq(params interface{}) (*bytes.Buffer, string, error) {
|
|||||||
return &bytes.Buffer{}, "", err
|
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:
|
default:
|
||||||
return &bytes.Buffer{}, "", fmt.Errorf("unsupported slice type:%T", slice)
|
return &bytes.Buffer{}, "", fmt.Errorf("unsupported slice type:%T", slice)
|
||||||
}
|
}
|
||||||
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,3 +415,35 @@ func valueToString(a any) string {
|
|||||||
func trimString(el reflect.StructField) string {
|
func trimString(el reflect.StructField) string {
|
||||||
return strings.TrimSuffix(el.Tag.Get("url"), ",omitempty")
|
return strings.TrimSuffix(el.Tag.Get("url"), ",omitempty")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func trimConfig(cfg *config.Config) config.Config {
|
||||||
|
cfg.SSOURL = strings.TrimSuffix(cfg.SSOURL, "/")
|
||||||
|
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||||
|
return *cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTokenExp(token string) (time.Time, error) {
|
||||||
|
parts := strings.Split(token, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return time.Time{}, fmt.Errorf("invalid token format")
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, fmt.Errorf("error decode payload from token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var claims map[string]interface{}
|
||||||
|
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||||
|
return time.Time{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
exp, ok := claims["exp"]
|
||||||
|
if !ok {
|
||||||
|
return time.Time{}, fmt.Errorf("exp time bot found")
|
||||||
|
}
|
||||||
|
|
||||||
|
expTime := time.Unix(int64(exp.(float64)), 0)
|
||||||
|
|
||||||
|
return expTime, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
cfg: cfg,
|
cfg: trimBVSConfig(&cfg),
|
||||||
mutex: &sync.Mutex{},
|
mutex: &sync.Mutex{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,14 +71,23 @@ func (bdc *BVSDecortClient) CloudBroker() *cloudbroker.CloudBroker {
|
|||||||
|
|
||||||
// DecortApiCall method for sending requests to the platform
|
// DecortApiCall method for sending requests to the platform
|
||||||
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url string, params interface{}) ([]byte, error) {
|
||||||
values, err := query.Values(params)
|
var body *bytes.Buffer
|
||||||
if err != nil {
|
var ctype string
|
||||||
return nil, err
|
|
||||||
|
byteSlice, ok := params.([]byte)
|
||||||
|
if ok {
|
||||||
|
body = bytes.NewBuffer(byteSlice)
|
||||||
|
// ctype = "application/x-iso9660-image"
|
||||||
|
ctype = "application/octet-stream"
|
||||||
|
} else {
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBufferString(values.Encode())
|
||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBufferString(values.Encode())
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.Restmachine+url, body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -101,7 +110,73 @@ func (bdc *BVSDecortClient) DecortApiCall(ctx context.Context, method, url strin
|
|||||||
|
|
||||||
// perform request
|
// perform request
|
||||||
reqCopy := req.Clone(ctx)
|
reqCopy := req.Clone(ctx)
|
||||||
respBytes, err := bdc.do(req, "")
|
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, "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecortApiCallCtype method for sending requests to the platform with content type
|
||||||
|
func (bdc *BVSDecortClient) DecortApiCallCtype(ctx context.Context, method, url, ctype string, params interface{}) ([]byte, error) {
|
||||||
|
var body *bytes.Buffer
|
||||||
|
|
||||||
|
switch ctype {
|
||||||
|
case constants.MIMESTREAM:
|
||||||
|
body = bytes.NewBuffer(params.([]byte))
|
||||||
|
case constants.MIMEJSON:
|
||||||
|
jsonBody, err := json.Marshal(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBuffer(jsonBody)
|
||||||
|
default:
|
||||||
|
ctype = constants.MIMEPOSTForm
|
||||||
|
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, ctype)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return respBytes, nil
|
return respBytes, nil
|
||||||
}
|
}
|
||||||
@@ -128,7 +203,7 @@ func (bdc *BVSDecortClient) DecortApiCallMP(ctx context.Context, method, url str
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.Restmachine+url, body)
|
req, err := http.NewRequestWithContext(ctx, method, bdc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -378,3 +453,9 @@ func (bdc *BVSDecortClient) do(req *http.Request, ctype string) ([]byte, error)
|
|||||||
err = fmt.Errorf("%s", respBytes)
|
err = fmt.Errorf("%s", respBytes)
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func trimBVSConfig(cfg *config.BVSConfig) config.BVSConfig {
|
||||||
|
cfg.SSOURL = strings.TrimSuffix(cfg.SSOURL, "/")
|
||||||
|
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||||
|
return *cfg
|
||||||
|
}
|
||||||
|
|||||||
8
config/universal-config.go
Normal file
8
config/universal-config.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
// UniversalConfig combines configurations for different types of clients
|
||||||
|
type UniversalConfig struct {
|
||||||
|
Decs3oConfig *Config `json:"decs3oConfig,omitempty" yaml:"decs3oConfig,omitempty"`
|
||||||
|
BVSConfig *BVSConfig `json:"bvsConfig,omitempty" yaml:"bvsConfig,omitempty"`
|
||||||
|
LegacyConfig *LegacyConfig `json:"legacyConfig,omitempty" yaml:"legacyConfig,omitempty"`
|
||||||
|
}
|
||||||
1
go.mod
1
go.mod
@@ -5,6 +5,7 @@ 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
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
2
go.sum
2
go.sum
@@ -13,6 +13,8 @@ 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-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=
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ 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)
|
||||||
|
|
||||||
|
// DecortApiCallCtype method for sending requests to the platform
|
||||||
|
DecortApiCallCtype(ctx context.Context, method, url, ctype string, params interface{}) ([]byte, error)
|
||||||
|
|
||||||
// DecortApiCallMP method for sending requests to the platform
|
// DecortApiCallMP method for sending requests to the platform
|
||||||
DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
DecortApiCallMP(ctx context.Context, method, url string, params interface{}) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|||||||
7
interfaces/request.go
Normal file
7
interfaces/request.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package interfaces
|
||||||
|
|
||||||
|
// Interface to valiate RAM values
|
||||||
|
type RequestWithRAM interface {
|
||||||
|
// GetRAM returns RAM values
|
||||||
|
GetRAM() map[string]uint64
|
||||||
|
}
|
||||||
@@ -1,7 +1,36 @@
|
|||||||
package constants
|
package constants
|
||||||
|
|
||||||
const Restmachine = "/restmachine"
|
const (
|
||||||
|
RESTMACHINE = "/restmachine"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
MIMEJSON = "application/json"
|
||||||
|
MIMEHTML = "text/html"
|
||||||
|
MIMEXML = "application/xml"
|
||||||
|
MIMEXML2 = "text/xml"
|
||||||
|
MIMEPlain = "text/plain"
|
||||||
|
MIMEPOSTForm = "application/x-www-form-urlencoded"
|
||||||
|
MIMEMultipartPOSTForm = "multipart/form-data"
|
||||||
|
MIMEPROTOBUF = "application/x-protobuf"
|
||||||
|
MIMEMSGPACK = "application/x-msgpack"
|
||||||
|
MIMEMSGPACK2 = "application/msgpack"
|
||||||
|
MIMEYAML = "application/x-yaml"
|
||||||
|
MIMEYAML2 = "application/yaml"
|
||||||
|
MIMETOML = "application/toml"
|
||||||
|
MIMESTREAM = "application/octet-stream"
|
||||||
|
)
|
||||||
|
|
||||||
var FileName = map[string]string{
|
var FileName = map[string]string{
|
||||||
"OidcCertificate": "ca.crt",
|
"OidcCertificate": "ca.crt",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var K8sValues = []string{"labels", "taints", "annotations, additionalSANs"}
|
||||||
|
|
||||||
|
var VersionMap = map[string]string{
|
||||||
|
"4.4.0": "-",
|
||||||
|
"4.3.0": "-",
|
||||||
|
"4.2.0": "-",
|
||||||
|
"4.1.1": "-",
|
||||||
|
"4.1.0": "-",
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,31 +1,38 @@
|
|||||||
package validators
|
package validators
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"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.
|
|
||||||
func computeDriverValidator(fe validator.FieldLevel) bool {
|
|
||||||
fieldValue := fe.Field().String()
|
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDriverValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
// protoValidator is used to validate Proto fields.
|
// protoValidator is used to validate Proto fields.
|
||||||
func protoValidator(fe validator.FieldLevel) bool {
|
func protoValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, protoValues)
|
return IsInSlice(fieldValue, protoValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// apiGroupValidator is used to validate APIGroup fields
|
||||||
|
func apiGroupValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, apiGroupValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// accessTypeValidator is used to validate AccessType fields.
|
// accessTypeValidator is used to validate AccessType fields.
|
||||||
func accessTypeValidator(fe validator.FieldLevel) bool {
|
func accessTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, accessTypeValues)
|
return IsInSlice(fieldValue, accessTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// resTypesValidator is used to validate ResTypes fields.
|
// resTypesValidator is used to validate ResTypes fields.
|
||||||
@@ -36,7 +43,7 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !StringInSlice(value, resTypesValues) {
|
if !IsInSlice(value, resTypesValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -44,60 +51,81 @@ func resTypesValidator(fe validator.FieldLevel) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// driverValidator is used to validate Driver fields.
|
|
||||||
func driverValidator(fe validator.FieldLevel) bool {
|
|
||||||
fieldValue := fe.Field().String()
|
|
||||||
|
|
||||||
return StringInSlice(fieldValue, driverValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
// accountCUTypeValidator is used to validate CUType field.
|
// accountCUTypeValidator is used to validate CUType field.
|
||||||
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
func accountCUTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, accountCUTypeValues)
|
return IsInSlice(fieldValue, accountCUTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// bserviceModeValidator is used to validate Mode field.
|
// bserviceModeValidator is used to validate Mode field.
|
||||||
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
func bserviceModeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, bserviceModeValues)
|
return IsInSlice(fieldValue, bserviceModeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeTopologyValidator is used to validate Topology field.
|
// computeTopologyValidator is used to validate Topology field.
|
||||||
func computeTopologyValidator(fe validator.FieldLevel) bool {
|
func computeTopologyValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeTopologyValues)
|
return IsInSlice(fieldValue, computeTopologyValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computePolicyValidator is used to validate Policy field.
|
// computePolicyValidator is used to validate Policy field.
|
||||||
func computePolicyValidator(fe validator.FieldLevel) bool {
|
func computePolicyValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computePolicyValues)
|
return IsInSlice(fieldValue, computePolicyValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeModeValidator is used to validate Mode field.
|
// computeModeValidator is used to validate Mode field.
|
||||||
func computeModeValidator(fe validator.FieldLevel) bool {
|
func computeModeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeModeValues)
|
return IsInSlice(fieldValue, computeModeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeDiskTypeValidator is used to validate DiskType field.
|
// computeDiskTypeValidator is used to validate DiskType field.
|
||||||
func computeDiskTypeValidator(fe validator.FieldLevel) bool {
|
func computeDiskTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDiskTypeValues)
|
return IsInSlice(fieldValue, computeDiskTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeNetTypeValidator is used to validate NetType field.
|
// computeNetTypeValidator is used to validate NetType field.
|
||||||
func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
func computeNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeNetTypeValues)
|
return IsInSlice(fieldValue, computeNetTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// computex86NetTypeValidator is used to validate NetType field.
|
||||||
|
func computex86NetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, computex86NetTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// securityGroupDirectionValidator is used to validate Direction field
|
||||||
|
func securityGroupDirectionValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, securityGroupDirectionValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// securityGroupEthertypeValidator is used to validate Ethertype field
|
||||||
|
func securityGroupEthertypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, securityGroupEthertypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// securityGroupProtocolValidator is used to validate Protocol field
|
||||||
|
func securityGroupProtocolValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, securityGroupProtocolValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// computeOrderValidator is used to validate Order field.
|
// computeOrderValidator is used to validate Order field.
|
||||||
@@ -108,7 +136,7 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, value := range fieldSlice {
|
for _, value := range fieldSlice {
|
||||||
if !StringInSlice(value, computeOrderValues) {
|
if !IsInSlice(value, computeOrderValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,100 +148,84 @@ func computeOrderValidator(fe validator.FieldLevel) bool {
|
|||||||
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
func computeDataDisksValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, computeDataDisksValues)
|
return IsInSlice(fieldValue, computeDataDisksValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// diskTypeValidator is used to validate Type field.
|
// diskTypeValidator is used to validate Type field.
|
||||||
func diskTypeValidator(fe validator.FieldLevel) bool {
|
func diskTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, diskTypeValues)
|
return IsInSlice(fieldValue, diskTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// flipgroupClientTypeValidator is used to validate ClientType field.
|
// flipgroupClientTypeValidator is used to validate ClientType field.
|
||||||
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
func flipgroupClientTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, flipgroupClientTypeValues)
|
return IsInSlice(fieldValue, flipgroupClientTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// kvmNetTypeValidator is used to validate NetType field.
|
// kvmNetTypeValidator is used to validate NetType field.
|
||||||
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
func kvmNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, kvmNetTypeValues)
|
return IsInSlice(fieldValue, kvmNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// lbAlgorithmValidator is used to validate Algorithm field.
|
// lbAlgorithmValidator is used to validate Algorithm field.
|
||||||
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
func lbAlgorithmValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, lbAlgorithmValues)
|
return IsInSlice(fieldValue, lbAlgorithmValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// rgDefNetValidator is used to validate DefNet field.
|
// rgDefNetValidator is used to validate DefNet field.
|
||||||
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
func rgDefNetValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, rgDefNetValues)
|
return IsInSlice(fieldValue, rgDefNetValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// rgNetTypeValidator is used to validate NetType field.
|
// rgNetTypeValidator is used to validate NetType field.
|
||||||
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
func rgNetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, rgNetTypeValues)
|
return IsInSlice(fieldValue, rgNetTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// vinsTypeValidator is used to validate Type field.
|
// vinsTypeValidator is used to validate Type field.
|
||||||
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
func vinsTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, vinsTypeValues)
|
return IsInSlice(fieldValue, vinsTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageBootTypeValidator is used to validate BootType field.
|
// imageBootTypeValidator is used to validate BootType field.
|
||||||
func imageBootTypeValidator(fe validator.FieldLevel) bool {
|
func imageBootTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageBootTypeValues)
|
return IsInSlice(fieldValue, imageBootTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageTypeValidator is used to validate ImageType field.
|
// imageTypeValidator is used to validate ImageType field.
|
||||||
func imageTypeValidator(fe validator.FieldLevel) bool {
|
func imageTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageTypeValues)
|
return IsInSlice(fieldValue, imageTypeValues)
|
||||||
}
|
|
||||||
|
|
||||||
// imageDriversValidator is used to validate Drivers field.
|
|
||||||
func imageDriversValidator(fe validator.FieldLevel) bool {
|
|
||||||
fieldSlice, ok := fe.Field().Interface().([]string)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, item := range fieldSlice {
|
|
||||||
if !StringInSlice(item, imageDriversValues) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// imageArchitectureValidator is used to validate Architecture field.
|
// imageArchitectureValidator is used to validate Architecture field.
|
||||||
func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
func imageArchitectureValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, imageArchitectureValues)
|
return IsInSlice(fieldValue, imageArchitectureValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sepFieldTypeValidator is used to validate FieldType field.
|
// sepFieldTypeValidator is used to validate FieldType field.
|
||||||
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
func sepFieldTypeValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
return StringInSlice(fieldValue, sepFieldTypeValues)
|
return IsInSlice(fieldValue, sepFieldTypeValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// hwPathValidator is used to validate HWPath field.
|
// hwPathValidator is used to validate HWPath field.
|
||||||
@@ -230,7 +242,7 @@ func networkPluginValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, networkPluginValues)
|
return IsInSlice(fieldValue, networkPluginValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// networkPluginsValidator is used to validate NetworkPlugins field
|
// networkPluginsValidator is used to validate NetworkPlugins field
|
||||||
@@ -243,7 +255,7 @@ func networkPluginsValidator(fe validator.FieldLevel) bool {
|
|||||||
for _, item := range fieldSlice {
|
for _, item := range fieldSlice {
|
||||||
item = strings.ToLower(item)
|
item = strings.ToLower(item)
|
||||||
|
|
||||||
if !StringInSlice(item, networkPluginValues) {
|
if !IsInSlice(item, networkPluginValues) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -255,14 +267,35 @@ func interfaceStateValidator(fe validator.FieldLevel) bool {
|
|||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, interfaceStateValues)
|
return IsInSlice(fieldValue, interfaceStateValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func interfaceTXModelValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, txModelValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func interfaceIOEventFDValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, ioEventFDValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func interfaceEventIDxValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, eventIDxValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
func strictLooseValidator(fe validator.FieldLevel) bool {
|
func strictLooseValidator(fe validator.FieldLevel) bool {
|
||||||
fieldValue := fe.Field().String()
|
fieldValue := fe.Field().String()
|
||||||
fieldValue = strings.ToLower(fieldValue)
|
fieldValue = strings.ToLower(fieldValue)
|
||||||
|
|
||||||
return StringInSlice(fieldValue, strictLooseValues)
|
return IsInSlice(fieldValue, strictLooseValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// name workerGroup must be more 3 symbol
|
// name workerGroup must be more 3 symbol
|
||||||
@@ -272,3 +305,155 @@ 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 mtuValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().Uint()
|
||||||
|
|
||||||
|
return fieldValue >= uint64(mtuMin) && fieldValue <= uint64(mtuMax)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func numaAffinityValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, numaAffinityValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// kvmx86NetTypeValidator is used to validate NetType field for x86 compute.
|
||||||
|
func kvmx86NetTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, kvmx86NetTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isBoolTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
return fe.Field().CanConvert(reflect.TypeOf(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlValidartor(fl validator.FieldLevel) bool {
|
||||||
|
fieldValues := fl.Field().String()
|
||||||
|
|
||||||
|
_, err := url.ParseRequestURI(fieldValues)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func chipsetValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, chipsetValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func preferredCPUValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldSlice, ok := fe.Field().Interface().([]int64)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range fieldSlice {
|
||||||
|
if value < -1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// loaderTypeValidator is used to validate loaderType fields
|
||||||
|
func loaderTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, loaderTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// languageValidator is used to validate language fields
|
||||||
|
func languageValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, languageValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
func userProviderValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, userProviders)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sepTypeValidator is used to validate sepType fields
|
||||||
|
func sepTypeValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, sepTypeValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceValidator is used to validate extnet device fields
|
||||||
|
func deviceValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
|
||||||
|
return IsInSlice(fieldValue, deviceValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// trunkTagsValidator checks if trunk_tags is in range from 1 to 4095
|
||||||
|
func trunkTagsValidator(fe validator.FieldLevel) bool {
|
||||||
|
fieldValue := fe.Field().String()
|
||||||
|
numFieldValue, err := strconv.ParseInt(fieldValue, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return uint64(numFieldValue) >= uint64(trunkTagsMin) && uint64(numFieldValue) <= uint64(trunkTagsMax)
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ func GetErrors(err error) validator.ValidationErrors {
|
|||||||
return err.(validator.ValidationErrors)
|
return err.(validator.ValidationErrors)
|
||||||
}
|
}
|
||||||
|
|
||||||
func StringInSlice(str string, target []string) bool {
|
func IsInSlice(str string, target []string) bool {
|
||||||
for _, v := range target {
|
for _, v := range target {
|
||||||
if v == str {
|
if v == str {
|
||||||
return true
|
return true
|
||||||
@@ -42,3 +42,12 @@ func StringInSlice(str string, target []string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsSubSlice(source []string, target []string) bool {
|
||||||
|
for _, s := range source {
|
||||||
|
if !IsInSlice(s, target) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,12 +25,8 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
return fmt.Sprintf("%s %s: unexpected URL format", prefix, fe.Field())
|
return fmt.Sprintf("%s %s: unexpected URL format", prefix, fe.Field())
|
||||||
case "email":
|
case "email":
|
||||||
return fmt.Sprintf("%s %s: unexpected E-Mail format", prefix, fe.Field())
|
return fmt.Sprintf("%s %s: unexpected E-Mail format", prefix, fe.Field())
|
||||||
|
case "isBool":
|
||||||
case "driver":
|
return fmt.Sprintf("%s %s: must be bool type", prefix, fe.Field())
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
|
||||||
prefix,
|
|
||||||
fe.Field(),
|
|
||||||
joinValues(driverValues))
|
|
||||||
|
|
||||||
case "accessType":
|
case "accessType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
@@ -50,6 +46,13 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(protoValues))
|
joinValues(protoValues))
|
||||||
|
|
||||||
|
// apiGroup Validators
|
||||||
|
case "apiGroup":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(apiGroupValues))
|
||||||
|
|
||||||
// Account Validators
|
// Account Validators
|
||||||
case "accountCUType":
|
case "accountCUType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
@@ -89,6 +92,18 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(computeDiskTypeValues))
|
joinValues(computeDiskTypeValues))
|
||||||
|
|
||||||
|
case "mtu":
|
||||||
|
return fmt.Sprint(prefix, fe.Field(), "must be ", mtuMin, "-", mtuMax)
|
||||||
|
|
||||||
|
case "preferredCPU":
|
||||||
|
return fmt.Sprint(prefix, fe.Field(), "must be equal to or greater than", -1)
|
||||||
|
|
||||||
|
case "computex86NetType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(computex86NetTypeValues))
|
||||||
|
|
||||||
case "computeNetType":
|
case "computeNetType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
@@ -107,12 +122,6 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(computeDataDisksValues))
|
joinValues(computeDataDisksValues))
|
||||||
|
|
||||||
case "computeDriver":
|
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
|
||||||
prefix,
|
|
||||||
fe.Field(),
|
|
||||||
joinValues(computeDriverValues))
|
|
||||||
|
|
||||||
// Disk Validators
|
// Disk Validators
|
||||||
case "diskType":
|
case "diskType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
@@ -133,7 +142,7 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
prefix,
|
prefix,
|
||||||
fe.Field())
|
fe.Field())
|
||||||
|
|
||||||
// KVM_X86/KVM_PPC Validators
|
// KVM_X86 Validators
|
||||||
case "kvmNetType":
|
case "kvmNetType":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
@@ -180,12 +189,6 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(imageTypeValues))
|
joinValues(imageTypeValues))
|
||||||
|
|
||||||
case "imageDrivers":
|
|
||||||
return fmt.Sprintf("%s %s must contain only the following: %s",
|
|
||||||
prefix,
|
|
||||||
fe.Field(),
|
|
||||||
joinValues(imageDriversValues))
|
|
||||||
|
|
||||||
case "imageArchitecture":
|
case "imageArchitecture":
|
||||||
return fmt.Sprintf("%s %s must be one of the following: %s",
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
prefix,
|
prefix,
|
||||||
@@ -229,6 +232,127 @@ func errorMessage(fe validator.FieldError) string {
|
|||||||
prefix,
|
prefix,
|
||||||
fe.Field(),
|
fe.Field(),
|
||||||
joinValues(interfaceStateValues))
|
joinValues(interfaceStateValues))
|
||||||
|
|
||||||
|
case "interfaceTXModel":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(txModelValues))
|
||||||
|
|
||||||
|
case "interfaceIOEventFD":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(ioEventFDValues))
|
||||||
|
|
||||||
|
case "interfaceEventIDx":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(eventIDxValues))
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
case "numaAffinity":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(numaAffinityValues))
|
||||||
|
|
||||||
|
case "kvmx86NetType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(kvmx86NetTypeValues))
|
||||||
|
|
||||||
|
case "chipset":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(chipsetValues))
|
||||||
|
|
||||||
|
case "loaderType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(loaderTypeValues))
|
||||||
|
|
||||||
|
case "language":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(languageValues))
|
||||||
|
|
||||||
|
case "sepType":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(sepTypeValues))
|
||||||
|
|
||||||
|
// user validators
|
||||||
|
case "userProvider":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(userProviders))
|
||||||
|
|
||||||
|
// security group validators
|
||||||
|
case "securityGroupDirection":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(securityGroupDirectionValues))
|
||||||
|
|
||||||
|
case "securityGroupEthertype":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(securityGroupEthertypeValues))
|
||||||
|
|
||||||
|
case "securityGroupProtocol":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(securityGroupProtocolValues))
|
||||||
|
|
||||||
|
// trunk tags validator
|
||||||
|
case "trunkTags":
|
||||||
|
return fmt.Sprintf("%s %s must be in range from 1 to 4095",
|
||||||
|
prefix,
|
||||||
|
fe.Field())
|
||||||
|
|
||||||
|
case "device":
|
||||||
|
return fmt.Sprintf("%s %s must be one of the following: %s",
|
||||||
|
prefix,
|
||||||
|
fe.Field(),
|
||||||
|
joinValues(deviceValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
return fe.Error()
|
return fe.Error()
|
||||||
|
|||||||
@@ -25,12 +25,13 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("computeDriver", computeDriverValidator)
|
err = validate.RegisterValidation("apiGroup", apiGroupValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -45,11 +46,6 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("driver", driverValidator)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = validate.RegisterValidation("imageBootType", imageBootTypeValidator)
|
err = validate.RegisterValidation("imageBootType", imageBootTypeValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -60,11 +56,6 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("imageDrivers", imageDriversValidator)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = validate.RegisterValidation("imageArchitecture", imageArchitectureValidator)
|
err = validate.RegisterValidation("imageArchitecture", imageArchitectureValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -105,6 +96,11 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("computex86NetType", computex86NetTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("computeOrder", computeOrderValidator)
|
err = validate.RegisterValidation("computeOrder", computeOrderValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -180,10 +176,130 @@ func registerAllValidators(validate *validator.Validate) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("interfaceTXModel", interfaceTXModelValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("interfaceIOEventFD", interfaceIOEventFDValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("interfaceEventIDx", interfaceEventIDxValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
err = validate.RegisterValidation("workerGroupName", workerGroupNameValidator)
|
err = validate.RegisterValidation("workerGroupName", workerGroupNameValidator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
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("mtu", mtuValidator)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("numaAffinity", numaAffinityValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("kvmx86NetType", kvmx86NetTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("isBool", isBoolTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("url", urlValidartor)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("chipset", chipsetValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("preferredCPU", preferredCPUValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("loaderType", loaderTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("language", languageValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("userProvider", userProviderValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("sepType", sepTypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("device", deviceValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("trunkTags", trunkTagsValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("securityGroupDirection", securityGroupDirectionValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("securityGroupEthertype", securityGroupEthertypeValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = validate.RegisterValidation("securityGroupProtocol", securityGroupProtocolValidator)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
package validators
|
package validators
|
||||||
|
|
||||||
var (
|
var (
|
||||||
driverValues = []string{"KVM_X86", "KVM_PPC"}
|
apiGroupValues = []string{"cloudapi", "cloudbroker", "system"}
|
||||||
|
|
||||||
accessTypeValues = []string{"R", "RCX", "ARCXDU"}
|
accessTypeValues = []string{"R", "RCX", "ARCXDU"}
|
||||||
resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"}
|
resTypesValues = []string{"compute", "vins", "k8s", "openshift", "lb", "flipgroup"}
|
||||||
protoValues = []string{"tcp", "udp"}
|
protoValues = []string{"tcp", "udp"}
|
||||||
@@ -10,38 +11,78 @@ var (
|
|||||||
|
|
||||||
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
|
bserviceModeValues = []string{"ABSOLUTE", "RELATIVE"}
|
||||||
|
|
||||||
computeTopologyValues = []string{"compute", "node"}
|
computeTopologyValues = []string{"compute", "node"}
|
||||||
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
computePolicyValues = []string{"RECOMMENDED", "REQUIRED"}
|
||||||
computeModeValues = []string{"EQ", "EN", "ANY"}
|
computeModeValues = []string{"EQ", "EN", "ANY"}
|
||||||
computeDiskTypeValues = []string{"D", "B"}
|
computeDiskTypeValues = []string{"D", "B"}
|
||||||
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
computeNetTypeValues = []string{"EXTNET", "VINS"}
|
||||||
computeOrderValues = []string{"cdrom", "network", "hd"}
|
computex86NetTypeValues = []string{"EXTNET", "VINS", "VFNIC", "DPDK", "SDN", "EMPTY", "TRUNK"}
|
||||||
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
|
computeOrderValues = []string{"cdrom", "network", "hd"}
|
||||||
computeDriverValues = []string{"KVM_X86", "SVA_KVM_X86"}
|
computeDataDisksValues = []string{"KEEP", "DETACH", "DESTROY"}
|
||||||
|
|
||||||
diskTypeValues = []string{"B", "T", "D"}
|
diskTypeValues = []string{"B", "T", "D"}
|
||||||
|
|
||||||
flipgroupClientTypeValues = []string{"compute", "vins"}
|
flipgroupClientTypeValues = []string{"compute", "vins"}
|
||||||
|
|
||||||
kvmNetTypeValues = []string{"EXTNET", "VINS", "NONE"}
|
kvmNetTypeValues = []string{"EXTNET", "VINS", "NONE"}
|
||||||
|
kvmx86NetTypeValues = []string{"EXTNET", "VINS", "EMPTY", "VFNIC", "DPDK", "SDN", "TRUNK"}
|
||||||
|
|
||||||
lbAlgorithmValues = []string{"roundrobin", "static-rr", "leastconn"}
|
lbAlgorithmValues = []string{"roundrobin", "static-rr", "leastconn"}
|
||||||
|
|
||||||
rgDefNetValues = []string{"PRIVATE", "PUBLIC", "NONE"}
|
rgDefNetValues = []string{"PRIVATE", "PUBLIC", "NONE"}
|
||||||
rgNetTypeValues = []string{"PUBLIC", "PRIVATE"}
|
rgNetTypeValues = []string{"PUBLIC", "PRIVATE"}
|
||||||
|
|
||||||
vinsTypeValues = []string{"DHCP", "VIP", "EXCLUDE"}
|
vinsTypeValues = []string{"DHCP", "VIP", "EXCLUDED"}
|
||||||
|
|
||||||
imageBootTypeValues = []string{"uefi", "bios"}
|
imageBootTypeValues = []string{"uefi", "bios"}
|
||||||
imageTypeValues = []string{"windows", "linux", "other"}
|
imageTypeValues = []string{"windows", "linux", "unknown"}
|
||||||
imageDriversValues = []string{"KVM_X86"}
|
imageArchitectureValues = []string{"X86_64"}
|
||||||
imageArchitectureValues = []string{"X86_64", "PPC64_LE"}
|
|
||||||
|
|
||||||
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
sepFieldTypeValues = []string{"int", "str", "bool", "list", "dict"}
|
||||||
|
|
||||||
networkPluginValues = []string{"flannel", "weawenet", "calico"}
|
networkPluginValues = []string{"flannel", "weavenet", "calico"}
|
||||||
|
|
||||||
strictLooseValues = []string{"strict", "loose"}
|
strictLooseValues = []string{"strict", "loose"}
|
||||||
|
|
||||||
interfaceStateValues = []string{"on", "off"}
|
interfaceStateValues = []string{"on", "off"}
|
||||||
|
|
||||||
|
actionValues = []string{"is_powered", "power_on", "shutdown", "force_shutdown", "reboot"}
|
||||||
|
|
||||||
|
vmActionValues = []string{"stop", "move"}
|
||||||
|
|
||||||
|
computeFeaturesValues = []string{"hugepages", "numa", "cpupin", "vfnic", "dpdk", "changemac", "trunk"}
|
||||||
|
|
||||||
|
networkInterfaceNamingValues = []string{"eth", "ens"}
|
||||||
|
|
||||||
|
numaAffinityValues = []string{"none", "strict", "loose"}
|
||||||
|
|
||||||
|
txModelValues = []string{"iothread", "timer", "selected by hypervisor"}
|
||||||
|
|
||||||
|
ioEventFDValues = []string{"on", "off", "selected by hypervisor"}
|
||||||
|
|
||||||
|
eventIDxValues = []string{"on", "off", "selected by hypervisor"}
|
||||||
|
|
||||||
|
chipsetValues = []string{"i440fx", "Q35"}
|
||||||
|
|
||||||
|
loaderTypeValues = []string{"linux", "windows", "unknown"}
|
||||||
|
|
||||||
|
sepTypeValues = []string{"hitachi", "dorado", "tatlin", "shared", "local", "des"}
|
||||||
|
|
||||||
|
languageValues = []string{"ru", "en"}
|
||||||
|
|
||||||
|
userProviders = []string{"bvs", "decs3o"}
|
||||||
|
|
||||||
|
deviceValues = []string{"primary", "secondary"}
|
||||||
|
|
||||||
|
securityGroupDirectionValues = []string{"inbound", "outbound"}
|
||||||
|
securityGroupEthertypeValues = []string{"IPv4", "IPv6"}
|
||||||
|
securityGroupProtocolValues = []string{"icmp", "tcp", "udp"}
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
mtuMin = 1
|
||||||
|
mtuMax = 9216
|
||||||
|
|
||||||
|
trunkTagsMin = 1
|
||||||
|
trunkTagsMax = 4095
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -50,7 +51,7 @@ func NewLegacy(cfg config.LegacyConfig) *LegacyDecortClient {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
cfg: cfg,
|
cfg: trimLegacyConfig(&cfg),
|
||||||
expiryTime: expiryTime,
|
expiryTime: expiryTime,
|
||||||
mutex: &sync.Mutex{},
|
mutex: &sync.Mutex{},
|
||||||
}
|
}
|
||||||
@@ -73,20 +74,69 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
values, err := query.Values(params)
|
var body *bytes.Buffer
|
||||||
if err != nil {
|
var ctype string
|
||||||
return nil, err
|
|
||||||
|
byteSlice, ok := params.([]byte)
|
||||||
|
if ok {
|
||||||
|
body = bytes.NewBuffer(byteSlice)
|
||||||
|
ctype = "application/octet-stream"
|
||||||
|
} else {
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.Restmachine+url, body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// perform request
|
// perform request
|
||||||
respBytes, err := ldc.do(req, "")
|
respBytes, err := ldc.do(req, ctype)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return respBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecortApiCallCtype method for sending requests to the platform with content type
|
||||||
|
func (ldc *LegacyDecortClient) DecortApiCallCtype(ctx context.Context, method, url, ctype string, params interface{}) ([]byte, error) {
|
||||||
|
// get token
|
||||||
|
if err := ldc.getToken(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var body *bytes.Buffer
|
||||||
|
|
||||||
|
switch ctype {
|
||||||
|
case constants.MIMESTREAM:
|
||||||
|
body = bytes.NewBuffer(params.([]byte))
|
||||||
|
case constants.MIMEJSON:
|
||||||
|
jsonBody, err := json.Marshal(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBuffer(jsonBody)
|
||||||
|
default:
|
||||||
|
ctype = constants.MIMEPOSTForm
|
||||||
|
values, err := query.Values(params)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body = bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// perform request
|
||||||
|
respBytes, err := ldc.do(req, ctype)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -100,7 +150,7 @@ func (ldc *LegacyDecortClient) DecortApiCallMP(ctx context.Context, method, url
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.Restmachine+url, body)
|
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+constants.RESTMACHINE+url, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -132,7 +182,7 @@ func (ldc *LegacyDecortClient) getToken(ctx context.Context) error {
|
|||||||
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
body := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(ldc.cfg.Username), url.QueryEscape(ldc.cfg.Password))
|
||||||
bodyReader := strings.NewReader(body)
|
bodyReader := strings.NewReader(body)
|
||||||
|
|
||||||
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+"/restmachine/cloudapi/user/authenticate", bodyReader)
|
req, _ := http.NewRequestWithContext(ctx, "POST", ldc.cfg.DecortURL+constants.RESTMACHINE+"/cloudapi/user/authenticate", bodyReader)
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
// request token
|
// request token
|
||||||
@@ -233,3 +283,8 @@ func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) ([]byte, erro
|
|||||||
err = fmt.Errorf("%s", respBytes)
|
err = fmt.Errorf("%s", respBytes)
|
||||||
return nil, fmt.Errorf("could not execute request: %w", err)
|
return nil, fmt.Errorf("could not execute request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func trimLegacyConfig(cfg *config.LegacyConfig) config.LegacyConfig {
|
||||||
|
cfg.DecortURL = strings.TrimSuffix(cfg.DecortURL, "/")
|
||||||
|
return *cfg
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
package account
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CreateRequest struct for creating account
|
|
||||||
type CreateRequest struct {
|
|
||||||
// Display name
|
|
||||||
// Required: true
|
|
||||||
Name string `url:"name" json:"name" validate:"required"`
|
|
||||||
|
|
||||||
// Name of the account
|
|
||||||
// Required: true
|
|
||||||
Username string `url:"username" json:"username" validate:"required"`
|
|
||||||
|
|
||||||
// Email
|
|
||||||
// Required: false
|
|
||||||
EmailAddress string `url:"emailaddress,omitempty" json:"emailaddress,omitempty" validate:"omitempty,email"`
|
|
||||||
|
|
||||||
// Max size of memory in MB
|
|
||||||
// Required: false
|
|
||||||
MaxMemoryCapacity int64 `url:"maxMemoryCapacity,omitempty" json:"maxMemoryCapacity,omitempty"`
|
|
||||||
|
|
||||||
// Max size of aggregated vdisks in GB
|
|
||||||
// Required: false
|
|
||||||
MaxVDiskCapacity int64 `url:"maxVDiskCapacity,omitempty" json:"maxVDiskCapacity,omitempty"`
|
|
||||||
|
|
||||||
// Max number of CPU cores
|
|
||||||
// Required: false
|
|
||||||
MaxCPUCapacity int64 `url:"maxCPUCapacity,omitempty" json:"maxCPUCapacity,omitempty"`
|
|
||||||
|
|
||||||
// Max sent/received network transfer peering
|
|
||||||
// Required: false
|
|
||||||
MaxNetworkPeerTransfer int64 `url:"maxNetworkPeerTransfer,omitempty" json:"maxNetworkPeerTransfer,omitempty"`
|
|
||||||
|
|
||||||
// Max number of assigned public IPs
|
|
||||||
// Required: false
|
|
||||||
MaxNumPublicIP int64 `url:"maxNumPublicIP,omitempty" json:"maxNumPublicIP,omitempty"`
|
|
||||||
|
|
||||||
// If true send emails when a user is granted access to resources
|
|
||||||
// Required: false
|
|
||||||
SendAccessEmails bool `url:"sendAccessEmails" json:"sendAccessEmails"`
|
|
||||||
|
|
||||||
// Limit (positive) or disable (0) GPU resources
|
|
||||||
// Required: false
|
|
||||||
GPUUnits int64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create creates account
|
|
||||||
// Setting a cloud unit maximum to -1 or empty will not put any restrictions on the resource
|
|
||||||
func (a Account) Create(ctx context.Context, req CreateRequest) (uint64, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/account/create"
|
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := strconv.ParseUint(string(res), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
@@ -19,18 +19,18 @@ type DeleteRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete completes delete an account from the system Returns true if account is deleted or was already deleted or never existed
|
// Delete completes delete an account from the system Returns true if account is deleted or was already deleted or never existed
|
||||||
func (a Account) Delete(ctx context.Context, req DeleteRequest) (bool, error) {
|
func (a Account) Delete(ctx context.Context, req DeleteRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/delete"
|
url := "/cloudapi/account/delete"
|
||||||
|
|
||||||
_, err = a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
result, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return true, nil
|
return string(result), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,10 +17,6 @@ type DeleteUserRequest struct {
|
|||||||
// ID or emailaddress of the user to remove
|
// ID or emailaddress of the user to remove
|
||||||
// Required: true
|
// Required: true
|
||||||
UserID string `url:"userId" json:"userId" validate:"required"`
|
UserID string `url:"userId" json:"userId" validate:"required"`
|
||||||
|
|
||||||
// Recursively revoke access rights from owned cloudspaces and vmachines
|
|
||||||
// Required: false
|
|
||||||
RecursiveDelete bool `url:"recursivedelete" json:"recursivedelete"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteUser revokes user access from the account
|
// DeleteUser revokes user access from the account
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
var accounts = ListAccounts{
|
var accounts = ListAccounts{
|
||||||
Data: []ItemAccount{
|
Data: []ItemAccount{
|
||||||
{
|
{
|
||||||
ACL: []RecordACL{
|
ACL: []ListRecordACL{
|
||||||
{
|
{
|
||||||
IsExplicit: true,
|
IsExplicit: true,
|
||||||
GUID: "",
|
GUID: "",
|
||||||
@@ -25,7 +25,7 @@ var accounts = ListAccounts{
|
|||||||
UpdatedTime: 1676645275,
|
UpdatedTime: 1676645275,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ACL: []RecordACL{
|
ACL: []ListRecordACL{
|
||||||
{
|
{
|
||||||
IsExplicit: true,
|
IsExplicit: true,
|
||||||
GUID: "",
|
GUID: "",
|
||||||
@@ -43,7 +43,7 @@ var accounts = ListAccounts{
|
|||||||
UpdatedTime: 1676645275,
|
UpdatedTime: 1676645275,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ACL: []RecordACL{
|
ACL: []ListRecordACL{
|
||||||
{
|
{
|
||||||
IsExplicit: true,
|
IsExplicit: true,
|
||||||
GUID: "",
|
GUID: "",
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
package account
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetConsumptionRequest struct to download the resources tracking files for an account
|
|
||||||
type GetConsumptionRequest struct {
|
|
||||||
// ID an account
|
|
||||||
// Required: true
|
|
||||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
|
||||||
|
|
||||||
// Epoch represents the start time
|
|
||||||
// Required: true
|
|
||||||
Start uint64 `url:"start" json:"start" validate:"required"`
|
|
||||||
|
|
||||||
// Epoch represents the end time
|
|
||||||
// Required: true
|
|
||||||
End uint64 `url:"end" json:"end" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetConsumption downloads the resources tracking files for an account within a given period
|
|
||||||
func (a Account) GetConsumption(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumption"
|
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(res), nil
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetConsumptionGet downloads the resources tracking files for an account within a given period
|
|
||||||
func (a Account) GetConsumptionGet(ctx context.Context, req GetConsumptionRequest) (string, error) {
|
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/account/getConsumption"
|
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(res), nil
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of accounts
|
// ListRequest struct to get list of accounts
|
||||||
@@ -24,6 +26,15 @@ 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"`
|
||||||
|
|
||||||
|
// Sort by zone id
|
||||||
|
// Default value: 0
|
||||||
|
// Required: false
|
||||||
|
ZoneID uint64 `url:"zone_id,omitempty" json:"zone_id,omitempty"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -35,6 +46,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets a list of all accounts the user has access to a ListAccounts struct
|
// List gets a list of all accounts the user has access to a ListAccounts struct
|
||||||
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, error) {
|
||||||
|
|
||||||
res, err := a.ListRaw(ctx, req)
|
res, err := a.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -52,6 +64,11 @@ func (a Account) List(ctx context.Context, req ListRequest) (*ListAccounts, erro
|
|||||||
|
|
||||||
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
// ListRaw gets a list of all accounts the user has access to as an array of bytes
|
||||||
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (a Account) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/list"
|
url := "/cloudapi/account/list"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ type ListComputesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -57,6 +61,7 @@ type ListComputesRequest struct {
|
|||||||
|
|
||||||
// ListComputes gets list all compute instances under specified account, accessible by the user
|
// ListComputes gets list all compute instances under specified account, accessible by the user
|
||||||
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
func (a Account) ListComputes(ctx context.Context, req ListComputesRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get a list of deleted accounts
|
// ListDeletedRequest struct to get a list of deleted accounts
|
||||||
@@ -27,10 +29,20 @@ type ListDeletedRequest struct {
|
|||||||
// Find by access control list
|
// Find by access control list
|
||||||
// Required: false
|
// Required: false
|
||||||
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
|
ACL string `url:"acl,omitempty" json:"acl,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListDeleted gets list of all deleted accounts the user has access to
|
// ListDeleted gets list of all deleted accounts the user has access to
|
||||||
func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
|
func (a Account) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListAccounts, error) {
|
||||||
|
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/listDeleted"
|
url := "/cloudapi/account/listDeleted"
|
||||||
|
|
||||||
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListDisksRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListDisksRequest struct {
|
|||||||
|
|
||||||
// ListDisks gets list all currently unattached disks under specified account
|
// ListDisks gets list all currently unattached disks under specified account
|
||||||
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
|
func (a Account) ListDisks(ctx context.Context, req ListDisksRequest) (*ListDisks, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ type ListFLIPGroupsRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
FLIPGroupID uint64 `url:"flipGroupId,omitempty" json:"flipGroupId,omitempty"`
|
FLIPGroupID uint64 `url:"flipGroupId,omitempty" json:"flipGroupId,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"`
|
||||||
@@ -49,6 +53,7 @@ type ListFLIPGroupsRequest struct {
|
|||||||
|
|
||||||
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
|
// ListFLIPGroups gets list all FLIPGroups under specified account, accessible by the user
|
||||||
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
|
func (a Account) ListFLIPGroups(ctx context.Context, req ListFLIPGroupsRequest) (*ListFLIPGroups, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -41,10 +41,15 @@ type ListRGRequest struct {
|
|||||||
// Find by status
|
// Find by status
|
||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRG gets list of all resource groups under specified account, accessible by the user
|
// ListRG gets list of all resource groups under specified account, accessible by the user
|
||||||
func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
|
func (a Account) ListRG(ctx context.Context, req ListRGRequest) (*ListRG, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListTemplatesRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Type string `url:"type,omitempty" json:"type,omitempty"`
|
Type string `url:"type,omitempty" json:"type,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListTemplatesRequest struct {
|
|||||||
|
|
||||||
// ListTemplates gets list of templates which can be managed by this account
|
// ListTemplates gets list of templates which can be managed by this account
|
||||||
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
func (a Account) ListTemplates(ctx context.Context, req ListTemplatesRequest) (*ListTemplates, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListVINSRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtIP string `url:"extIp,omitempty" json:"extIp,omitempty"`
|
ExtIP string `url:"extIp,omitempty" json:"extIp,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListVINSRequest struct {
|
|||||||
|
|
||||||
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
// ListVINS gets list of all ViNSes under specified account, accessible by the user
|
||||||
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
func (a Account) ListVINS(ctx context.Context, req ListVINSRequest) (*ListVINS, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -1,7 +1,34 @@
|
|||||||
package account
|
package account
|
||||||
|
|
||||||
|
// Access Control List
|
||||||
|
type ListRecordACL struct {
|
||||||
|
// Whether access is explicitly specified
|
||||||
|
IsExplicit bool `json:"explicit"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
|
||||||
|
// Access rights
|
||||||
|
Rights string `json:"right"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Account Type
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// Account owner ID
|
||||||
|
UgroupID string `json:"userGroupId"`
|
||||||
|
|
||||||
|
// Is it possible to remove
|
||||||
|
CanBeDeleted bool `json:"canBeDeleted"`
|
||||||
|
}
|
||||||
|
|
||||||
// Access Control List
|
// Access Control List
|
||||||
type RecordACL struct {
|
type RecordACL struct {
|
||||||
|
// Emails
|
||||||
|
Emails []string `json:"emails"`
|
||||||
|
|
||||||
// Whether access is explicitly specified
|
// Whether access is explicitly specified
|
||||||
IsExplicit bool `json:"explicit"`
|
IsExplicit bool `json:"explicit"`
|
||||||
|
|
||||||
@@ -46,12 +73,24 @@ type ResourceLimits struct {
|
|||||||
|
|
||||||
// Number of graphics cores
|
// Number of graphics cores
|
||||||
GPUUnits float64 `json:"gpu_units"`
|
GPUUnits float64 `json:"gpu_units"`
|
||||||
|
|
||||||
|
// Storage policy
|
||||||
|
StoragePolicy []StoragePolicyItem `json:"storage_policy"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type StoragePolicyItem struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
Limit int `json:"limit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main information in one of if the list of accounts
|
// Main information in one of if the list of accounts
|
||||||
type ItemAccount struct {
|
type ItemAccount struct {
|
||||||
// Access Control List
|
// Access Control List
|
||||||
ACL []RecordACL `json:"acl"`
|
ACL []ListRecordACL `json:"acl"`
|
||||||
|
|
||||||
|
// Compute Features
|
||||||
|
ComputeFeatures []string `json:"computeFeatures"`
|
||||||
|
|
||||||
// Created time
|
// Created time
|
||||||
CreatedTime uint64 `json:"createdTime"`
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
@@ -59,6 +98,9 @@ type ItemAccount struct {
|
|||||||
// Deleted time
|
// Deleted time
|
||||||
DeletedTime uint64 `json:"deletedTime"`
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"desc"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
@@ -70,6 +112,9 @@ type ItemAccount struct {
|
|||||||
|
|
||||||
// Updated time
|
// Updated time
|
||||||
UpdatedTime uint64 `json:"updatedTime"`
|
UpdatedTime uint64 `json:"updatedTime"`
|
||||||
|
|
||||||
|
// Zones
|
||||||
|
ZoneIDs []uint64 `json:"zoneIds"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of accounts
|
// List of accounts
|
||||||
@@ -79,6 +124,18 @@ type ListAccounts struct {
|
|||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Policy
|
||||||
|
type Policy struct {
|
||||||
|
// Size of the disk
|
||||||
|
DiskSize float64 `json:"disksize"`
|
||||||
|
|
||||||
|
// Max size of the disk
|
||||||
|
DiskSizeMax float64 `json:"disksizemax"`
|
||||||
|
|
||||||
|
// SEPs used
|
||||||
|
SEPs map[string]map[string]DiskUsage `json:"seps"`
|
||||||
|
}
|
||||||
|
|
||||||
// Resources used
|
// Resources used
|
||||||
type Resource struct {
|
type Resource struct {
|
||||||
// Number of cores
|
// Number of cores
|
||||||
@@ -99,6 +156,9 @@ type Resource struct {
|
|||||||
// Number of grafic cores
|
// Number of grafic cores
|
||||||
GPU int64 `json:"gpu"`
|
GPU int64 `json:"gpu"`
|
||||||
|
|
||||||
|
// Policies
|
||||||
|
Policies map[string]Policy `json:"policies"`
|
||||||
|
|
||||||
// Number of RAM
|
// Number of RAM
|
||||||
RAM int64 `json:"ram"`
|
RAM int64 `json:"ram"`
|
||||||
|
|
||||||
@@ -159,14 +219,20 @@ type Machines struct {
|
|||||||
Halted uint64 `json:"halted"`
|
Halted uint64 `json:"halted"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Detailed information about the account zone
|
||||||
|
type ZoneID struct {
|
||||||
|
// ID of zone
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
|
||||||
|
// Name of zone
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
// Main information about account
|
// Main information about account
|
||||||
type RecordAccount struct {
|
type RecordAccount struct {
|
||||||
// DCLocation
|
// DCLocation
|
||||||
DCLocation string `json:"DCLocation"`
|
DCLocation string `json:"DCLocation"`
|
||||||
|
|
||||||
// CKey
|
|
||||||
CKey string `json:"_ckey"`
|
|
||||||
|
|
||||||
// Access control list
|
// Access control list
|
||||||
ACL []RecordACL `json:"acl"`
|
ACL []RecordACL `json:"acl"`
|
||||||
|
|
||||||
@@ -176,6 +242,9 @@ type RecordAccount struct {
|
|||||||
// Company URL
|
// Company URL
|
||||||
CompanyURL string `json:"companyurl"`
|
CompanyURL string `json:"companyurl"`
|
||||||
|
|
||||||
|
// Compute Features
|
||||||
|
ComputeFeatures []string `json:"computeFeatures"`
|
||||||
|
|
||||||
// Computes
|
// Computes
|
||||||
Computes Computes `json:"computes"`
|
Computes Computes `json:"computes"`
|
||||||
|
|
||||||
@@ -191,6 +260,9 @@ type RecordAccount struct {
|
|||||||
// Created time
|
// Created time
|
||||||
CreatedTime uint64 `json:"createdTime"`
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"desc"`
|
||||||
|
|
||||||
// Deactivation time
|
// Deactivation time
|
||||||
DeactivationTime float64 `json:"deactivationTime"`
|
DeactivationTime float64 `json:"deactivationTime"`
|
||||||
|
|
||||||
@@ -227,6 +299,9 @@ type RecordAccount struct {
|
|||||||
// Status
|
// Status
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Storage policy ids
|
||||||
|
StoragePolicyIDs []uint64 `json:"storage_policy_ids"`
|
||||||
|
|
||||||
// UniqPools
|
// UniqPools
|
||||||
UniqPools []interface{} `json:"uniqPools"`
|
UniqPools []interface{} `json:"uniqPools"`
|
||||||
|
|
||||||
@@ -241,6 +316,12 @@ type RecordAccount struct {
|
|||||||
|
|
||||||
// VINSes
|
// VINSes
|
||||||
VINSes uint64 `json:"vinses"`
|
VINSes uint64 `json:"vinses"`
|
||||||
|
|
||||||
|
// Zone
|
||||||
|
ZoneIDs []ZoneID `json:"zoneIds"`
|
||||||
|
|
||||||
|
// Zones
|
||||||
|
DefaultZoneID uint64 `json:"defaultZoneId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main information about compute
|
// Main information about compute
|
||||||
@@ -374,6 +455,12 @@ type ItemVINS struct {
|
|||||||
// External IP
|
// External IP
|
||||||
ExternalIP string `json:"externalIP"`
|
ExternalIP string `json:"externalIP"`
|
||||||
|
|
||||||
|
// Extnet ID
|
||||||
|
ExtnetId uint64 `json:"extnetId"`
|
||||||
|
|
||||||
|
// Free IPs
|
||||||
|
FreeIPs int64 `json:"freeIPs"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
@@ -500,6 +587,9 @@ type ItemRG struct {
|
|||||||
// Deleted time
|
// Deleted time
|
||||||
DeletedTime uint64 `json:"deletedTime"`
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"desc"`
|
||||||
|
|
||||||
// Resource group ID
|
// Resource group ID
|
||||||
RGID uint64 `json:"id"`
|
RGID uint64 `json:"id"`
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package account
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,18 +15,18 @@ type RestoreRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Restore restores a deleted account
|
// Restore restores a deleted account
|
||||||
func (a Account) Restore(ctx context.Context, req RestoreRequest) (bool, error) {
|
func (a Account) Restore(ctx context.Context, req RestoreRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/account/restore"
|
url := "/cloudapi/account/restore"
|
||||||
|
|
||||||
_, err = a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
result, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return true, nil
|
return string(result), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ type UpdateRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
// Required: false
|
||||||
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
|
|
||||||
// Name of the account
|
// Name of the account
|
||||||
// Required: false
|
// Required: false
|
||||||
Name string `url:"name,omitempty" json:"name,omitempty"`
|
Name string `url:"name,omitempty" json:"name,omitempty"`
|
||||||
@@ -45,6 +49,15 @@ type UpdateRequest struct {
|
|||||||
// Limit (positive) or disable (0) GPU resources
|
// Limit (positive) or disable (0) GPU resources
|
||||||
// Required: false
|
// Required: false
|
||||||
GPUUnits int64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
GPUUnits int64 `url:"gpu_units,omitempty" json:"gpu_units,omitempty"`
|
||||||
|
|
||||||
|
// List of strings with pools
|
||||||
|
// i.e.: ["sep1_poolName1", "sep2_poolName2", etc]
|
||||||
|
// Required: false
|
||||||
|
UniqPools []string `url:"uniqPools,omitempty" json:"uniqPools,omitempty"`
|
||||||
|
|
||||||
|
// Default zone ID
|
||||||
|
// Required: false
|
||||||
|
DefaultZoneID uint64 `url:"defaultZoneId,omitempty" json:"defaultZoneId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update updates an account name and resource types and limits
|
// Update updates an account name and resource types and limits
|
||||||
|
|||||||
10
pkg/cloudapi/audit.go
Normal file
10
pkg/cloudapi/audit.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package cloudapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/audit"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Accessing the Stack method group
|
||||||
|
func (ca *CloudAPI) Audit() *audit.Audit {
|
||||||
|
return audit.New(ca.client)
|
||||||
|
}
|
||||||
15
pkg/cloudapi/audit/audit.go
Normal file
15
pkg/cloudapi/audit/audit.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import "repository.basistech.ru/BASIS/decort-golang-sdk/interfaces"
|
||||||
|
|
||||||
|
// Structure for creating request to audit
|
||||||
|
type Audit struct {
|
||||||
|
client interfaces.Caller
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builder for audit endpoint
|
||||||
|
func New(client interfaces.Caller) *Audit{
|
||||||
|
return &Audit{
|
||||||
|
client: client,
|
||||||
|
}
|
||||||
|
}
|
||||||
81
pkg/cloudapi/audit/filter.go
Normal file
81
pkg/cloudapi/audit/filter.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
// FilterByID returns ListAudits with specified ID.
|
||||||
|
func (la ListAudits) FilterByID(guid string) ListAudits {
|
||||||
|
predicate := func(ia ItemAudit) bool {
|
||||||
|
return ia.GUID == guid
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByCall returns ListAudits with specified call.
|
||||||
|
func (la ListAudits) FilterByCall(call string) ListAudits {
|
||||||
|
predicate := func(ic ItemAudit) bool {
|
||||||
|
return ic.Call == call
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByCorrelationID returns ListAudits with specified correlation id.
|
||||||
|
func (la ListAudits) FilterByCorrelationID(correlationID string) ListAudits {
|
||||||
|
predicate := func(ic ItemAudit) bool {
|
||||||
|
return ic.CorrelationID == correlationID
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByRemoteAddr returns ListAudits with specified remote address.
|
||||||
|
func (la ListAudits) FilterByRemoteAddr(remoteAddr string) ListAudits {
|
||||||
|
predicate := func(ic ItemAudit) bool {
|
||||||
|
return ic.RemoteAddr == remoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByUser returns ListAudits with specified user name.
|
||||||
|
func (la ListAudits) FilterByUser(user string) ListAudits {
|
||||||
|
predicate := func(ic ItemAudit) bool {
|
||||||
|
return ic.User == user
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterByStatusCode return ListAudits with specified status code.
|
||||||
|
func (la ListAudits) FilterByStatusCode(statusCode uint64) ListAudits {
|
||||||
|
predicate := func(ic ItemAudit) bool {
|
||||||
|
return ic.StatusCode == statusCode
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.FilterFunc(predicate)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterFunc allows filtering ListAudits based on a user-specified predicate.
|
||||||
|
func (la ListAudits) FilterFunc(predicate func(ItemAudit) bool) ListAudits {
|
||||||
|
var result ListAudits
|
||||||
|
|
||||||
|
for _, item := range la.Data {
|
||||||
|
if predicate(item) {
|
||||||
|
result.Data = append(result.Data, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.EntryCount = uint64(len(result.Data))
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindOne returns first found ItemAudit
|
||||||
|
// If none was found, returns an empty struct.
|
||||||
|
func (la ListAudits) FindOne() ItemAudit {
|
||||||
|
if len(la.Data) == 0 {
|
||||||
|
return ItemAudit{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return la.Data[0]
|
||||||
|
}
|
||||||
115
pkg/cloudapi/audit/filter_test.go
Normal file
115
pkg/cloudapi/audit/filter_test.go
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var audits = ListAudits{
|
||||||
|
Data: []ItemAudit{
|
||||||
|
{
|
||||||
|
Args: "[]",
|
||||||
|
Call: "/restmachine/cloudapi/audit/linkedJobs",
|
||||||
|
GUID: "550e8400-e29b-41d4-a716-446655440001",
|
||||||
|
CorrelationID: "550e8400-e29b-41d4-a716-446655440001",
|
||||||
|
Kwargs: `{\"audit_guid\":\"dd8623a1-a887-48c1-a500-c10210d404cf\"}`,
|
||||||
|
RemoteAddr: "192.168.1.100",
|
||||||
|
ResponseTime: 1,
|
||||||
|
Result: `[]`,
|
||||||
|
StatusCode: 200,
|
||||||
|
Timestamp: 1640995200,
|
||||||
|
TimestampEnd: 1640995201,
|
||||||
|
User: "test@example.com",
|
||||||
|
TTL: "2025-07-31T14:22:57.028000",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Args: "[]",
|
||||||
|
Call: "/restmachine/cloudapi/audit/test",
|
||||||
|
GUID: "550e8400-e29b-41d4-a716-446655440002",
|
||||||
|
CorrelationID: "550e8400-e29b-41d4-a716-446655440002",
|
||||||
|
Kwargs: `{\"audit_guid\":\"dd8623a1-a887-48c1-a500-c10210d404cf\"}`,
|
||||||
|
RemoteAddr: "192.168.1.105",
|
||||||
|
ResponseTime: 5,
|
||||||
|
Result: `[]`,
|
||||||
|
StatusCode: 400,
|
||||||
|
Timestamp: 1640995200,
|
||||||
|
TimestampEnd: 1640995201,
|
||||||
|
User: "test2@example.com",
|
||||||
|
TTL: "2025-07-31T14:22:57.028000",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
EntryCount: 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByID(t *testing.T) {
|
||||||
|
actual := audits.FilterByID("550e8400-e29b-41d4-a716-446655440002").FindOne()
|
||||||
|
|
||||||
|
if actual.GUID != "550e8400-e29b-41d4-a716-446655440002" {
|
||||||
|
t.Fatal("expected GUID 550e8400-e29b-41d4-a716-446655440002, found: ", actual.GUID)
|
||||||
|
}
|
||||||
|
|
||||||
|
actualEmpty := audits.FilterByID("")
|
||||||
|
|
||||||
|
if len(actualEmpty.Data) != 0 {
|
||||||
|
t.Fatal("expected empty, actual: ", len(actualEmpty.Data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByCorrelationID(t *testing.T) {
|
||||||
|
actual := audits.FilterByCorrelationID("550e8400-e29b-41d4-a716-446655440002").FindOne()
|
||||||
|
|
||||||
|
if actual.CorrelationID != "550e8400-e29b-41d4-a716-446655440002" {
|
||||||
|
t.Fatal("expected GUID 550e8400-e29b-41d4-a716-446655440002, found: ", actual.CorrelationID)
|
||||||
|
}
|
||||||
|
|
||||||
|
actualEmpty := audits.FilterByCorrelationID("")
|
||||||
|
|
||||||
|
if len(actualEmpty.Data) != 0 {
|
||||||
|
t.Fatal("expected empty, actual: ", len(actualEmpty.Data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByRemoteAddr(t *testing.T) {
|
||||||
|
actual := audits.FilterByRemoteAddr("192.168.1.100").FindOne()
|
||||||
|
|
||||||
|
if actual.RemoteAddr != "192.168.1.100" {
|
||||||
|
t.Fatal("expected remote address 192.168.1.100, found: ", actual.RemoteAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
actualEmpty := audits.FilterByRemoteAddr("")
|
||||||
|
|
||||||
|
if len(actualEmpty.Data) != 0 {
|
||||||
|
t.Fatal("expected empty, actual: ", len(actualEmpty.Data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByUser(t *testing.T) {
|
||||||
|
actual := audits.FilterByUser("test@example.com").FindOne()
|
||||||
|
|
||||||
|
if actual.User != "test@example.com" {
|
||||||
|
t.Fatal("expected user test@example.com, found: ", actual.RemoteAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
actualEmpty := audits.FilterByUser("")
|
||||||
|
|
||||||
|
if len(actualEmpty.Data) != 0 {
|
||||||
|
t.Fatal("expected empty, actual: ", len(actualEmpty.Data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByCall(t *testing.T) {
|
||||||
|
actual := audits.FilterByCall("/restmachine/cloudapi/audit/test").FindOne()
|
||||||
|
|
||||||
|
if actual.Call != "/restmachine/cloudapi/audit/test" {
|
||||||
|
t.Fatal("expected call /restmachine/cloudapi/audit/test, found: ", actual.Call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterByStatusCode(t *testing.T) {
|
||||||
|
actual := audits.FilterByStatusCode(200)
|
||||||
|
|
||||||
|
for _, item := range actual.Data {
|
||||||
|
if item.StatusCode != 200 {
|
||||||
|
t.Fatal("expected 200 status code, found: ", item.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
46
pkg/cloudapi/audit/get.go
Normal file
46
pkg/cloudapi/audit/get.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetRequest struct to get information about account
|
||||||
|
type GetRequest struct {
|
||||||
|
// Audit GUID
|
||||||
|
// Required: true
|
||||||
|
AuditGuid string `url:"audit_guid" json:"audit_guid" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gets information about audit as a RecordAudit struct
|
||||||
|
func (a Audit) Get(ctx context.Context, req GetRequest) (*RecordAudit, error) {
|
||||||
|
res, err := a.GetRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
info := RecordAudit{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &info)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRaw gets information about audit as an array of bytes
|
||||||
|
func (a Audit) GetRaw(ctx context.Context, req GetRequest) ([]byte, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/audit/get"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
124
pkg/cloudapi/audit/list.go
Normal file
124
pkg/cloudapi/audit/list.go
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListRequest struct to give list of account audits
|
||||||
|
type ListRequest struct {
|
||||||
|
|
||||||
|
// Find all audits after point in time (unixtime)
|
||||||
|
// Required: false
|
||||||
|
TimestampAt uint64 `url:"timestamp_at,omitempty" json:"timestamp_at,omitempty"`
|
||||||
|
|
||||||
|
// Find all audits before point in time (unixtime)
|
||||||
|
// Required: false
|
||||||
|
TimestampTo uint64 `url:"timestamp_to,omitempty" json:"timestamp_to,omitempty"`
|
||||||
|
|
||||||
|
// Find by user (Mongo RegExp supported)
|
||||||
|
// Required: false
|
||||||
|
User string `url:"user,omitempty" json:"user,omitempty"`
|
||||||
|
|
||||||
|
// Find by api endpoint (Mongo RegExp supported)
|
||||||
|
// Required: false
|
||||||
|
Call string `url:"call,omitempty" json:"call,omitempty"`
|
||||||
|
|
||||||
|
// Find by request id
|
||||||
|
// Required: false
|
||||||
|
RequestID string `url:"request_id,omitempty" json:"request_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by HTTP min status code
|
||||||
|
// Required: false
|
||||||
|
MinStatusCode uint64 `url:"min_status_code,omitempty" json:"min_status_code,omitempty"`
|
||||||
|
|
||||||
|
// Find by HTTP max status code
|
||||||
|
// Required: false
|
||||||
|
MaxStatusCode uint64 `url:"max_status_code,omitempty" json:"max_status_code,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sort_by,omitempty" json:"sort_by,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
|
||||||
|
// Find by resource group id
|
||||||
|
// Required: false
|
||||||
|
RGID uint64 `url:"resgroup_id,omitempty" json:"resgroup_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by compute id
|
||||||
|
// Required: false
|
||||||
|
ComputeID uint64 `url:"compute_id,omitempty" json:"compute_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by account id
|
||||||
|
// Required: false
|
||||||
|
AccountID uint64 `url:"account_id,omitempty" json:"account_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by vins id
|
||||||
|
// Required: false
|
||||||
|
VINSID uint64 `url:"vins_id,omitempty" json:"vins_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by service id
|
||||||
|
// Required: false
|
||||||
|
ServiceID uint64 `url:"service_id,omitempty" json:"service_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by k8s id
|
||||||
|
// Required: false
|
||||||
|
K8SID uint64 `url:"k8s_id,omitempty" json:"k8s_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by flipgroup id
|
||||||
|
// Required: false
|
||||||
|
FLIPGroupID uint64 `url:"flipgroup_id,omitempty" json:"flipgroup_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by load balancer id
|
||||||
|
// Required: false
|
||||||
|
LBID uint64 `url:"lb_id,omitempty" json:"lb_id,omitempty"`
|
||||||
|
|
||||||
|
// Find by sep id
|
||||||
|
// Required: false
|
||||||
|
SEPID uint64 `url:"sep_id,omitempty" json:"sep_id,omitempty"`
|
||||||
|
|
||||||
|
// Exclude audit lines from response
|
||||||
|
// Required: false
|
||||||
|
ExcludeAuditLines bool `url:"exclude_audit_lines,omitempty" json:"exclude_audit_lines,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List gets audit records for the specified account object
|
||||||
|
func (a Audit) List(ctx context.Context, req ListRequest) (*ListAudits, error) {
|
||||||
|
|
||||||
|
res, err := a.ListRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
list := ListAudits{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &list)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &list, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRaw gets list of audit records an array of bytes
|
||||||
|
func (a Audit) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/audit/list"
|
||||||
|
|
||||||
|
res, err := a.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
95
pkg/cloudapi/audit/models.go
Normal file
95
pkg/cloudapi/audit/models.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
// Main info about audit
|
||||||
|
type RecordAudit struct {
|
||||||
|
|
||||||
|
// Arguments
|
||||||
|
Arguments string `json:"args"`
|
||||||
|
|
||||||
|
// Call
|
||||||
|
Call string `json:"call"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
|
||||||
|
// Correlation ID
|
||||||
|
CorrelationID string `json:"correlation_id"`
|
||||||
|
|
||||||
|
// Kwargs
|
||||||
|
Kwargs string `json:"kwargs"`
|
||||||
|
|
||||||
|
// RemoteAddr
|
||||||
|
RemoteAddr string `json:"remote_addr"`
|
||||||
|
|
||||||
|
// Response time
|
||||||
|
ResponseTime float64 `json:"responsetime"`
|
||||||
|
|
||||||
|
// Result
|
||||||
|
Result string `json:"result"`
|
||||||
|
|
||||||
|
// Status code
|
||||||
|
StatusCode uint64 `json:"statuscode"`
|
||||||
|
|
||||||
|
// Tags
|
||||||
|
Tags string `json:"tags"`
|
||||||
|
|
||||||
|
// Timestamp
|
||||||
|
Timestamp float64 `json:"timestamp"`
|
||||||
|
|
||||||
|
// TimestampEnd
|
||||||
|
TimestampEnd float64 `json:"timestampEnd"`
|
||||||
|
|
||||||
|
// User
|
||||||
|
User string `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main info about audit
|
||||||
|
type ItemAudit struct {
|
||||||
|
// Args
|
||||||
|
Args string `json:"args"`
|
||||||
|
|
||||||
|
// Call
|
||||||
|
Call string `json:"call"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
|
||||||
|
// Correlation ID
|
||||||
|
CorrelationID string `json:"correlation_id"`
|
||||||
|
|
||||||
|
// Kwargs
|
||||||
|
Kwargs string `json:"kwargs"`
|
||||||
|
|
||||||
|
// RemoteAddr
|
||||||
|
RemoteAddr string `json:"remote_addr"`
|
||||||
|
|
||||||
|
// Response time
|
||||||
|
ResponseTime float64 `json:"responsetime"`
|
||||||
|
|
||||||
|
// Result
|
||||||
|
Result string `json:"result"`
|
||||||
|
|
||||||
|
// Status code
|
||||||
|
StatusCode uint64 `json:"statuscode"`
|
||||||
|
|
||||||
|
// Timestamp
|
||||||
|
Timestamp float64 `json:"timestamp"`
|
||||||
|
|
||||||
|
// Timestamp End
|
||||||
|
TimestampEnd float64 `json:"timestampEnd"`
|
||||||
|
|
||||||
|
// User
|
||||||
|
User string `json:"user"`
|
||||||
|
|
||||||
|
// TTL
|
||||||
|
TTL string `json:"_ttl"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of audits
|
||||||
|
type ListAudits struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemAudit `json:"data"`
|
||||||
|
|
||||||
|
// EntryCount
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
@@ -25,6 +25,10 @@ type CreateRequest struct {
|
|||||||
// SSH key to deploy for the specified user. Same key will be deployed to all computes of the service
|
// SSH key to deploy for the specified user. Same key will be deployed to all computes of the service
|
||||||
// Required: false
|
// Required: false
|
||||||
SSHKey string `url:"sshKey,omitempty" json:"sshKey,omitempty"`
|
SSHKey string `url:"sshKey,omitempty" json:"sshKey,omitempty"`
|
||||||
|
|
||||||
|
// Zone ID
|
||||||
|
// Required: false
|
||||||
|
ZoneID uint64 `url:"zoneId,omitempty" json:"zoneId,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create creates blank BasicService instance
|
// Create creates blank BasicService instance
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ type DeleteRequest struct {
|
|||||||
|
|
||||||
// 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
|
||||||
|
// Default: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func (b BService) Disable(ctx context.Context, req DisableRequest) (bool, error)
|
|||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/delete"
|
url := "/cloudapi/bservice/disable"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -38,12 +38,9 @@ type GroupAddRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
ImageID uint64 `url:"imageId" json:"imageId" validate:"required"`
|
||||||
|
|
||||||
// Compute driver
|
// Compute driver like a KVM_X86, etc.
|
||||||
// should be one of:
|
|
||||||
// - KVM_X86
|
|
||||||
// - KVM_PPC
|
|
||||||
// Required: true
|
// Required: true
|
||||||
Driver string `url:"driver" json:"driver" validate:"driver"`
|
Driver string `url:"driver" json:"driver" validate:"required"`
|
||||||
|
|
||||||
// Storage endpoint provider ID
|
// Storage endpoint provider ID
|
||||||
// Required: false
|
// Required: false
|
||||||
@@ -72,6 +69,24 @@ type GroupAddRequest struct {
|
|||||||
// Meta data for working group computes, format YAML "user_data": 1111
|
// Meta data for working group computes, format YAML "user_data": 1111
|
||||||
// Required: false
|
// Required: false
|
||||||
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
UserData string `url:"userData,omitempty" json:"userData,omitempty"`
|
||||||
|
|
||||||
|
//Chipset "i440fx" or "Q35
|
||||||
|
//Required: false
|
||||||
|
Chipset string `url:"chipset,omitempty" json:"chipset,omitempty" validate:"chipset,omitempty"`
|
||||||
|
|
||||||
|
// ID of the chosen storage policy
|
||||||
|
// Required: false
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id,omitempty" json:"storage_policy_id,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.
|
||||||
|
|||||||
@@ -22,6 +22,12 @@ type GroupResizeRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
Count int64 `url:"count" json:"count" validate:"required"`
|
Count int64 `url:"count" json:"count" validate:"required"`
|
||||||
|
|
||||||
|
//Chipset for new computes, either i440fx or Q35 (i440fx by default)
|
||||||
|
//Available values : i440fx, Q35
|
||||||
|
//Default value : i440fx
|
||||||
|
//Required: true
|
||||||
|
Chipset string `url:"chipset" json:"chipset" validate:"required,chipset"`
|
||||||
|
|
||||||
// Either delta or absolute value of computes
|
// Either delta or absolute value of computes
|
||||||
// Should be one of:
|
// Should be one of:
|
||||||
// - ABSOLUTE
|
// - ABSOLUTE
|
||||||
|
|||||||
@@ -43,6 +43,16 @@ type GroupUpdateRequest struct {
|
|||||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r GroupUpdateRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// GroupUpdate updates existing Compute group within Basic Service and apply new settings to its computes as necessary
|
// GroupUpdate updates existing Compute group within Basic Service and apply new settings to its computes as necessary
|
||||||
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
|
func (b BService) GroupUpdate(ctx context.Context, req GroupUpdateRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of BasicService instances
|
// ListRequest struct to get list of BasicService instances
|
||||||
@@ -40,6 +42,15 @@ 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"`
|
||||||
|
|
||||||
|
// Sort by zone id
|
||||||
|
// Default value: 0
|
||||||
|
// Required: false
|
||||||
|
ZoneID uint64 `url:"zone_id,omitempty" json:"zone_id,omitempty"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -51,6 +62,7 @@ type ListRequest struct {
|
|||||||
|
|
||||||
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
// List gets list of BasicService instances associated with the specified Resource Group as a ListBasicServices struct
|
||||||
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices, error) {
|
||||||
|
|
||||||
res, err := b.ListRaw(ctx, req)
|
res, err := b.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -68,6 +80,11 @@ func (b BService) List(ctx context.Context, req ListRequest) (*ListBasicServices
|
|||||||
|
|
||||||
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
// ListRaw gets list of BasicService instances associated with the specified Resource Group as an array of bytes
|
||||||
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (b BService) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/list"
|
url := "/cloudapi/bservice/list"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get list of deleted BasicService instances
|
// ListDeletedRequest struct to get list of deleted BasicService instances
|
||||||
@@ -16,6 +18,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
RGID uint64 `url:"rgId,omitempty" json:"rgId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -27,6 +33,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
// ListDeleted gets list of deleted BasicService instances associated with the specified Resource Group
|
||||||
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
|
func (b BService) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListBasicServices, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/bservice/listDeleted"
|
url := "/cloudapi/bservice/listDeleted"
|
||||||
|
|
||||||
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := b.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
42
pkg/cloudapi/bservice/migrate_to_zone.go
Normal file
42
pkg/cloudapi/bservice/migrate_to_zone.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package bservice
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MigrateToZone struct to move basic service to another zone
|
||||||
|
type MigrateToZoneRequest struct {
|
||||||
|
// ID of the BasicService to move
|
||||||
|
// Required: true
|
||||||
|
ServiceID uint64 `url:"serviceId" json:"serviceId" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the zone to move
|
||||||
|
// Required: true
|
||||||
|
ZoneID uint64 `url:"zoneId" json:"zoneId" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MigrateToZone moves basic service instance to new zone
|
||||||
|
func (b BService) MigrateToZone(ctx context.Context, req MigrateToZoneRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/bservice/migrateToZone"
|
||||||
|
|
||||||
|
res, err := b.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
|
||||||
|
}
|
||||||
@@ -88,12 +88,15 @@ type RecordBasicService struct {
|
|||||||
|
|
||||||
// Whether user controlled
|
// Whether user controlled
|
||||||
UserManaged bool `json:"userManaged"`
|
UserManaged bool `json:"userManaged"`
|
||||||
|
|
||||||
|
// Zone ID
|
||||||
|
ZoneID uint64 `json:"zoneId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main information about Compute
|
// Main information about Compute
|
||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
// Architecture
|
// Architecture
|
||||||
Architecture string `json:"arch"`
|
Architecture string `json:"arch"`
|
||||||
@@ -295,6 +298,9 @@ type ItemGroupCompute struct {
|
|||||||
|
|
||||||
// List of information about OS Users
|
// List of information about OS Users
|
||||||
OSUsers ListOSUsers `json:"osUsers"`
|
OSUsers ListOSUsers `json:"osUsers"`
|
||||||
|
|
||||||
|
//Chipset
|
||||||
|
Chipset string `json:"chipset"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of Group Computes
|
// List of Group Computes
|
||||||
@@ -379,6 +385,9 @@ type ItemBasicService struct {
|
|||||||
|
|
||||||
// User Managed or not
|
// User Managed or not
|
||||||
UserManaged bool `json:"userManaged"`
|
UserManaged bool `json:"userManaged"`
|
||||||
|
|
||||||
|
// Zone ID
|
||||||
|
ZoneID uint64 `json:"zoneId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of BasicServices
|
// List of BasicServices
|
||||||
|
|||||||
42
pkg/cloudapi/compute/abort_shared_snapshot_merge.go
Normal file
42
pkg/cloudapi/compute/abort_shared_snapshot_merge.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AbortSharedSnapshotMergeRequest struct to abort shared snapshots merge
|
||||||
|
type AbortSharedSnapshotMergeRequest struct {
|
||||||
|
// ID of the compute
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Label of the snapshot
|
||||||
|
// Required: true
|
||||||
|
Label string `url:"label" json:"label" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AbortSharedSnapshotMerge shared snapshots merge abort
|
||||||
|
func (c Compute) AbortSharedSnapshotMerge(ctx context.Context, req AbortSharedSnapshotMergeRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/abort_shared_snapshot_merge"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -38,8 +38,9 @@ type AffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleAdd add affinity rule
|
// AffinityRuleAdd add affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,9 @@ type AffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AffinityRuleRemove remove affinity rule
|
// AffinityRuleRemove remove affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,9 @@ type AntiAffinityRuleAddRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleAdd add anti affinity rule
|
// AntiAffinityRuleAdd add anti affinity rule
|
||||||
|
|||||||
@@ -38,8 +38,9 @@ type AntiAffinityRuleRemoveRequest struct {
|
|||||||
Key string `url:"key" json:"key" validate:"required"`
|
Key string `url:"key" json:"key" validate:"required"`
|
||||||
|
|
||||||
// Value that must match the key to be taken into account when analyzing this rule
|
// Value that must match the key to be taken into account when analyzing this rule
|
||||||
// Required: true
|
// Required: false
|
||||||
Value string `url:"value" json:"value" validate:"required"`
|
// Not required on purpose: despite required tag on platform, empty string is allowed
|
||||||
|
Value string `url:"value" json:"value"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AntiAffinityRuleRemove remove anti affinity rule
|
// AntiAffinityRuleRemove remove anti affinity rule
|
||||||
|
|||||||
@@ -12,11 +12,47 @@ import (
|
|||||||
type AuditsRequest struct {
|
type AuditsRequest struct {
|
||||||
// ID of the compute
|
// ID of the compute
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Find all audits after point in time
|
||||||
|
// Required: false
|
||||||
|
TimestampAT uint64 `url:"timestamp_at,omitempty" json:"timestamp_at,omitempty"`
|
||||||
|
|
||||||
|
// Find all audits before point in time
|
||||||
|
// Required: false
|
||||||
|
TimestampTO uint64 `url:"timestamp_to,omitempty" json:"timestamp_to,omitempty"`
|
||||||
|
|
||||||
|
// Find by user
|
||||||
|
// Required: false
|
||||||
|
User string `url:"user,omitempty" json:"user,omitempty"`
|
||||||
|
|
||||||
|
// Find by api endpoints
|
||||||
|
// Required: false
|
||||||
|
Call string `url:"call,omitempty" json:"call,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format ±<field>
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sort_by,omitempty" json:"sort_by,omitempty"`
|
||||||
|
|
||||||
|
// Page number
|
||||||
|
// Required: false
|
||||||
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
|
|
||||||
|
// Page size
|
||||||
|
// Required: false
|
||||||
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
|
||||||
|
// Find by HTTP min status code
|
||||||
|
// Required: false
|
||||||
|
MinStatusCode uint64 `url:"min_status_code,omitempty" json:"min_status_code,omitempty"`
|
||||||
|
|
||||||
|
// Find by HTTP max status code
|
||||||
|
// Required: false
|
||||||
|
MaxStatusCode uint64 `url:"max_status_code,omitempty" json:"max_status_code,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Audits gets audit records for the specified compute object
|
// Audits gets audit records for the specified compute object
|
||||||
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))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
@@ -24,7 +60,7 @@ func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, err
|
|||||||
|
|
||||||
url := "/cloudapi/compute/audits"
|
url := "/cloudapi/compute/audits"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -36,5 +72,5 @@ func (c Compute) Audits(ctx context.Context, req AuditsRequest) (ListAudits, err
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return list, nil
|
return &list, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,25 +8,25 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RepairBootFSRequest struct to repair filesystem
|
// BootDiskSetRequest struct to set boot disk for compute
|
||||||
type RepairBootFSRequest struct {
|
type BootDiskSetRequest struct {
|
||||||
// ID of compute instance
|
// ID of compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
// Reason for action
|
// ID of the disk to set as boot
|
||||||
// Required: false
|
// Required: true
|
||||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RepairBootFS repairs compute boot disk filesystem
|
// BootDiskSet sets boot disk for compute
|
||||||
func (c Compute) RepairBootFS(ctx context.Context, req RepairBootFSRequest) (bool, error) {
|
func (c Compute) BootDiskSet(ctx context.Context, req BootDiskSetRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudbroker/compute/repairBootFs"
|
url := "/cloudapi/compute/bootDiskSet"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
54
pkg/cloudapi/compute/change_ip.go
Normal file
54
pkg/cloudapi/compute/change_ip.go
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeIPRequest struct to change IP for network
|
||||||
|
type ChangeIPRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Network type
|
||||||
|
// 'EXTNET' for connect to external network directly
|
||||||
|
// 'VINS' for connect to ViNS
|
||||||
|
// Required: true
|
||||||
|
NetType string `url:"net_type" json:"net_type" validate:"computeNetType"`
|
||||||
|
|
||||||
|
// Network ID for connect to
|
||||||
|
// For EXTNET - external network ID
|
||||||
|
// For VINS - VINS ID
|
||||||
|
// Required: true
|
||||||
|
NetID uint64 `url:"net_id" json:"net_id" validate:"required"`
|
||||||
|
|
||||||
|
// IP address to which we will change the existing one, it must be from the same subnet
|
||||||
|
// Required: true
|
||||||
|
IPAddr string `url:"ip_addr" json:"ip_addr" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeIP change reserved IP for compute instance
|
||||||
|
func (c Compute) ChangeIP(ctx context.Context, req ChangeIPRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/changeIp"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
46
pkg/cloudapi/compute/change_mac.go
Normal file
46
pkg/cloudapi/compute/change_mac.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeMACRequest struct to change MAC for network
|
||||||
|
type ChangeMACRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Current mac address
|
||||||
|
// Required: true
|
||||||
|
СurrentMAC string `url:"current_mac_address" json:"current_mac_address" validate:"required"`
|
||||||
|
|
||||||
|
// the MAC address to which we will change the existing one
|
||||||
|
// Required: true
|
||||||
|
NewMAC string `url:"new_mac_address" json:"new_mac_address" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeMAC change MAC for compute instance
|
||||||
|
func (c Compute) ChangeMAC(ctx context.Context, req ChangeMACRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/changeMac"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
46
pkg/cloudapi/compute/change_mtu.go
Normal file
46
pkg/cloudapi/compute/change_mtu.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeMTURequest struct to change MTU for a compute
|
||||||
|
type ChangeMTURequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Interface name or MAC address
|
||||||
|
// Required: true
|
||||||
|
Interface string `url:"interface" json:"interface" validate:"required"`
|
||||||
|
|
||||||
|
// Maximum transmission unit
|
||||||
|
// Required: true
|
||||||
|
MTU uint64 `url:"mtu" json:"mtu" validate:"required" validate:"omitempty,mtu"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeMTU change MTU for compute instance
|
||||||
|
func (c Compute) ChangeMTU(ctx context.Context, req ChangeMTURequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/change_mtu"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
50
pkg/cloudapi/compute/change_secutity_group.go
Normal file
50
pkg/cloudapi/compute/change_secutity_group.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeSecGroupsRequest struct to change security groups for compute
|
||||||
|
type ChangeSecGroupsRequest struct {
|
||||||
|
// Identifier compute
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Interface name or MAC address
|
||||||
|
// Required: true
|
||||||
|
Interface string `url:"interface" json:"interface" validate:"required"`
|
||||||
|
|
||||||
|
// List of security group IDs to assign to this interface
|
||||||
|
// Required: false
|
||||||
|
SecGroups []uint64 `url:"security_groups,omitempty" json:"security_groups,omitempty"`
|
||||||
|
|
||||||
|
// Flag indicating whether security groups are enabled for this interface
|
||||||
|
// Required: false
|
||||||
|
EnableSecGroups interface{} `url:"enable_secgroups,omitempty" json:"enable_secgroups,omitempty" validate:"omitempty,isBool"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeSecGroups changes security groups for compute
|
||||||
|
func (c Compute) ChangeSecGroups(ctx context.Context, req ChangeSecGroupsRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/change_security_groups"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -3,8 +3,8 @@ package compute
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
|
"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/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,6 +18,10 @@ type CloneRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name" validate:"required"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the Storage Policy
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
|
||||||
// Timestamp of the parent's snapshot to create clone from
|
// Timestamp of the parent's snapshot to create clone from
|
||||||
// Required: false
|
// Required: false
|
||||||
SnapshotTimestamp uint64 `url:"snapshotTimestamp,omitempty" json:"snapshotTimestamp,omitempty"`
|
SnapshotTimestamp uint64 `url:"snapshotTimestamp,omitempty" json:"snapshotTimestamp,omitempty"`
|
||||||
@@ -25,26 +29,34 @@ type CloneRequest struct {
|
|||||||
// Name of the parent's snapshot to create clone from
|
// Name of the parent's snapshot to create clone from
|
||||||
// Required: false
|
// Required: false
|
||||||
SnapshotName string `url:"snapshotName,omitempty" json:"snapshotName,omitempty"`
|
SnapshotName string `url:"snapshotName,omitempty" json:"snapshotName,omitempty"`
|
||||||
|
|
||||||
|
// true ignore that the compute is running
|
||||||
|
// Default: false
|
||||||
|
// Required: false
|
||||||
|
Force bool `url:"force" json:"force"`
|
||||||
|
|
||||||
|
// The name of the pool to migrate disks to
|
||||||
|
// Required: false
|
||||||
|
PoolName string `url:"pool_name" json:"pool_name"`
|
||||||
|
|
||||||
|
// The ID of the SEP to migrate disks to
|
||||||
|
// Required: false
|
||||||
|
SEPID uint64 `url:"sep_id" json:"sep_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clone clones compute instance
|
// Clone clones compute instance
|
||||||
func (c Compute) Clone(ctx context.Context, req CloneRequest) (uint64, error) {
|
func (c Compute) Clone(ctx context.Context, req CloneRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/clone"
|
url := "/cloudapi/compute/clone"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := strconv.ParseUint(string(res), 10, 64)
|
return string(res), nil
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
39
pkg/cloudapi/compute/clone_abort.go
Normal file
39
pkg/cloudapi/compute/clone_abort.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CloneAbortRequest struct to abort a compute clone
|
||||||
|
type CloneAbortRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloneAbort aborts a compute clone
|
||||||
|
func (c Compute) CloneAbort(ctx context.Context, req CloneAbortRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/clone_abort"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
40
pkg/cloudapi/compute/clone_status.go
Normal file
40
pkg/cloudapi/compute/clone_status.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetCloneStatusRequest struct to get information about compute clone status
|
||||||
|
type GetCloneStatusRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCloneStatus gets information about compute clone status as a RecordCloneStatus struct
|
||||||
|
func (c Compute) GetCloneStatus(ctx context.Context, req GetCloneStatusRequest) ([]RecordCloneStatus, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/clone_status"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cloneStatus := make([]RecordCloneStatus, 0)
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &cloneStatus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return cloneStatus, nil
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package compute
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
@@ -23,51 +22,19 @@ type CreateTemplateRequest struct {
|
|||||||
type wrapperCreateTemplateRequest struct {
|
type wrapperCreateTemplateRequest struct {
|
||||||
CreateTemplateRequest
|
CreateTemplateRequest
|
||||||
|
|
||||||
Async bool `url:"async"`
|
AsyncMode bool `url:"asyncMode"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateTemplate create template from compute instance
|
// CreateTemplate create template from compute instance
|
||||||
func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (uint64, error) {
|
func (c Compute) CreateTemplate(ctx context.Context, req CreateTemplateRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
|
||||||
}
|
|
||||||
|
|
||||||
reqWrapped := wrapperCreateTemplateRequest{
|
|
||||||
CreateTemplateRequest: req,
|
|
||||||
Async: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/compute/createTemplate"
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateTemplateAsync create template from compute instance
|
|
||||||
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))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
reqWrapped := wrapperCreateTemplateRequest{
|
|
||||||
CreateTemplateRequest: req,
|
|
||||||
Async: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
url := "/cloudapi/compute/createTemplate"
|
url := "/cloudapi/compute/createTemplate"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|||||||
112
pkg/cloudapi/compute/create_template_from_blank.go
Normal file
112
pkg/cloudapi/compute/create_template_from_blank.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateTemplateFromBlankRequest struct to create template from boot disk of current compute
|
||||||
|
type CreateTemplateFromBlankRequest struct {
|
||||||
|
// ID of the compute to create template from
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Name of the rescue disk
|
||||||
|
// Required: true
|
||||||
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// Boot type of image BIOS or UEFI
|
||||||
|
// Required: true
|
||||||
|
BootType string `url:"boottype" json:"boottype" validate:"imageBootType"`
|
||||||
|
|
||||||
|
// Image type linux, windows or other
|
||||||
|
// Required: true
|
||||||
|
ImageType string `url:"imagetype" json:"imagetype" validate:"imageType"`
|
||||||
|
|
||||||
|
// Storage policy id of disk. The rules of the specified storage policy will be used.
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -22,6 +22,10 @@ type DiskAddRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
Size uint64 `url:"size" json:"size" validate:"required"`
|
Size uint64 `url:"size" json:"size" validate:"required"`
|
||||||
|
|
||||||
|
// Storage policy id of disk. The rules of the specified storage policy will be used.
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
|
||||||
// Type of the disk
|
// Type of the disk
|
||||||
// Should be one of:
|
// Should be one of:
|
||||||
// - D
|
// - D
|
||||||
@@ -46,6 +50,14 @@ type DiskAddRequest struct {
|
|||||||
// Specify image id for create disk from template
|
// Specify image id for create disk from template
|
||||||
// Required: false
|
// Required: false
|
||||||
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
||||||
|
|
||||||
|
// Desired PCI slot (hex string, e.g. "0x1A")
|
||||||
|
// Required: false
|
||||||
|
PCISlot string `url:"pci_slot,omitempty" json:"pci_slot,omitempty"`
|
||||||
|
|
||||||
|
// Desired bus number (hex string, e.g. "0x03")
|
||||||
|
// Required: false
|
||||||
|
BusNumber string `url:"bus_number,omitempty" json:"bus_number,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DiskAdd creates new disk and attach to compute
|
// DiskAdd creates new disk and attach to compute
|
||||||
|
|||||||
@@ -21,6 +21,14 @@ type DiskAttachRequest struct {
|
|||||||
// Type of the disk B;D
|
// Type of the disk B;D
|
||||||
// Required: false
|
// Required: false
|
||||||
DiskType string `url:"diskType,omitempty" json:"diskType,omitempty" validate:"omitempty,computeDiskType"`
|
DiskType string `url:"diskType,omitempty" json:"diskType,omitempty" validate:"omitempty,computeDiskType"`
|
||||||
|
|
||||||
|
// Desired PCI slot (hex string, e.g. "0x1A")
|
||||||
|
// Required: false
|
||||||
|
PCISlot string `url:"pci_slot,omitempty" json:"pci_slot,omitempty"`
|
||||||
|
|
||||||
|
// Desired bus number (hex string, e.g. "0x03")
|
||||||
|
// Required: false
|
||||||
|
BusNumber string `url:"bus_number,omitempty" json:"bus_number,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DiskAttach attach disk to compute
|
// DiskAttach attach disk to compute
|
||||||
|
|||||||
53
pkg/cloudapi/compute/disk_migrate.go
Normal file
53
pkg/cloudapi/compute/disk_migrate.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiskMigrateRequest struct to migrate compute's disk to target disk
|
||||||
|
type DiskMigrateRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// ID source disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// ID target disk
|
||||||
|
// Required: true
|
||||||
|
TargetDiskID uint64 `url:"targetDiskId" json:"targetDiskId" validate:"required"`
|
||||||
|
|
||||||
|
// Migration mode. 1 - Data migration and domain update were already completed by third-party software.
|
||||||
|
// Use this if target disk already connected to compute and you only need to save changes for next reboot.
|
||||||
|
// Required: false
|
||||||
|
Mode int64 `url:"mode,omitempty" json:"mode,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiskMigrate - migrate compute's disk to target disk. Source disk will be detached, target disk will be attached to the same PCI slot.
|
||||||
|
// (WARNING) Current realisation is limited. No actual data migration will be performed.
|
||||||
|
// Use this API if target disk already connected to compute and you only need to save changes for next reboot (mode: 1).
|
||||||
|
func (c Compute) DiskMigrate(ctx context.Context, req DiskMigrateRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/diskMigrate"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
46
pkg/cloudapi/compute/disk_switch_to_replication.go
Normal file
46
pkg/cloudapi/compute/disk_switch_to_replication.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiskSwitchToReplicationRequest struct to switch disk to it's replication
|
||||||
|
type DiskSwitchToReplicationRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the disk to switch
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Delete replication relationship
|
||||||
|
// Required: false
|
||||||
|
StopReplication bool `url:"stopReplication" json:"stopReplication"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiskSwitchToReplication switches disk to it's replication
|
||||||
|
func (c Compute) DiskSwitchToReplication(ctx context.Context, req DiskSwitchToReplicationRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/diskSwitchToReplication"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -48,15 +48,13 @@ var computes = ListComputes{
|
|||||||
Devices: nil,
|
Devices: nil,
|
||||||
Disks: []InfoDisk{
|
Disks: []InfoDisk{
|
||||||
{
|
{
|
||||||
ID: 65191,
|
ID: 65191,
|
||||||
PCISlot: 6,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Driver: "KVM_X86",
|
Driver: "KVM_X86",
|
||||||
GID: 212,
|
GID: 212,
|
||||||
GUID: 48500,
|
GUID: 48500,
|
||||||
ID: 48500,
|
ID: 48500,
|
||||||
ImageID: 9884,
|
|
||||||
Interfaces: []ItemVNFInterface{},
|
Interfaces: []ItemVNFInterface{},
|
||||||
LockStatus: "UNLOCKED",
|
LockStatus: "UNLOCKED",
|
||||||
ManagerID: 0,
|
ManagerID: 0,
|
||||||
@@ -64,7 +62,7 @@ var computes = ListComputes{
|
|||||||
MigrationJob: 0,
|
MigrationJob: 0,
|
||||||
Milestones: 363500,
|
Milestones: 363500,
|
||||||
Name: "test",
|
Name: "test",
|
||||||
Pinned: false,
|
PinnedToStack: true,
|
||||||
RAM: 4096,
|
RAM: 4096,
|
||||||
ReferenceID: "c7cb19ac-af4a-4067-852f-c5572949207e",
|
ReferenceID: "c7cb19ac-af4a-4067-852f-c5572949207e",
|
||||||
Registered: true,
|
Registered: true,
|
||||||
@@ -83,7 +81,7 @@ var computes = ListComputes{
|
|||||||
UserManaged: true,
|
UserManaged: true,
|
||||||
VGPUs: []uint64{},
|
VGPUs: []uint64{},
|
||||||
VINSConnected: 0,
|
VINSConnected: 0,
|
||||||
VirtualImageID: 0,
|
ZoneID: 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ACL: ListACL{},
|
ACL: ListACL{},
|
||||||
@@ -111,15 +109,13 @@ var computes = ListComputes{
|
|||||||
Devices: nil,
|
Devices: nil,
|
||||||
Disks: []InfoDisk{
|
Disks: []InfoDisk{
|
||||||
{
|
{
|
||||||
ID: 65248,
|
ID: 65248,
|
||||||
PCISlot: 6,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Driver: "KVM_X86",
|
Driver: "KVM_X86",
|
||||||
GID: 212,
|
GID: 212,
|
||||||
GUID: 48556,
|
GUID: 48556,
|
||||||
ID: 48556,
|
ID: 48556,
|
||||||
ImageID: 9884,
|
|
||||||
Interfaces: []ItemVNFInterface{},
|
Interfaces: []ItemVNFInterface{},
|
||||||
LockStatus: "UNLOCKED",
|
LockStatus: "UNLOCKED",
|
||||||
ManagerID: 0,
|
ManagerID: 0,
|
||||||
@@ -127,10 +123,10 @@ var computes = ListComputes{
|
|||||||
MigrationJob: 0,
|
MigrationJob: 0,
|
||||||
Milestones: 363853,
|
Milestones: 363853,
|
||||||
Name: "compute_2",
|
Name: "compute_2",
|
||||||
Pinned: false,
|
|
||||||
RAM: 4096,
|
RAM: 4096,
|
||||||
ReferenceID: "a542c449-5b1c-4f90-88c5-7bb5f8ae68ff",
|
ReferenceID: "a542c449-5b1c-4f90-88c5-7bb5f8ae68ff",
|
||||||
Registered: true,
|
Registered: true,
|
||||||
|
PinnedToStack: true,
|
||||||
ResName: "compute-48556",
|
ResName: "compute-48556",
|
||||||
RGID: 79727,
|
RGID: 79727,
|
||||||
RGName: "sdk_negative_fields_test",
|
RGName: "sdk_negative_fields_test",
|
||||||
@@ -146,7 +142,7 @@ var computes = ListComputes{
|
|||||||
UserManaged: true,
|
UserManaged: true,
|
||||||
VGPUs: []uint64{},
|
VGPUs: []uint64{},
|
||||||
VINSConnected: 0,
|
VINSConnected: 0,
|
||||||
VirtualImageID: 0,
|
ZoneID: 5,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
EntryCount: 2,
|
EntryCount: 2,
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ func (c Compute) GetLog(ctx context.Context, req GetLogRequest) (string, error)
|
|||||||
|
|
||||||
url := "/cloudapi/compute/getLog"
|
url := "/cloudapi/compute/getLog"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -42,7 +42,7 @@ func (c Compute) GetLogGet(ctx context.Context, req GetLogRequest) (string, erro
|
|||||||
return "", validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi//compute/getLog"
|
url := "/cloudapi/compute/getLog"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
38
pkg/cloudapi/compute/guest_agent_disable.go
Normal file
38
pkg/cloudapi/compute/guest_agent_disable.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestAgentDisableRequest struct to disable guest agent
|
||||||
|
type GuestAgentDisableRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disable guest agent at a specific compute
|
||||||
|
func (c Compute) GuestAgentDisable(ctx context.Context, req GuestAgentDisableRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/guest_agent_disable"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
38
pkg/cloudapi/compute/guest_agent_enable.go
Normal file
38
pkg/cloudapi/compute/guest_agent_enable.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestAgentEnableRequest struct to enable guest agent
|
||||||
|
type GuestAgentEnableRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enable guest agent at a specific compute
|
||||||
|
func (c Compute) GuestAgentEnable(ctx context.Context, req GuestAgentEnableRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/guest_agent_enable"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
48
pkg/cloudapi/compute/guest_agent_execute.go
Normal file
48
pkg/cloudapi/compute/guest_agent_execute.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestAgentExecuteRequest struct to execute command from user to agent
|
||||||
|
type GuestAgentExecuteRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
|
||||||
|
// Custom command from user to agent
|
||||||
|
// Required: true
|
||||||
|
Command string `url:"command" json:"command" validate:"required"`
|
||||||
|
|
||||||
|
// Arguments to command
|
||||||
|
// Required: true
|
||||||
|
Arguments string `url:"arguments" json:"arguments" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute guest agent command
|
||||||
|
func (c Compute) GuestAgentExecuteRequest(ctx context.Context, req GuestAgentExecuteRequest) (map[string]interface{}, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/guest_agent_execute"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result map[string]interface{}
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &result)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
40
pkg/cloudapi/compute/guest_agent_feature_get.go
Normal file
40
pkg/cloudapi/compute/guest_agent_feature_get.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestAgentFeatureGetRequest struct to feature get guest agent
|
||||||
|
type GuestAgentFeatureGetRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List of features
|
||||||
|
func (c Compute) GuestAgentFeatureGet(ctx context.Context, req GuestAgentFeatureGetRequest) ([]string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/guest_agent_feature_get"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
features := make([]string, 0)
|
||||||
|
|
||||||
|
err = json.Unmarshal(res, &features)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return features, nil
|
||||||
|
}
|
||||||
38
pkg/cloudapi/compute/guest_agent_feature_update.go
Normal file
38
pkg/cloudapi/compute/guest_agent_feature_update.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestAgentFeatureUpdateRequest struct to feature update guest agent
|
||||||
|
type GuestAgentFeatureUpdateRequest struct {
|
||||||
|
// ID of compute instance
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feature update guest agent
|
||||||
|
func (c Compute) GuestAgentFeatureUpdate(ctx context.Context, req GuestAgentFeatureUpdateRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/guest_agent_feature_update"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListRequest struct to get list of available computes
|
// ListRequest struct to get list of available computes
|
||||||
@@ -52,6 +54,15 @@ type ListRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
IncludeDeleted bool `url:"includedeleted,omitempty" json:"includedeleted,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
|
// Sort by zone id
|
||||||
|
// Default value: 0
|
||||||
|
// Required: false
|
||||||
|
ZoneID uint64 `url:"zone_id,omitempty" json:"zone_id,omitempty"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -64,6 +75,7 @@ type ListRequest struct {
|
|||||||
// List gets list of the available computes.
|
// List gets list of the available computes.
|
||||||
// Filtering based on status is possible
|
// Filtering based on status is possible
|
||||||
func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, error) {
|
func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
res, err := c.ListRaw(ctx, req)
|
res, err := c.ListRaw(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -81,6 +93,11 @@ func (c Compute) List(ctx context.Context, req ListRequest) (*ListComputes, erro
|
|||||||
|
|
||||||
// ListRaw gets list of the available computes.
|
// ListRaw gets list of the available computes.
|
||||||
func (c Compute) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
func (c Compute) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/list"
|
url := "/cloudapi/compute/list"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListDeletedRequest struct to get deleted computes list
|
// ListDeletedRequest struct to get deleted computes list
|
||||||
@@ -44,6 +46,10 @@ type ListDeletedRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
ExtNetID uint64 `url:"extNetId,omitempty" json:"extNetId,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -55,6 +61,11 @@ type ListDeletedRequest struct {
|
|||||||
|
|
||||||
// ListDeleted gets list all deleted computes
|
// ListDeleted gets list all deleted computes
|
||||||
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListComputes, error) {
|
func (c Compute) ListDeleted(ctx context.Context, req ListDeletedRequest) (*ListComputes, error) {
|
||||||
|
|
||||||
|
if err := validators.ValidateRequest(req); err != nil {
|
||||||
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/listDeleted"
|
url := "/cloudapi/compute/listDeleted"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type ListPCIDeviceRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListPCIDeviceRequest struct {
|
|||||||
|
|
||||||
// ListPCIDevice gets list PCI device
|
// ListPCIDevice gets list PCI device
|
||||||
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) (*ListPCIDevices, error) {
|
func (c Compute) ListPCIDevice(ctx context.Context, req ListPCIDeviceRequest) (*ListPCIDevices, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ type ListVGPURequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Status string `url:"status,omitempty" json:"status,omitempty"`
|
Status string `url:"status,omitempty" json:"status,omitempty"`
|
||||||
|
|
||||||
|
// Sort by one of supported fields, format +|-(field)
|
||||||
|
// Required: false
|
||||||
|
SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`
|
||||||
|
|
||||||
// Page number
|
// Page number
|
||||||
// Required: false
|
// Required: false
|
||||||
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
Page uint64 `url:"page,omitempty" json:"page,omitempty"`
|
||||||
@@ -41,6 +45,7 @@ type ListVGPURequest struct {
|
|||||||
|
|
||||||
// ListVGPU gets list vGPU
|
// ListVGPU gets list vGPU
|
||||||
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) (*ListVGPUs, error) {
|
func (c Compute) ListVGPU(ctx context.Context, req ListVGPURequest) (*ListVGPUs, error) {
|
||||||
|
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
return nil, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
|||||||
@@ -8,25 +8,25 @@ import (
|
|||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RegistrationRequest struct to set compute registered in RT
|
// MigrateToRGZone struct to move compute to another zone
|
||||||
type RegistrationRequest struct {
|
type MigrateToZoneRequest struct {
|
||||||
// ID of the Compute
|
// ID of the compute instance to move
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
// Unique compute registration key
|
// ID of the zone to move
|
||||||
// Required: true
|
// Required: true
|
||||||
RegistrationKey string `url:"registrationKey" json:"registrationKey" validate:"required"`
|
ZoneID uint64 `url:"zoneId" json:"zoneId " validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Registration sets compute registered in RT
|
// MoveToRG moves compute instance to new resource group
|
||||||
func (c Compute) Registration(ctx context.Context, req RegistrationRequest) (bool, error) {
|
func (c Compute) MigrateToZone(ctx context.Context, req MigrateToZoneRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudbroker/compute/registration"
|
url := "/cloudapi/compute/migrateToZone"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -5,13 +5,13 @@ import "strconv"
|
|||||||
// Access Control List
|
// Access Control List
|
||||||
type RecordACL struct {
|
type RecordACL struct {
|
||||||
// Account ACL list
|
// Account ACL list
|
||||||
AccountACL ListACL `json:"accountAcl"`
|
AccountACL ListACL `json:"accountACL"`
|
||||||
|
|
||||||
// Compute ACL list
|
// Compute ACL list
|
||||||
ComputeACL ListACL `json:"computeAcl"`
|
ComputeACL ListACL `json:"computeACL"`
|
||||||
|
|
||||||
// Resource group ACL list
|
// Resource group ACL list
|
||||||
RGACL ListACL `json:"rgAcl"`
|
RGACL ListACL `json:"rgACL"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ListUsers struct {
|
type ListUsers struct {
|
||||||
@@ -214,6 +214,9 @@ type RecordNetAttach struct {
|
|||||||
|
|
||||||
// List VNF IDs
|
// List VNF IDs
|
||||||
VNFs []uint64 `json:"vnfs"`
|
VNFs []uint64 `json:"vnfs"`
|
||||||
|
|
||||||
|
// Maximum transmission unit
|
||||||
|
MTU uint64 `json:"mtu"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Detailed information about audit
|
// Detailed information about audit
|
||||||
@@ -235,7 +238,13 @@ type ItemAudit struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List Detailed audits
|
// List Detailed audits
|
||||||
type ListAudits []ItemAudit
|
type ListAudits struct {
|
||||||
|
// Data
|
||||||
|
Data []ItemAudit `json:"data"`
|
||||||
|
|
||||||
|
// Entry count
|
||||||
|
EntryCount uint64 `json:"entryCount"`
|
||||||
|
}
|
||||||
|
|
||||||
// Short information about audit
|
// Short information about audit
|
||||||
type ItemShortAudit struct {
|
type ItemShortAudit struct {
|
||||||
@@ -296,15 +305,30 @@ type RecordCompute struct {
|
|||||||
// List anti affinity rules
|
// List anti affinity rules
|
||||||
AntiAffinityRules ListRules `json:"antiAffinityRules"`
|
AntiAffinityRules ListRules `json:"antiAffinityRules"`
|
||||||
|
|
||||||
|
// Auto start when node restarted
|
||||||
|
AutoStart bool `json:"autoStart"`
|
||||||
|
|
||||||
// Architecture
|
// Architecture
|
||||||
Architecture string `json:"arch"`
|
Architecture string `json:"arch"`
|
||||||
|
|
||||||
|
// Boot image ID
|
||||||
|
BootImageID uint64 `json:"boot_image_id"`
|
||||||
|
|
||||||
// Boot order
|
// Boot order
|
||||||
BootOrder []string `json:"bootOrder"`
|
BootOrder []string `json:"bootOrder"`
|
||||||
|
|
||||||
|
// Boot type
|
||||||
|
BootType string `json:"bootType"`
|
||||||
|
|
||||||
// Boot disk size
|
// Boot disk size
|
||||||
BootDiskSize uint64 `json:"bootdiskSize"`
|
BootDiskSize uint64 `json:"bootdiskSize"`
|
||||||
|
|
||||||
|
// CD Image Id
|
||||||
|
CdImageId uint64 `json:"cdImageId"`
|
||||||
|
|
||||||
|
// Chipset
|
||||||
|
Chipset string `json:"chipset"`
|
||||||
|
|
||||||
// Clone reference
|
// Clone reference
|
||||||
CloneReference uint64 `json:"cloneReference"`
|
CloneReference uint64 `json:"cloneReference"`
|
||||||
|
|
||||||
@@ -314,6 +338,9 @@ type RecordCompute struct {
|
|||||||
// Compute CI ID
|
// Compute CI ID
|
||||||
ComputeCIID uint64 `json:"computeciId"`
|
ComputeCIID uint64 `json:"computeciId"`
|
||||||
|
|
||||||
|
// CPU Pin
|
||||||
|
CPUPin bool `json:"cpupin"`
|
||||||
|
|
||||||
// Number of cores
|
// Number of cores
|
||||||
CPU uint64 `json:"cpus"`
|
CPU uint64 `json:"cpus"`
|
||||||
|
|
||||||
@@ -350,6 +377,12 @@ type RecordCompute struct {
|
|||||||
// GUID
|
// GUID
|
||||||
GUID uint64 `json:"guid"`
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HPBacked
|
||||||
|
HPBacked bool `json:"hpBacked"`
|
||||||
|
|
||||||
|
// Hot resize
|
||||||
|
HotResize bool `json:"hotResize"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
@@ -362,6 +395,15 @@ type RecordCompute struct {
|
|||||||
// List interfaces
|
// List interfaces
|
||||||
Interfaces ListInterfaces `json:"interfaces"`
|
Interfaces ListInterfaces `json:"interfaces"`
|
||||||
|
|
||||||
|
// Loader meta iso information
|
||||||
|
LoaderMetaIso LoaderMetaIso `json:"loaderMetaIso"`
|
||||||
|
|
||||||
|
// Live migration job ID
|
||||||
|
LiveMigrationJobID uint64 `json:"live_migration_job_id"`
|
||||||
|
|
||||||
|
// Loader type
|
||||||
|
LoaderType string `json:"loaderType"`
|
||||||
|
|
||||||
// Lock status
|
// Lock status
|
||||||
LockStatus string `json:"lockStatus"`
|
LockStatus string `json:"lockStatus"`
|
||||||
|
|
||||||
@@ -380,6 +422,18 @@ type RecordCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// NeedReboot
|
||||||
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
|
// Network interface naming
|
||||||
|
NetworkInterfaceNaming string `json:"networkInterfaceNaming"`
|
||||||
|
|
||||||
|
// Numa Affinity
|
||||||
|
NumaAffinity string `json:"numaAffinity"`
|
||||||
|
|
||||||
|
//NumaNodeId
|
||||||
|
NumaNodeId int64 `json:"numaNodeId"`
|
||||||
|
|
||||||
// Natable VINS ID
|
// Natable VINS ID
|
||||||
NatableVINSID uint64 `json:"natableVinsId"`
|
NatableVINSID uint64 `json:"natableVinsId"`
|
||||||
|
|
||||||
@@ -395,11 +449,20 @@ type RecordCompute struct {
|
|||||||
// Natable VINS network name
|
// Natable VINS network name
|
||||||
NatableVINSNetworkName string `json:"natableVinsNetworkName"`
|
NatableVINSNetworkName string `json:"natableVinsNetworkName"`
|
||||||
|
|
||||||
|
// Name of OS
|
||||||
|
OSVersion string `json:"os_version"`
|
||||||
|
|
||||||
// List OS Users
|
// List OS Users
|
||||||
OSUsers ListOSUser `json:"osUsers"`
|
OSUsers ListOSUser `json:"osUsers"`
|
||||||
|
|
||||||
// Pinned or not
|
// Pinned to stack
|
||||||
Pinned bool `json:"pinned"`
|
PinnedToStack bool `json:"pinnedToStack"`
|
||||||
|
|
||||||
|
// PreferredCPU
|
||||||
|
PreferredCPU []int64 `json:"preferredCpu"`
|
||||||
|
|
||||||
|
// Qemu_quest
|
||||||
|
QemuQuest QemuQuest `json:"qemu_guest"`
|
||||||
|
|
||||||
// Number of RAM
|
// Number of RAM
|
||||||
RAM uint64 `json:"ram"`
|
RAM uint64 `json:"ram"`
|
||||||
@@ -413,6 +476,9 @@ type RecordCompute struct {
|
|||||||
// Resource name
|
// Resource name
|
||||||
ResName string `json:"resName"`
|
ResName string `json:"resName"`
|
||||||
|
|
||||||
|
// Reserved Node Cpus
|
||||||
|
ReservedNodeCpus []uint64 `json:"reservedNodeCpus"`
|
||||||
|
|
||||||
// Resource group ID
|
// Resource group ID
|
||||||
RGID uint64 `json:"rgId"`
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
@@ -449,14 +515,113 @@ type RecordCompute struct {
|
|||||||
// Userdata
|
// Userdata
|
||||||
Userdata interface{} `json:"userdata"`
|
Userdata interface{} `json:"userdata"`
|
||||||
|
|
||||||
// vGPU IDs
|
// vGPUs list
|
||||||
VGPUs []uint64 `json:"vgpus"`
|
VGPUs []VGPUItem `json:"vgpus"`
|
||||||
|
|
||||||
// Virtual image ID
|
// VNC password
|
||||||
VirtualImageID uint64 `json:"virtualImageId"`
|
VNCPassword string `json:"vncPasswd"`
|
||||||
|
|
||||||
// Virtual image name
|
// Zone ID
|
||||||
VirtualImageName string `json:"virtualImageName"`
|
// Required: false
|
||||||
|
ZoneID uint64 `json:"zoneId"`
|
||||||
|
}
|
||||||
|
type LoaderMetaIso struct {
|
||||||
|
// Name
|
||||||
|
DeviceName string `json:"devicename"`
|
||||||
|
|
||||||
|
// Path
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type QemuQuest struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
EnabledAgentFeatures []string `json:"enabled_agent_features"`
|
||||||
|
GUID string `json:"guid"`
|
||||||
|
LastUpdate uint64 `json:"last_update"`
|
||||||
|
User string `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type VGPUItem struct {
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// GID
|
||||||
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
|
// Type
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// Mode
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// ProfileID
|
||||||
|
ProfileID uint64 `json:"profileId"`
|
||||||
|
|
||||||
|
// RAM
|
||||||
|
RAM uint64 `json:"ram"`
|
||||||
|
|
||||||
|
// LastUpdateTime
|
||||||
|
LastUpdateTime uint64 `json:"lastUpdateTime"`
|
||||||
|
|
||||||
|
// CreatedTime
|
||||||
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// DeletedTime
|
||||||
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// VMID
|
||||||
|
VMID uint64 `json:"vmid"`
|
||||||
|
|
||||||
|
// PGPuid
|
||||||
|
PGPuid uint64 `json:"pgpuid"`
|
||||||
|
|
||||||
|
// ReferenceID
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
|
// AccountID
|
||||||
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
|
// RgID
|
||||||
|
RgID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// LastClaimedBy
|
||||||
|
LastClaimedBy uint64 `json:"lastClaimedBy"`
|
||||||
|
|
||||||
|
// PCISlot
|
||||||
|
PCISlot uint64 `json:"pciSlot"`
|
||||||
|
|
||||||
|
// BusNumber
|
||||||
|
BusNumber uint64 `json:"bus_number"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Information about libvirt settings
|
||||||
|
type LibvirtSettings struct {
|
||||||
|
// TX mode
|
||||||
|
TXMode string `json:"txmode"`
|
||||||
|
|
||||||
|
// IO event
|
||||||
|
IOEventFD string `json:"ioeventfd"`
|
||||||
|
|
||||||
|
// Event ID
|
||||||
|
EventIDx string `json:"event_idx"`
|
||||||
|
|
||||||
|
// Number of queues
|
||||||
|
Queues uint64 `json:"queues"`
|
||||||
|
|
||||||
|
// RX queue size
|
||||||
|
RXQueueSize uint64 `json:"rx_queue_size"`
|
||||||
|
|
||||||
|
// TX queue size
|
||||||
|
TXQueueSize uint64 `json:"tx_queue_size"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID string `json:"guid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main information about OS user
|
// Main information about OS user
|
||||||
@@ -497,6 +662,9 @@ type ListSnapSets []ItemSnapSet
|
|||||||
|
|
||||||
// Main information about VNF
|
// Main information about VNF
|
||||||
type ItemVNFInterface struct {
|
type ItemVNFInterface struct {
|
||||||
|
// Bus number
|
||||||
|
BusNumber uint64 `json:"bus_number"`
|
||||||
|
|
||||||
// Connection ID
|
// Connection ID
|
||||||
ConnID uint64 `json:"connId"`
|
ConnID uint64 `json:"connId"`
|
||||||
|
|
||||||
@@ -509,6 +677,9 @@ type ItemVNFInterface struct {
|
|||||||
// Enabled
|
// Enabled
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
|
|
||||||
|
// Enable security groups
|
||||||
|
EnableSecGroups bool `json:"enable_secgroups"`
|
||||||
|
|
||||||
// FLIPGroup ID
|
// FLIPGroup ID
|
||||||
FLIPGroupID uint64 `json:"flipgroupId"`
|
FLIPGroupID uint64 `json:"flipgroupId"`
|
||||||
|
|
||||||
@@ -521,9 +692,15 @@ type ItemVNFInterface struct {
|
|||||||
// Listen SSH or not
|
// Listen SSH or not
|
||||||
ListenSSH bool `json:"listenSsh"`
|
ListenSSH bool `json:"listenSsh"`
|
||||||
|
|
||||||
|
// Libvirt Settings
|
||||||
|
LibvirtSettings LibvirtSettings `json:"libvirtSettings"`
|
||||||
|
|
||||||
// MAC
|
// MAC
|
||||||
MAC string `json:"mac"`
|
MAC string `json:"mac"`
|
||||||
|
|
||||||
|
// Maximum transmission unit
|
||||||
|
MTU uint64 `json:"mtu"`
|
||||||
|
|
||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
@@ -536,15 +713,27 @@ type ItemVNFInterface struct {
|
|||||||
// Network type
|
// Network type
|
||||||
NetType string `json:"netType"`
|
NetType string `json:"netType"`
|
||||||
|
|
||||||
|
// NodeID
|
||||||
|
NodeID int64 `json:"nodeId"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot int64 `json:"pciSlot"`
|
PCISlot int64 `json:"pciSlot"`
|
||||||
|
|
||||||
// QOS
|
// QOS
|
||||||
QOS QOS `json:"qos"`
|
QOS QOS `json:"qos"`
|
||||||
|
|
||||||
|
// List of security groups
|
||||||
|
SecGroups []uint64 `json:"security_groups"`
|
||||||
|
|
||||||
|
// SDN interface ID
|
||||||
|
SDNInterfaceID string `json:"sdn_interface_id"`
|
||||||
|
|
||||||
// Target
|
// Target
|
||||||
Target string `json:"target"`
|
Target string `json:"target"`
|
||||||
|
|
||||||
|
// Trunk tags
|
||||||
|
TrunkTags string `json:"trunk_tags"`
|
||||||
|
|
||||||
// Type
|
// Type
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
|
||||||
@@ -579,9 +768,21 @@ type ItemComputeDisk struct {
|
|||||||
// Boot partition
|
// Boot partition
|
||||||
BootPartition uint64 `json:"bootPartition"`
|
BootPartition uint64 `json:"bootPartition"`
|
||||||
|
|
||||||
|
// Bus number
|
||||||
|
BusNumber uint64 `json:"bus_number"`
|
||||||
|
|
||||||
|
// Created by
|
||||||
|
CreatedBy string `json:"createdBy"`
|
||||||
|
|
||||||
// Created time
|
// Created time
|
||||||
CreatedTime uint64 `json:"createdTime"`
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// Device name
|
||||||
|
DeviceName string `json:"devicename"`
|
||||||
|
|
||||||
|
// Deleted by
|
||||||
|
DeletedBy string `json:"deletedBy"`
|
||||||
|
|
||||||
// Deleted time
|
// Deleted time
|
||||||
DeletedTime uint64 `json:"deletedTime"`
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
@@ -624,9 +825,6 @@ type ItemComputeDisk struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
// Order
|
|
||||||
Order uint64 `json:"order"`
|
|
||||||
|
|
||||||
// Params
|
// Params
|
||||||
Params string `json:"params"`
|
Params string `json:"params"`
|
||||||
|
|
||||||
@@ -637,13 +835,13 @@ type ItemComputeDisk struct {
|
|||||||
Passwd string `json:"passwd"`
|
Passwd string `json:"passwd"`
|
||||||
|
|
||||||
// PCI slot
|
// PCI slot
|
||||||
PCISlot int64 `json:"pciSlot"`
|
PCISlot int64 `json:"pci_slot"`
|
||||||
|
|
||||||
// Pool
|
// Pool
|
||||||
Pool string `json:"pool"`
|
Pool string `json:"pool"`
|
||||||
|
|
||||||
// Present to
|
// Present to
|
||||||
PresentTo []uint64 `json:"presentTo"`
|
PresentTo map[string]uint64 `json:"presentTo"`
|
||||||
|
|
||||||
// Purge time
|
// Purge time
|
||||||
PurgeTime uint64 `json:"purgeTime"`
|
PurgeTime uint64 `json:"purgeTime"`
|
||||||
@@ -651,6 +849,9 @@ type ItemComputeDisk struct {
|
|||||||
// Reality device number
|
// Reality device number
|
||||||
RealityDeviceNumber uint64 `json:"realityDeviceNumber"`
|
RealityDeviceNumber uint64 `json:"realityDeviceNumber"`
|
||||||
|
|
||||||
|
// Replication
|
||||||
|
Replication ItemReplication `json:"replication"`
|
||||||
|
|
||||||
// Resource ID
|
// Resource ID
|
||||||
ResID string `json:"resId"`
|
ResID string `json:"resId"`
|
||||||
|
|
||||||
@@ -663,6 +864,9 @@ type ItemComputeDisk struct {
|
|||||||
// Shareable
|
// Shareable
|
||||||
Shareable bool `json:"shareable"`
|
Shareable bool `json:"shareable"`
|
||||||
|
|
||||||
|
// Size available
|
||||||
|
SizeAvailable float64 `json:"sizeAvailable"`
|
||||||
|
|
||||||
// Size max
|
// Size max
|
||||||
SizeMax uint64 `json:"sizeMax"`
|
SizeMax uint64 `json:"sizeMax"`
|
||||||
|
|
||||||
@@ -675,14 +879,43 @@ type ItemComputeDisk struct {
|
|||||||
// Status
|
// Status
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Storage policy id of compute.
|
||||||
|
StoragePolicyID uint64 `json:"storage_policy_id"`
|
||||||
|
|
||||||
// Tech status
|
// Tech status
|
||||||
TechStatus string `json:"techStatus"`
|
TechStatus string `json:"techStatus"`
|
||||||
|
|
||||||
|
// Need to clean before destroy
|
||||||
|
ToClean bool `json:"to_clean"`
|
||||||
|
|
||||||
// Type
|
// Type
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
|
||||||
// Virtual machine ID
|
// Updated by
|
||||||
VMID uint64 `json:"vmid"`
|
UpdatedBy string `json:"updatedBy"`
|
||||||
|
|
||||||
|
// UpdatedTime
|
||||||
|
UpdatedTime uint64 `json:"updatedTime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ItemReplication struct {
|
||||||
|
// DiskID
|
||||||
|
DiskID uint64 `json:"diskId"`
|
||||||
|
|
||||||
|
// PoolID
|
||||||
|
PoolID string `json:"poolId"`
|
||||||
|
|
||||||
|
// Role
|
||||||
|
Role string `json:"role"`
|
||||||
|
|
||||||
|
// SelfVolumeID
|
||||||
|
SelfVolumeID string `json:"selfVolumeId"`
|
||||||
|
|
||||||
|
// StorageID
|
||||||
|
StorageID string `json:"storageId"`
|
||||||
|
|
||||||
|
// VolumeID
|
||||||
|
VolumeID string `json:"volumeId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main information about snapshot extend
|
// Main information about snapshot extend
|
||||||
@@ -758,6 +991,7 @@ type IOTune struct {
|
|||||||
type ItemCompute struct {
|
type ItemCompute struct {
|
||||||
// Access Control List
|
// Access Control List
|
||||||
ACL ListACL `json:"acl"`
|
ACL ListACL `json:"acl"`
|
||||||
|
|
||||||
// Account ID
|
// Account ID
|
||||||
AccountID uint64 `json:"accountId"`
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
@@ -776,15 +1010,30 @@ type ItemCompute struct {
|
|||||||
// List anti affinity rules
|
// List anti affinity rules
|
||||||
AntiAffinityRules ListRules `json:"antiAffinityRules"`
|
AntiAffinityRules ListRules `json:"antiAffinityRules"`
|
||||||
|
|
||||||
|
// Auto start when node restarted
|
||||||
|
AutoStart bool `json:"autoStart"`
|
||||||
|
|
||||||
// Architecture
|
// Architecture
|
||||||
Architecture string `json:"arch"`
|
Architecture string `json:"arch"`
|
||||||
|
|
||||||
|
// Boot image ID
|
||||||
|
BootImageID uint64 `json:"boot_image_id"`
|
||||||
|
|
||||||
// Boot order
|
// Boot order
|
||||||
BootOrder []string `json:"bootOrder"`
|
BootOrder []string `json:"bootOrder"`
|
||||||
|
|
||||||
|
// Boot type
|
||||||
|
BootType string `json:"bootType"`
|
||||||
|
|
||||||
// Boot disk size
|
// Boot disk size
|
||||||
BootDiskSize uint64 `json:"bootdiskSize"`
|
BootDiskSize uint64 `json:"bootdiskSize"`
|
||||||
|
|
||||||
|
// CD Image Id
|
||||||
|
CdImageId uint64 `json:"cdImageId"`
|
||||||
|
|
||||||
|
// Chipset
|
||||||
|
Chipset string `json:"chipset"`
|
||||||
|
|
||||||
// Clone reference
|
// Clone reference
|
||||||
CloneReference uint64 `json:"cloneReference"`
|
CloneReference uint64 `json:"cloneReference"`
|
||||||
|
|
||||||
@@ -794,6 +1043,9 @@ type ItemCompute struct {
|
|||||||
// Compute CI ID
|
// Compute CI ID
|
||||||
ComputeCIID uint64 `json:"computeciId"`
|
ComputeCIID uint64 `json:"computeciId"`
|
||||||
|
|
||||||
|
// CPU Pin
|
||||||
|
CPUPin bool `json:"cpupin"`
|
||||||
|
|
||||||
// Number of cores
|
// Number of cores
|
||||||
CPU uint64 `json:"cpus"`
|
CPU uint64 `json:"cpus"`
|
||||||
|
|
||||||
@@ -830,15 +1082,24 @@ type ItemCompute struct {
|
|||||||
// GUID
|
// GUID
|
||||||
GUID uint64 `json:"guid"`
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// Hot resize
|
||||||
|
HotResize bool `json:"hotResize"`
|
||||||
|
|
||||||
|
// HPBacked
|
||||||
|
HPBacked bool `json:"hpBacked"`
|
||||||
|
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
// Image ID
|
|
||||||
ImageID uint64 `json:"imageId"`
|
|
||||||
|
|
||||||
// List interfaces
|
// List interfaces
|
||||||
Interfaces ListInterfaces `json:"interfaces"`
|
Interfaces ListInterfaces `json:"interfaces"`
|
||||||
|
|
||||||
|
// Live migration job ID
|
||||||
|
LiveMigrationJobID uint64 `json:"live_migration_job_id"`
|
||||||
|
|
||||||
|
// Loader type
|
||||||
|
LoaderType string `json:"loaderType"`
|
||||||
|
|
||||||
// Lock status
|
// Lock status
|
||||||
LockStatus string `json:"lockStatus"`
|
LockStatus string `json:"lockStatus"`
|
||||||
|
|
||||||
@@ -857,12 +1118,33 @@ type ItemCompute struct {
|
|||||||
// Name
|
// Name
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
|
||||||
// Pinned or not
|
// NeedReboot
|
||||||
Pinned bool `json:"pinned"`
|
NeedReboot bool `json:"needReboot"`
|
||||||
|
|
||||||
|
// network interface naming
|
||||||
|
NetworkInterfaceNaming string `json:"networkInterfaceNaming"`
|
||||||
|
|
||||||
|
// Numa Affinity
|
||||||
|
NumaAffinity string `json:"numaAffinity"`
|
||||||
|
|
||||||
|
//NumaNodeId
|
||||||
|
NumaNodeId int64 `json:"numaNodeId"`
|
||||||
|
|
||||||
|
// Pinned to stack
|
||||||
|
PinnedToStack bool `json:"pinnedToStack"`
|
||||||
|
|
||||||
|
// PreferredCPU
|
||||||
|
PreferredCPU []int64 `json:"preferredCpu"`
|
||||||
|
|
||||||
// Number of RAM
|
// Number of RAM
|
||||||
RAM uint64 `json:"ram"`
|
RAM uint64 `json:"ram"`
|
||||||
|
|
||||||
|
// Name of OS
|
||||||
|
OSVersion string `json:"os_version"`
|
||||||
|
|
||||||
|
// Qemu_quest
|
||||||
|
QemuQuest QemuQuest `json:"qemu_guest"`
|
||||||
|
|
||||||
// Reference ID
|
// Reference ID
|
||||||
ReferenceID string `json:"referenceId"`
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
@@ -872,6 +1154,9 @@ type ItemCompute struct {
|
|||||||
// Resource name
|
// Resource name
|
||||||
ResName string `json:"resName"`
|
ResName string `json:"resName"`
|
||||||
|
|
||||||
|
// Reserved Node Cpus
|
||||||
|
ReservedNodeCpus []uint64 `json:"reservedNodeCpus"`
|
||||||
|
|
||||||
// Resource group ID
|
// Resource group ID
|
||||||
RGID uint64 `json:"rgId"`
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
@@ -914,8 +1199,8 @@ type ItemCompute struct {
|
|||||||
// VINS connected
|
// VINS connected
|
||||||
VINSConnected uint64 `json:"vinsConnected"`
|
VINSConnected uint64 `json:"vinsConnected"`
|
||||||
|
|
||||||
// Virtual image ID
|
// Zone ID
|
||||||
VirtualImageID uint64 `json:"virtualImageId"`
|
ZoneID uint64 `json:"zoneId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListInfoDisks
|
// ListInfoDisks
|
||||||
@@ -925,9 +1210,6 @@ type ListInfoDisks []InfoDisk
|
|||||||
type InfoDisk struct {
|
type InfoDisk struct {
|
||||||
// ID
|
// ID
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
// PCISlot
|
|
||||||
PCISlot int64 `json:"pciSlot"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// List information about computes
|
// List information about computes
|
||||||
@@ -942,17 +1224,135 @@ type ListComputes struct {
|
|||||||
// List VGPUs
|
// List VGPUs
|
||||||
type ListVGPUs struct {
|
type ListVGPUs struct {
|
||||||
// Data
|
// Data
|
||||||
Data []interface{} `json:"data"`
|
Data []ItemVGPU `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Main information about vgpu device
|
||||||
|
type ItemVGPU struct {
|
||||||
|
// Account ID
|
||||||
|
AccountID uint64 `json:"accountId"`
|
||||||
|
|
||||||
|
// Created Time
|
||||||
|
CreatedTime uint64 `json:"createdTime"`
|
||||||
|
|
||||||
|
// Deleted Time
|
||||||
|
DeletedTime uint64 `json:"deletedTime"`
|
||||||
|
|
||||||
|
// GID
|
||||||
|
GID uint64 `json:"gid"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Last Claimed By
|
||||||
|
LastClaimedBy uint64 `json:"lastClaimedBy"`
|
||||||
|
|
||||||
|
// Last Update Time
|
||||||
|
LastUpdateTime uint64 `json:"lastUpdateTime"`
|
||||||
|
|
||||||
|
// Mode
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
|
||||||
|
// PCI Slot
|
||||||
|
PCISlot uint64 `json:"pciSlot"`
|
||||||
|
|
||||||
|
// PGPUID
|
||||||
|
PGPUID uint64 `json:"pgpuid"`
|
||||||
|
|
||||||
|
// Profile ID
|
||||||
|
ProfileID uint64 `json:"profileId"`
|
||||||
|
|
||||||
|
// RAM
|
||||||
|
RAM uint64 `json:"ram"`
|
||||||
|
|
||||||
|
// Reference ID
|
||||||
|
ReferenceID string `json:"referenceId"`
|
||||||
|
|
||||||
|
// RG ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// Type
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// VM ID
|
||||||
|
VMID uint64 `json:"vmid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main information about PCI device
|
||||||
|
type ItemPCIDevice struct {
|
||||||
|
// Compute ID
|
||||||
|
ComputeID uint64 `json:"computeId"`
|
||||||
|
|
||||||
|
// Description
|
||||||
|
Description string `json:"description"`
|
||||||
|
|
||||||
|
// GUID
|
||||||
|
GUID uint64 `json:"guid"`
|
||||||
|
|
||||||
|
// HwPath
|
||||||
|
HwPath string `json:"hwPath"`
|
||||||
|
|
||||||
|
// ID
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
|
||||||
|
// Name
|
||||||
|
Name string `json:"name"`
|
||||||
|
|
||||||
|
// Resource group ID
|
||||||
|
RGID uint64 `json:"rgId"`
|
||||||
|
|
||||||
|
// Stack ID
|
||||||
|
StackID uint64 `json:"stackId"`
|
||||||
|
|
||||||
|
// Status
|
||||||
|
Status string `json:"status"`
|
||||||
|
|
||||||
|
// System name
|
||||||
|
SystemName string `json:"systemName"`
|
||||||
|
}
|
||||||
|
|
||||||
// List PCI devices
|
// List PCI devices
|
||||||
type ListPCIDevices struct {
|
type ListPCIDevices struct {
|
||||||
// Data
|
// Data
|
||||||
Data []interface{} `json:"data"`
|
Data []ItemPCIDevice `json:"data"`
|
||||||
|
|
||||||
// Entry count
|
// Entry count
|
||||||
EntryCount uint64 `json:"entryCount"`
|
EntryCount uint64 `json:"entryCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RecordCloneStatus struct {
|
||||||
|
// Disk ID
|
||||||
|
DiskID int `json:"disk_id"`
|
||||||
|
|
||||||
|
// Clone Status
|
||||||
|
Status CloneStatus `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CloneStatus struct {
|
||||||
|
// Type
|
||||||
|
Type int `json:"type"`
|
||||||
|
|
||||||
|
// Copy speed
|
||||||
|
Bandwidth int `json:"bandwidth"`
|
||||||
|
|
||||||
|
// Current progress
|
||||||
|
Cur int `json:"cur"`
|
||||||
|
|
||||||
|
// Total size
|
||||||
|
End int `json:"end"`
|
||||||
|
|
||||||
|
// Operation status
|
||||||
|
Ready bool `json:"ready"`
|
||||||
|
|
||||||
|
// Progress percent
|
||||||
|
ProgressPercent int `json:"progress_percent"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,9 +16,14 @@ type NetAttachRequest struct {
|
|||||||
|
|
||||||
// Network type
|
// Network type
|
||||||
// 'EXTNET' for connect to external network directly
|
// 'EXTNET' for connect to external network directly
|
||||||
// and 'VINS' for connect to ViNS
|
// 'VINS' for connect to ViNS
|
||||||
|
// 'VFNIC' for connect to vfpool
|
||||||
|
// 'DPDK' for connect to DPDK
|
||||||
|
// `EMPTY` for connect empty network
|
||||||
|
// `SDT` for connect to SDN
|
||||||
|
// `TRUNK` for connect to TRUNK
|
||||||
// Required: true
|
// Required: true
|
||||||
NetType string `url:"netType" json:"netType" validate:"computeNetType"`
|
NetType string `url:"netType" json:"netType" validate:"computex86NetType"`
|
||||||
|
|
||||||
// Network ID for connect to
|
// Network ID for connect to
|
||||||
// For EXTNET - external network ID
|
// For EXTNET - external network ID
|
||||||
@@ -29,6 +34,32 @@ type NetAttachRequest struct {
|
|||||||
// Directly required IP address for new network interface
|
// Directly required IP address for new network interface
|
||||||
// Required: false
|
// Required: false
|
||||||
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`
|
||||||
|
|
||||||
|
// MAC address
|
||||||
|
// Required: false
|
||||||
|
MACAddr string `url:"mac_addr,omitempty" json:"mac_addr,omitempty"`
|
||||||
|
|
||||||
|
// Used only for EXTNET and DPDK
|
||||||
|
// For DPDK must be 1-9216
|
||||||
|
// For EXTNET must be 1500-9216
|
||||||
|
// Required: false
|
||||||
|
MTU uint64 `url:"mtu,omitempty" json:"mtu,omitempty" validate:"omitempty,mtu"`
|
||||||
|
|
||||||
|
// Unique identifier of logical port on SDN side
|
||||||
|
// Required: false
|
||||||
|
SDNInterfaceID string `url:"sdn_interface_id,omitempty" json:"sdn_interface_id,omitempty" validate:"omitempty"`
|
||||||
|
|
||||||
|
// List of security group IDs to assign to this interface
|
||||||
|
// Required: false
|
||||||
|
SecGroups []uint64 `url:"security_groups,omitempty" json:"security_groups,omitempty"`
|
||||||
|
|
||||||
|
// Flag indicating whether security groups are enabled for this interface
|
||||||
|
// Required: false
|
||||||
|
EnableSecGroups bool `url:"enable_secgroups,omitempty" json:"enable_secgroups,omitempty"`
|
||||||
|
|
||||||
|
// Flag indicating whether this interface is enabled (only for VINS, EXTNET, DPDK, SDN, TRUNK)
|
||||||
|
// Required: false
|
||||||
|
Enabled interface{} `url:"enabled,omitempty" json:"enabled,omitempty" validate:"omitempty,isBool"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NetAttach attaches network to compute and gets info about network
|
// NetAttach attaches network to compute and gets info about network
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ type PFWAddRequest struct {
|
|||||||
PublicPortEnd int64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
PublicPortEnd int64 `url:"publicPortEnd,omitempty" json:"publicPortEnd,omitempty"`
|
||||||
|
|
||||||
// Internal base port number
|
// Internal base port number
|
||||||
// Required: true
|
// Required: false
|
||||||
LocalBasePort uint64 `url:"localBasePort" json:"localBasePort" validate:"required"`
|
LocalBasePort uint64 `url:"localBasePort,omitempty" json:"localBasePort,omitempty"`
|
||||||
|
|
||||||
// Network protocol
|
// Network protocol
|
||||||
// either "tcp" or "udp"
|
// either "tcp" or "udp"
|
||||||
|
|||||||
@@ -13,25 +13,30 @@ type PinToStackRequest struct {
|
|||||||
// ID of the compute instance
|
// ID of the compute instance
|
||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Auto start when node restarted
|
||||||
|
// Required: false
|
||||||
|
// Default: false
|
||||||
|
AutoStart bool `url:"autoStart" json:"autoStart"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PinToStack pin compute to current stack
|
// PinToStack pin compute to current stack
|
||||||
func (c Compute) PinToStack(ctx context.Context, req PinToStackRequest) (uint64, error) {
|
func (c Compute) PinToStack(ctx context.Context, req PinToStackRequest) (bool, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/pinToStack"
|
url := "/cloudapi/compute/pinToStack"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := strconv.ParseUint(string(res), 10, 64)
|
result, err := strconv.ParseBool(string(res))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
|||||||
@@ -14,9 +14,17 @@ type RedeployRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
ComputeID uint64 `url:"computeId" json:"computeId" validate:"required"`
|
||||||
|
|
||||||
|
// Storage policy id of compute. The rules of the specified storage policy will be used.
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
|
||||||
// ID of the new OS image, if image change is required
|
// ID of the new OS image, if image change is required
|
||||||
// Required: false
|
// Required: false
|
||||||
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`
|
||||||
|
|
||||||
|
// The OS version that will be installed on the virtual machine
|
||||||
|
// Required: false
|
||||||
|
OSVersion string `url:"os_version,omitempty" json:"os_version,omitempty"`
|
||||||
|
|
||||||
// new size for the boot disk in GB, if boot disk size change is required
|
// new size for the boot disk in GB, if boot disk size change is required
|
||||||
// Required: false
|
// Required: false
|
||||||
|
|||||||
@@ -27,6 +27,20 @@ type ResizeRequest struct {
|
|||||||
// Force compute resize
|
// Force compute resize
|
||||||
// Required: false
|
// Required: false
|
||||||
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
Force bool `url:"force,omitempty" json:"force,omitempty"`
|
||||||
|
|
||||||
|
// Recommended isolated CPUs. Field is ignored if compute.cpupin=False or compute.pinned=False
|
||||||
|
// Required: false
|
||||||
|
PreferredCPU []int64 `url:"preferredCpu,omitempty" json:"preferredCpu,omitempty" validate:"omitempty,preferredCPU"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRAM returns RAM field values
|
||||||
|
func (r ResizeRequest) GetRAM() map[string]uint64 {
|
||||||
|
|
||||||
|
res := make(map[string]uint64, 1)
|
||||||
|
|
||||||
|
res["RAM"] = r.RAM
|
||||||
|
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resize resizes compute instance
|
// Resize resizes compute instance
|
||||||
|
|||||||
33
pkg/cloudapi/compute/shared_snapshot_merge_status.go
Normal file
33
pkg/cloudapi/compute/shared_snapshot_merge_status.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package compute
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SharedSnapshotMergeStatusRequest struct to get shared snapshot merge status
|
||||||
|
type SharedSnapshotMergeStatusRequest struct {
|
||||||
|
// ID of compute instance to get log for
|
||||||
|
// Required: true
|
||||||
|
ComputeID uint64 `url:"compute_id" json:"compute_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SharedSnapshotMergeStatus shared snapshots merge status
|
||||||
|
// returns a string representing either the current status or the progress percentage
|
||||||
|
func (c Compute) SharedSnapshotMergeStatus(ctx context.Context, req SharedSnapshotMergeStatusRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/shared_snapshot_merge_status"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodGet, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(res), nil
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package compute
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
@@ -19,24 +18,52 @@ type SnapshotDeleteRequest struct {
|
|||||||
Label string `url:"label" json:"label" validate:"required"`
|
Label string `url:"label" json:"label" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type wrapperSnapshotDeleteRequeststruct struct {
|
||||||
|
SnapshotDeleteRequest
|
||||||
|
|
||||||
|
AsyncMode bool `url:"asyncMode"`
|
||||||
|
}
|
||||||
|
|
||||||
// SnapshotDelete deletes specified compute snapshot
|
// SnapshotDelete deletes specified compute snapshot
|
||||||
func (c Compute) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (bool, error) {
|
func (c Compute) SnapshotDelete(ctx context.Context, req SnapshotDeleteRequest) (string, error) {
|
||||||
err := validators.ValidateRequest(req)
|
err := validators.ValidateRequest(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, validators.ValidationErrors(validators.GetErrors(err))
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
reqWrapped := wrapperSnapshotDeleteRequeststruct{
|
||||||
|
SnapshotDeleteRequest: req,
|
||||||
|
AsyncMode: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
url := "/cloudapi/compute/snapshotDelete"
|
url := "/cloudapi/compute/snapshotDelete"
|
||||||
|
|
||||||
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := strconv.ParseBool(string(res))
|
return string(res), nil
|
||||||
if err != nil {
|
}
|
||||||
return false, err
|
|
||||||
}
|
// SnapshotDeleteAsync deletes specified compute snapshot
|
||||||
|
func (c Compute) SnapshotDeleteAsync(ctx context.Context, req SnapshotDeleteRequest) (string, error) {
|
||||||
return result, nil
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
reqWrapped := wrapperSnapshotDeleteRequeststruct{
|
||||||
|
SnapshotDeleteRequest: req,
|
||||||
|
AsyncMode: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/compute/snapshotDelete"
|
||||||
|
|
||||||
|
res, err := c.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(res), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,54 @@ type UpdateRequest struct {
|
|||||||
// New description
|
// New description
|
||||||
// Required: false
|
// Required: false
|
||||||
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
Description string `url:"desc,omitempty" json:"desc,omitempty"`
|
||||||
|
|
||||||
|
// Rule for VM placement with NUMA affinity.
|
||||||
|
// Possible values - none (placement without NUMA affinity),
|
||||||
|
// strict (strictly with NUMA affinity, if not possible - do not start VM),
|
||||||
|
// loose (use NUMA affinity if possible)
|
||||||
|
// Required: false
|
||||||
|
// Default: none
|
||||||
|
NumaAffinity string `url:"numaAffinity,omitempty" json:"numaAffinity,omitempty" validate:"omitempty,numaAffinity"`
|
||||||
|
|
||||||
|
// Run VM on dedicated CPUs. To use this feature, the system must be pre-configured by allocating CPUs on the physical node, true or false
|
||||||
|
// Required: false
|
||||||
|
CPUPin interface{} `url:"cpupin,omitempty" json:"cpupin,omitempty" validate:"omitempty,isBool"`
|
||||||
|
|
||||||
|
// Type of the emulated system, Q35 or i440fx
|
||||||
|
// Required: false
|
||||||
|
Chipset string `url:"chipset,omitempty" json:"chipset,omitempty" validate:"omitempty,chipset"`
|
||||||
|
|
||||||
|
// Use Huge Pages to allocate RAM of the virtual machine. The system must be pre-configured by allocating Huge Pages on the physical node, true or false
|
||||||
|
// Required: false
|
||||||
|
HPBacked interface{} `url:"hpBacked,omitempty" json:"hpBacked,omitempty" validate:"omitempty,isBool"`
|
||||||
|
|
||||||
|
// Auto start when node restarted, true or false
|
||||||
|
// Required: false
|
||||||
|
AutoStart interface{} `url:"autoStart,omitempty" json:"autoStart,omitempty" validate:"omitempty,isBool"`
|
||||||
|
|
||||||
|
// Recommended isolated CPUs. Field is ignored if compute.cpupin=False or compute.pinned=False
|
||||||
|
// Required: false
|
||||||
|
PreferredCPU []int64 `url:"preferredCpu,omitempty" json:"preferredCpu,omitempty" validate:"omitempty,preferredCPU"`
|
||||||
|
|
||||||
|
// VM type linux, windows or unknown
|
||||||
|
// Required: false
|
||||||
|
LoaderType string `url:"loaderType,omitempty" json:"loaderType,omitempty" validate:"omitempty,loaderType"`
|
||||||
|
|
||||||
|
// Boot type of image bios or uefi
|
||||||
|
// Required: false
|
||||||
|
BootType string `url:"bootType,omitempty" json:"bootType,omitempty" validate:"omitempty,imageBootType"`
|
||||||
|
|
||||||
|
// Select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming.
|
||||||
|
// Required: false
|
||||||
|
NetworkInterfaceNaming string `url:"networkInterfaceNaming,omitempty" json:"networkInterfaceNaming,omitempty" validate:"omitempty,networkInterfaceNaming"`
|
||||||
|
|
||||||
|
// Does this machine supports hot resize, true or false
|
||||||
|
// Required: false
|
||||||
|
HotResize interface{} `url:"hotResize,omitempty" json:"hotResize,omitempty" validate:"omitempty,isBool"`
|
||||||
|
|
||||||
|
// The OS version that will be installed on the virtual machine
|
||||||
|
// Required: false
|
||||||
|
OSVersion string `url:"os_version,omitempty" json:"os_version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update updates some properties of the compute
|
// Update updates some properties of the compute
|
||||||
|
|||||||
42
pkg/cloudapi/disks/change_disk_storage_policy.go
Normal file
42
pkg/cloudapi/disks/change_disk_storage_policy.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeDiskStoragePolicyRequest struct to change storage policy for disk
|
||||||
|
type ChangeDiskStoragePolicyRequest struct {
|
||||||
|
// ID of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"disk_id" json:"disk_id" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the storage policy to which to connect for disk
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeDiskStoragePolicy changes storage policy for disk
|
||||||
|
func (d Disks) ChangeDiskStoragePolicy(ctx context.Context, req ChangeDiskStoragePolicyRequest) (bool, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return false, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/change_disk_storage_policy"
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, req)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(string(res))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -3,8 +3,9 @@ package disks
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateRequest struct to create disk
|
// CreateRequest struct to create disk
|
||||||
@@ -13,14 +14,14 @@ type CreateRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
AccountID uint64 `url:"accountId" json:"accountId" validate:"required"`
|
||||||
|
|
||||||
// ID of the grid (platform)
|
|
||||||
// Required: true
|
|
||||||
GID uint64 `url:"gid" json:"gid" validate:"required"`
|
|
||||||
|
|
||||||
// Name of disk
|
// Name of disk
|
||||||
// Required: true
|
// Required: true
|
||||||
Name string `url:"name" json:"name" validate:"required"`
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// ID of the storage policy under the disk will be created
|
||||||
|
// Required: true
|
||||||
|
StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`
|
||||||
|
|
||||||
// Description of disk
|
// Description of disk
|
||||||
// Required: false
|
// Required: false
|
||||||
Description string `url:"description,omitempty" json:"description,omitempty"`
|
Description string `url:"description,omitempty" json:"description,omitempty"`
|
||||||
@@ -29,21 +30,6 @@ type CreateRequest struct {
|
|||||||
// Required: false
|
// Required: false
|
||||||
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
Size uint64 `url:"size,omitempty" json:"size,omitempty"`
|
||||||
|
|
||||||
// Type of disk
|
|
||||||
// - B=Boot
|
|
||||||
// - D=Data
|
|
||||||
// - T=Temp
|
|
||||||
// Required: true
|
|
||||||
Type string `url:"type" json:"type" validate:"diskType"`
|
|
||||||
|
|
||||||
// Size in GB default is 0
|
|
||||||
// Required: false
|
|
||||||
SSDSize uint64 `url:"ssdSize,omitempty" json:"ssdSize,omitempty"`
|
|
||||||
|
|
||||||
// Max IOPS disk can perform defaults to 2000
|
|
||||||
// Required: false
|
|
||||||
IOPS uint64 `url:"iops,omitempty" json:"iops,omitempty"`
|
|
||||||
|
|
||||||
// Storage endpoint provider ID to create disk
|
// Storage endpoint provider ID to create disk
|
||||||
// Required: false
|
// Required: false
|
||||||
SEPID uint64 `url:"sep_id,omitempty" json:"sep_id,omitempty"`
|
SEPID uint64 `url:"sep_id,omitempty" json:"sep_id,omitempty"`
|
||||||
|
|||||||
@@ -21,10 +21,6 @@ type DeleteRequest struct {
|
|||||||
// Whether to completely delete the disk, works only with non attached disks
|
// Whether to completely delete the disk, works only with non attached disks
|
||||||
// Required: false
|
// Required: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
||||||
|
|
||||||
// Reason to delete
|
|
||||||
// Required: false
|
|
||||||
Reason string `url:"reason,omitempty" json:"reason,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes disk by ID
|
// Delete deletes disk by ID
|
||||||
|
|||||||
@@ -14,10 +14,6 @@ type DisksDeleteRequest struct {
|
|||||||
// Required: true
|
// Required: true
|
||||||
DisksIDs []uint64 `url:"diskIds" json:"diskIds" validate:"required"`
|
DisksIDs []uint64 `url:"diskIds" json:"diskIds" validate:"required"`
|
||||||
|
|
||||||
// Reason for deleting the disks
|
|
||||||
// Required: true
|
|
||||||
Reason string `url:"reason" json:"reason" validate:"required"`
|
|
||||||
|
|
||||||
// Whether to completely delete the disks, works only with non attached disks
|
// Whether to completely delete the disks, works only with non attached disks
|
||||||
// Required: false
|
// Required: false
|
||||||
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
Permanently bool `url:"permanently,omitempty" json:"permanently,omitempty"`
|
||||||
|
|||||||
@@ -35,9 +35,9 @@ var disks = ListDisks{
|
|||||||
ParentID: 0,
|
ParentID: 0,
|
||||||
PCISlot: 6,
|
PCISlot: 6,
|
||||||
Pool: "vmstor",
|
Pool: "vmstor",
|
||||||
PresentTo: []uint64{
|
//PresentTo: []uint64{
|
||||||
27,
|
// 27,
|
||||||
},
|
//},
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
ResID: "sample",
|
ResID: "sample",
|
||||||
ResName: "sample",
|
ResName: "sample",
|
||||||
@@ -78,10 +78,10 @@ var disks = ListDisks{
|
|||||||
ParentID: 0,
|
ParentID: 0,
|
||||||
PCISlot: 6,
|
PCISlot: 6,
|
||||||
Pool: "vmstor",
|
Pool: "vmstor",
|
||||||
PresentTo: []uint64{
|
//PresentTo: []uint64{
|
||||||
27,
|
// 27,
|
||||||
27,
|
// 27,
|
||||||
},
|
//},
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
ResID: "sample",
|
ResID: "sample",
|
||||||
ResName: "sample",
|
ResName: "sample",
|
||||||
@@ -211,9 +211,9 @@ var searchDisks = ListSearchDisks{
|
|||||||
ParentID: 0,
|
ParentID: 0,
|
||||||
PCISlot: 6,
|
PCISlot: 6,
|
||||||
Pool: "vmstor",
|
Pool: "vmstor",
|
||||||
PresentTo: []uint64{
|
//PresentTo: []uint64{
|
||||||
27,
|
// 27,
|
||||||
},
|
//},
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
ResID: "sample",
|
ResID: "sample",
|
||||||
ResName: "sample",
|
ResName: "sample",
|
||||||
@@ -254,10 +254,10 @@ var searchDisks = ListSearchDisks{
|
|||||||
ParentID: 0,
|
ParentID: 0,
|
||||||
PCISlot: 6,
|
PCISlot: 6,
|
||||||
Pool: "vmstor",
|
Pool: "vmstor",
|
||||||
PresentTo: []uint64{
|
//PresentTo: []uint64{
|
||||||
27,
|
// 27,
|
||||||
27,
|
// 27,
|
||||||
},
|
//},
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
ResID: "sample",
|
ResID: "sample",
|
||||||
ResName: "sample",
|
ResName: "sample",
|
||||||
@@ -393,7 +393,7 @@ var unattachedDisks = ListDisksUnattached{
|
|||||||
Password: "",
|
Password: "",
|
||||||
PCISlot: -1,
|
PCISlot: -1,
|
||||||
Pool: "data05",
|
Pool: "data05",
|
||||||
PresentTo: []uint64{},
|
PresentTo: map[string]uint64{},
|
||||||
PurgeAttempts: 0,
|
PurgeAttempts: 0,
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
RealityDeviceNumber: 0,
|
RealityDeviceNumber: 0,
|
||||||
@@ -445,10 +445,10 @@ var unattachedDisks = ListDisksUnattached{
|
|||||||
Password: "",
|
Password: "",
|
||||||
PCISlot: -1,
|
PCISlot: -1,
|
||||||
Pool: "data05",
|
Pool: "data05",
|
||||||
PresentTo: []uint64{
|
//PresentTo: []uint64{
|
||||||
27,
|
// 27,
|
||||||
27,
|
// 27,
|
||||||
},
|
//},
|
||||||
PurgeAttempts: 0,
|
PurgeAttempts: 0,
|
||||||
PurgeTime: 0,
|
PurgeTime: 0,
|
||||||
RealityDeviceNumber: 0,
|
RealityDeviceNumber: 0,
|
||||||
|
|||||||
111
pkg/cloudapi/disks/from_platform_disk.go
Normal file
111
pkg/cloudapi/disks/from_platform_disk.go
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
package disks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FromPlatformDiskRequest struct to create template from platform disk
|
||||||
|
type FromPlatformDiskRequest struct {
|
||||||
|
// ID of the disk
|
||||||
|
// Required: true
|
||||||
|
DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`
|
||||||
|
|
||||||
|
// Name of the rescue disk
|
||||||
|
// Required: true
|
||||||
|
Name string `url:"name" json:"name" validate:"required"`
|
||||||
|
|
||||||
|
// Boot type of image BIOS or UEFI
|
||||||
|
// Required: true
|
||||||
|
BootType string `url:"boottype" json:"boottype" validate:"imageBootType"`
|
||||||
|
|
||||||
|
// Image type linux, windows or other
|
||||||
|
// Required: true
|
||||||
|
ImageType string `url:"imagetype" json:"imagetype" validate:"imageType"`
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
|
||||||
|
// Pool for image create
|
||||||
|
// Required: false
|
||||||
|
PoolName string `url:"poolName,omitempty" json:"poolName,omitempty"`
|
||||||
|
|
||||||
|
// Does this machine supports hot resize
|
||||||
|
// Required: false
|
||||||
|
HotResize bool `url:"hotresize" json:"hotresize"`
|
||||||
|
|
||||||
|
// Bootable image
|
||||||
|
// Required: true
|
||||||
|
Bootable bool `url:"bootable" json:"bootable"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wrapperFromPlatformDiskRequest struct {
|
||||||
|
FromPlatformDiskRequest
|
||||||
|
AsyncMode bool `url:"asyncMode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPlatformDisk creates template from platform disk in sync mode.
|
||||||
|
// It returns id of created disk and error.
|
||||||
|
func (d Disks) FromPlatformDisk(ctx context.Context, req FromPlatformDiskRequest) (uint64, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/fromPlatformDisk"
|
||||||
|
|
||||||
|
reqWrapped := wrapperFromPlatformDiskRequest{
|
||||||
|
FromPlatformDiskRequest: req,
|
||||||
|
AsyncMode: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := strconv.ParseUint(string(res), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromPlatformDiskAsync creates template from platform disk in async mode.
|
||||||
|
// It returns guid of task and error.
|
||||||
|
func (d Disks) FromPlatformDiskAsync(ctx context.Context, req FromPlatformDiskRequest) (string, error) {
|
||||||
|
err := validators.ValidateRequest(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", validators.ValidationErrors(validators.GetErrors(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "/cloudapi/disks/fromPlatformDisk"
|
||||||
|
|
||||||
|
reqWrapped := wrapperFromPlatformDiskRequest{
|
||||||
|
FromPlatformDiskRequest: req,
|
||||||
|
AsyncMode: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := strings.ReplaceAll(string(res), "\"", "")
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user