v1.7.0
This commit is contained in:
175
README.md
175
README.md
@@ -11,6 +11,7 @@ Decort SDK - это библиотека, написанная на языке G
|
|||||||
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
|
||||||
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
|
||||||
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
|
||||||
|
- Версия 1.7.х Decort-SDK соответствует 3.8.9 версии платформы
|
||||||
|
|
||||||
## Оглавление
|
## Оглавление
|
||||||
|
|
||||||
@@ -936,6 +937,7 @@ func main() {
|
|||||||
legacyCfg := config.LegacyConfig{
|
legacyCfg := config.LegacyConfig{
|
||||||
Username: "<USERNAME>",
|
Username: "<USERNAME>",
|
||||||
Password: "<PASSWORD>",
|
Password: "<PASSWORD>",
|
||||||
|
Domain: "dynamix",
|
||||||
DecortURL: "https://mr4.digitalenergy.online",
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
Retries: 5,
|
Retries: 5,
|
||||||
}
|
}
|
||||||
@@ -961,3 +963,176 @@ func main() {
|
|||||||
|
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Работа с BVS клиентом
|
||||||
|
|
||||||
|
Работа с BVS клиентом применяется для пользователей, которые используют для авторизации BVS.
|
||||||
|
|
||||||
|
### Настройка конфигурации BVS клиента
|
||||||
|
|
||||||
|
Сначала, необходимо создать переменную конфигурации клиента. Конфигурация состоит как из обязательных, так и необязательных полей.
|
||||||
|
|
||||||
|
| Поле | Тип | Обязательный | Описание |
|
||||||
|
| ------------- | ------ | ------------ | ------------------------------------------------------------------ |
|
||||||
|
| Username | string | Да | username legacy пользователя |
|
||||||
|
| Password | string | Да | пароль legacy пользователя |
|
||||||
|
| DecortURL | string | Да | URL адрес платформы, с которой будет осуществляться взаимодействие |
|
||||||
|
| SSOURL | string | Да | URL адрес сервиса аутентификации и авторизации |
|
||||||
|
| Domain | string | Да | Имя домена |
|
||||||
|
| Retries | uint | Нет | Кол-во неудачных попыток выполнения запроса, по умолчанию - 5 |
|
||||||
|
| Timeout | config.Duration | Нет | Таймаут HTTP клиента, по умолчанию - без ограничений |
|
||||||
|
| SSLSkipVerify | bool | Нет | Пропуск проверки подлинности сертификата |
|
||||||
|
|
||||||
|
|
||||||
|
#### Пример конфигурации BVS клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main(){
|
||||||
|
// Настройка конфигурации
|
||||||
|
BvsCfg := config.BVSConfig{
|
||||||
|
AppID: "<APP_ID>",
|
||||||
|
AppSecret: "<APP_SECRET>",
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443"
|
||||||
|
DecortURL: "https://delta.qa.loc",
|
||||||
|
Domain: "dynamix"
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
BvsCfg.SetTimeout(5 * time.Minute)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Парсинг BVS конфигурации из файла
|
||||||
|
|
||||||
|
Также возможно создать переменную конфигурации из JSON или YAML файла, используя функцию `ParseConfigBVSJSON` (или `ParseConfigBVSYAML`) из пакета config.
|
||||||
|
<br>
|
||||||
|
*См. пример файлов конфигурации ниже и в директории `samples/`.*
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Парсинг конфигурации из YAML-файла
|
||||||
|
BVSCfg := config.ParseConfigBVSYAML("<PATH>")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример BVS JSON конфигурации
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "<USERNAME>",
|
||||||
|
"password": "<PASSWORD>",
|
||||||
|
"appId": "<APP_ID>",
|
||||||
|
"appSecret": "<APP_SECRET>",
|
||||||
|
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
||||||
|
"decortUrl": "https://delta.qa.loc",
|
||||||
|
"domain": "dynamix",
|
||||||
|
"retries": 5,
|
||||||
|
"timeout": "5m",
|
||||||
|
"sslSkipVerify": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример BVS YAML конфигурации
|
||||||
|
```yaml
|
||||||
|
username: <USERNAME>
|
||||||
|
password: <PASSWORD>
|
||||||
|
appId: <APP_ID>
|
||||||
|
appSecret: <APP_SECRET>
|
||||||
|
ssoUrl: https://bvs-delta.qa.loc:8443
|
||||||
|
decortUrl: https://delta.qa.loc
|
||||||
|
domain: dynamix,
|
||||||
|
retries: 5
|
||||||
|
timeout: 5m
|
||||||
|
sslSkipVerify: false
|
||||||
|
```
|
||||||
|
### Создание BVS клиента
|
||||||
|
|
||||||
|
Создание клиента происходит с помощью функции-строителя `NewBVS` из основного пакета `decort-sdk`, для избежания проблем с именами, пакету можно присвоить алиас `decort`. Функция принимает конфигурацию, возвращает структуру `DecortClient`, с помощью которой можно взаимодействовать с платформой.
|
||||||
|
|
||||||
|
#### Пример создания BVS клиента
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
BVSCfg := config.BVSConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443"
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Domain: "dynamix",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
BVSCfg.SetTimeout(5 * time.Minute)
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
BVSClient := decort.NewBVS(cfg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Пример выполнения запроса
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
|
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Настройка конфигурации
|
||||||
|
BVSCfg := config.config.BVSConfig{
|
||||||
|
Username: "<USERNAME>",
|
||||||
|
Password: "<PASSWORD>",
|
||||||
|
AppID: "<APPID>",
|
||||||
|
AppSecret: "<APPSECRET>",
|
||||||
|
SSOURL: "https://bvs-delta.qa.loc:8443"
|
||||||
|
DecortURL: "https://mr4.digitalenergy.online",
|
||||||
|
Domain: "dynamix",
|
||||||
|
Retries: 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание клиента
|
||||||
|
BVSClient := decort.NewBVS(cfg)
|
||||||
|
|
||||||
|
// Создание структуры запроса
|
||||||
|
// CreateRequest - реквест на создание виртуальной машины
|
||||||
|
req := kvmx86.CreateRequest{
|
||||||
|
RGID: 123,
|
||||||
|
Name: "compute",
|
||||||
|
CPU: 4,
|
||||||
|
RAM: 4096,
|
||||||
|
ImageID: 321,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выполнение запроса
|
||||||
|
res, err := client.CloudAPI().KVMX86().Create(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/google/go-querystring/query"
|
"github.com/google/go-querystring/query"
|
||||||
"golang.org/x/oauth2"
|
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/config"
|
||||||
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
|
||||||
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
|
||||||
@@ -26,16 +25,9 @@ import (
|
|||||||
// HTTP-client for platform
|
// HTTP-client for platform
|
||||||
type BVSDecortClient struct {
|
type BVSDecortClient struct {
|
||||||
client *http.Client
|
client *http.Client
|
||||||
cfg *oauth2.Config
|
cfg config.BVSConfig
|
||||||
mutex *sync.Mutex
|
mutex *sync.Mutex
|
||||||
token *oauth2.Token
|
|
||||||
decortURL string
|
decortURL string
|
||||||
username string
|
|
||||||
password string
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProviderEndpoint struct {
|
|
||||||
TokenURL string `json:"token_endpoint"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сlient builder
|
// Сlient builder
|
||||||
@@ -43,11 +35,6 @@ func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
|||||||
if cfg.Retries == 0 {
|
if cfg.Retries == 0 {
|
||||||
cfg.Retries = 5
|
cfg.Retries = 5
|
||||||
}
|
}
|
||||||
// if cfg.Token.AccessToken != "" {
|
|
||||||
|
|
||||||
// }
|
|
||||||
ctx := context.Background()
|
|
||||||
providerEndpoint, _ := GetEndpoint(ctx, cfg.SSOURL, cfg.Domain, cfg.SSLSkipVerify)
|
|
||||||
|
|
||||||
return &BVSDecortClient{
|
return &BVSDecortClient{
|
||||||
decortURL: cfg.DecortURL,
|
decortURL: cfg.DecortURL,
|
||||||
@@ -59,15 +46,8 @@ func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
cfg: &oauth2.Config{
|
cfg: cfg,
|
||||||
ClientID: cfg.AppID,
|
mutex: &sync.Mutex{},
|
||||||
ClientSecret: cfg.AppSecret,
|
|
||||||
Endpoint: providerEndpoint,
|
|
||||||
},
|
|
||||||
mutex: &sync.Mutex{},
|
|
||||||
token: &cfg.Token,
|
|
||||||
username: cfg.Username,
|
|
||||||
password: cfg.Password,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,14 +111,14 @@ func (bdc *BVSDecortClient) getToken(ctx context.Context) error {
|
|||||||
bdc.mutex.Lock()
|
bdc.mutex.Lock()
|
||||||
defer bdc.mutex.Unlock()
|
defer bdc.mutex.Unlock()
|
||||||
|
|
||||||
if !bdc.token.Valid() {
|
if !bdc.cfg.Token.Valid() {
|
||||||
|
|
||||||
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token", bdc.cfg.ClientID, bdc.cfg.ClientSecret, bdc.username, bdc.password)
|
body := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s&response_type=token&scope=openid", bdc.cfg.AppID, bdc.cfg.AppSecret, bdc.cfg.Username, bdc.cfg.Password)
|
||||||
bodyReader := strings.NewReader(body)
|
bodyReader := strings.NewReader(body)
|
||||||
// body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&", bdc.cfg.ClientID, bdc.cfg.ClientSecret)
|
|
||||||
// bodyReader := strings.NewReader(body)
|
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
|
||||||
|
|
||||||
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.Endpoint.TokenURL, bodyReader)
|
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
resp, err := bdc.client.Do(req)
|
resp, err := bdc.client.Do(req)
|
||||||
@@ -153,7 +133,7 @@ func (bdc *BVSDecortClient) getToken(ctx context.Context) error {
|
|||||||
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
return fmt.Errorf("cannot get token: %s", tokenBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = json.Unmarshal(tokenBytes, &bdc.token)
|
err = json.Unmarshal(tokenBytes, &bdc.cfg.Token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("cannot unmarshal token: %s", tokenBytes)
|
return fmt.Errorf("cannot unmarshal token: %s", tokenBytes)
|
||||||
}
|
}
|
||||||
@@ -168,7 +148,7 @@ func (bdc *BVSDecortClient) do(req *http.Request, ctype string) (*http.Response,
|
|||||||
} else {
|
} else {
|
||||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
}
|
}
|
||||||
bdc.token.SetAuthHeader(req)
|
bdc.cfg.Token.SetAuthHeader(req)
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
// var resp *http.Response
|
// var resp *http.Response
|
||||||
@@ -180,7 +160,7 @@ func (bdc *BVSDecortClient) do(req *http.Request, ctype string) (*http.Response,
|
|||||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
resp, err := bdc.client.Do(req)
|
resp, err := bdc.client.Do(req)
|
||||||
// if err == nil {
|
// if err == nil {
|
||||||
if resp.StatusCode != 200 {
|
if resp.StatusCode == 200 {
|
||||||
return resp, err
|
return resp, err
|
||||||
}
|
}
|
||||||
respBytes, _ := io.ReadAll(resp.Body)
|
respBytes, _ := io.ReadAll(resp.Body)
|
||||||
@@ -419,39 +399,3 @@ func createK8sCloudBrokerBVS(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
|
|||||||
writer.Close()
|
writer.Close()
|
||||||
return reqBody, ct
|
return reqBody, ct
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetEndpoint(ctx context.Context, issuer string, domain string, skip bool) (oauth2.Endpoint, error) {
|
|
||||||
wellKnown := issuer + "/" + domain + "/.well-known/openid-configuration"
|
|
||||||
req, err := http.NewRequestWithContext(ctx, "GET", wellKnown, nil)
|
|
||||||
if err != nil {
|
|
||||||
return oauth2.Endpoint{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
client := &http.Client{
|
|
||||||
Transport: &http.Transport{
|
|
||||||
TLSClientConfig: &tls.Config{
|
|
||||||
//nolint:gosec
|
|
||||||
InsecureSkipVerify: skip,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return oauth2.Endpoint{}, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return oauth2.Endpoint{}, fmt.Errorf("unable to read response body: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var p ProviderEndpoint
|
|
||||||
err = json.Unmarshal(body, &p)
|
|
||||||
if err != nil {
|
|
||||||
return oauth2.Endpoint{}, fmt.Errorf("cannot unmarshal endpoint: %s", body)
|
|
||||||
}
|
|
||||||
|
|
||||||
return oauth2.Endpoint{TokenURL: p.TokenURL}, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type BVSConfig struct {
|
|||||||
|
|
||||||
// Domain name
|
// Domain name
|
||||||
// Required: true
|
// Required: true
|
||||||
// Example: "realms/dynamix"
|
// Example: "dynamix"
|
||||||
Domain string `json:"domain" yaml:"domain"`
|
Domain string `json:"domain" yaml:"domain"`
|
||||||
|
|
||||||
// Application (client) identifier for authorization
|
// Application (client) identifier for authorization
|
||||||
|
|||||||
12
samples/config/bvs-config.json
Normal file
12
samples/config/bvs-config.json
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"username": "<USERNAME>",
|
||||||
|
"password": "<PASSWORD>",
|
||||||
|
"appId": "<APP_ID>",
|
||||||
|
"appSecret": "<APP_SECRET>",
|
||||||
|
"ssoUrl": "https://bvs-delta.qa.loc:8443",
|
||||||
|
"decortUrl": "https://delta.qa.loc",
|
||||||
|
"domain": "dynamix",
|
||||||
|
"retries": 5,
|
||||||
|
"timeout": "5m",
|
||||||
|
"sslSkipVerify": false
|
||||||
|
}
|
||||||
10
samples/config/bvs-config.yml
Normal file
10
samples/config/bvs-config.yml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
username: <USERNAME>
|
||||||
|
password: <PASSWORD>
|
||||||
|
appId: <APP_ID>
|
||||||
|
appSecret: <APP_SECRET>
|
||||||
|
ssoUrl: https://bvs-delta.qa.loc:8443
|
||||||
|
decortUrl: https://delta.qa.loc
|
||||||
|
domain: dynamix,
|
||||||
|
retries: 5
|
||||||
|
timeout: 5m
|
||||||
|
sslSkipVerify: false
|
||||||
Reference in New Issue
Block a user