Compare commits

..

2 Commits

Author SHA1 Message Date
a85ad3acd5 v1.7.1 2023-11-15 12:03:31 +03:00
823dfb49bc v1.7.0 2023-11-09 10:27:14 +03:00
8 changed files with 233 additions and 100 deletions

View File

@@ -1,9 +1,4 @@
## Version 1.7.0
## Feature
- Added support for authorization using the Basis.Virtual Security system. Add client and config
## Version 1.7.1
## Bugfix
- Add model ListInfoSnapshots in cloudapi/bservice/models
- Fix func SnapshotList for work with new model cloudapi/bservice/snapshot_list
- Add models ItemAffinityGroup, ListAffinityGroup in cloudapi/rg/models
- Fix panic in clients

175
README.md
View File

@@ -11,6 +11,7 @@ Decort SDK - это библиотека, написанная на языке G
- Версия 1.4.x Decort-SDK соответствует 3.8.6 версии платформы
- Версия 1.5.x Decort-SDK соответствует 3.8.7 версии платформы
- Версия 1.6.x Decort-SDK соответствует 3.8.8 версии платформы
- Версия 1.7.х Decort-SDK соответствует 3.8.9 версии платформы
## Оглавление
@@ -936,6 +937,7 @@ func main() {
legacyCfg := config.LegacyConfig{
Username: "<USERNAME>",
Password: "<PASSWORD>",
Domain: "dynamix",
DecortURL: "https://mr4.digitalenergy.online",
Retries: 5,
}
@@ -961,3 +963,176 @@ func main() {
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)
}

View File

@@ -164,21 +164,20 @@ func (dc *DecortClient) do(req *http.Request, ctype string) (*http.Response, err
// var resp *http.Response
// var err error
buf, _ := io.ReadAll(req.Body)
// req = req.Clone(req.Context())
// for i := uint64(0); i < dc.cfg.Retries; i++ {
// req = req.Clone(req.Context())
req.Body = io.NopCloser(bytes.NewBuffer(buf))
resp, err := dc.client.Do(req)
// if err == nil {
if resp.StatusCode == 200 {
return resp, err
if err == nil {
if resp.StatusCode == 200 {
return resp, err
}
}
// }
respBytes, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("%s", respBytes)
resp.Body.Close()
// }
// }
return nil, fmt.Errorf("could not execute request: %w", err)
}
@@ -404,7 +403,7 @@ func createK8sCloudBroker(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
ct := writer.FormDataContentType()
writer.Close()

View File

@@ -15,7 +15,6 @@ import (
"sync"
"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/pkg/cloudapi"
k8s_ca "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
@@ -26,16 +25,9 @@ import (
// HTTP-client for platform
type BVSDecortClient struct {
client *http.Client
cfg *oauth2.Config
cfg config.BVSConfig
mutex *sync.Mutex
token *oauth2.Token
decortURL string
username string
password string
}
type ProviderEndpoint struct {
TokenURL string `json:"token_endpoint"`
}
// Сlient builder
@@ -43,11 +35,6 @@ func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
if cfg.Retries == 0 {
cfg.Retries = 5
}
// if cfg.Token.AccessToken != "" {
// }
ctx := context.Background()
providerEndpoint, _ := GetEndpoint(ctx, cfg.SSOURL, cfg.Domain, cfg.SSLSkipVerify)
return &BVSDecortClient{
decortURL: cfg.DecortURL,
@@ -59,15 +46,8 @@ func NewBVS(cfg config.BVSConfig) *BVSDecortClient {
},
},
},
cfg: &oauth2.Config{
ClientID: cfg.AppID,
ClientSecret: cfg.AppSecret,
Endpoint: providerEndpoint,
},
mutex: &sync.Mutex{},
token: &cfg.Token,
username: cfg.Username,
password: cfg.Password,
cfg: cfg,
mutex: &sync.Mutex{},
}
}
@@ -131,14 +111,14 @@ func (bdc *BVSDecortClient) getToken(ctx context.Context) error {
bdc.mutex.Lock()
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)
// body := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s&", bdc.cfg.ClientID, bdc.cfg.ClientSecret)
// bodyReader := strings.NewReader(body)
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.Endpoint.TokenURL, bodyReader)
bdc.cfg.SSOURL = strings.TrimSuffix(bdc.cfg.SSOURL, "/")
req, _ := http.NewRequestWithContext(ctx, "POST", bdc.cfg.SSOURL+"/realms/"+bdc.cfg.Domain+"/protocol/openid-connect/token", bodyReader)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
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)
}
err = json.Unmarshal(tokenBytes, &bdc.token)
err = json.Unmarshal(tokenBytes, &bdc.cfg.Token)
if err != nil {
return fmt.Errorf("cannot unmarshal token: %s", tokenBytes)
}
@@ -168,26 +148,26 @@ func (bdc *BVSDecortClient) do(req *http.Request, ctype string) (*http.Response,
} else {
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")
// var resp *http.Response
// var err error
buf, _ := io.ReadAll(req.Body)
// req = req.Clone(req.Context())
// for i := uint64(0); i < dc.cfg.Retries; i++ {
// for i := uint64(0); i < bdc.cfg.Retries; i++ {
// req = req.Clone(req.Context())
req.Body = io.NopCloser(bytes.NewBuffer(buf))
resp, err := bdc.client.Do(req)
// if err == nil {
if resp.StatusCode != 200 {
return resp, err
if err == nil {
if resp.StatusCode == 200 {
return resp, err
}
}
// }
respBytes, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("%s", respBytes)
resp.Body.Close()
// }
// }
return nil, fmt.Errorf("could not execute request: %w", err)
}
@@ -419,39 +399,3 @@ func createK8sCloudBrokerBVS(req k8s_cb.CreateRequest) (*bytes.Buffer, string) {
writer.Close()
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
}

View File

@@ -23,7 +23,7 @@ type BVSConfig struct {
// Domain name
// Required: true
// Example: "realms/dynamix"
// Example: "dynamix"
Domain string `json:"domain" yaml:"domain"`
// Application (client) identifier for authorization

View File

@@ -78,7 +78,7 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
k8sCaCreateReq, okCa := params.(k8s_ca.CreateRequest)
k8sCbCreateReq, okCb := params.(k8s_cb.CreateRequest)
var body *bytes.Buffer
var ctype string
@@ -93,7 +93,7 @@ func (ldc *LegacyDecortClient) DecortApiCall(ctx context.Context, method, url st
}
body = bytes.NewBufferString(values.Encode() + fmt.Sprintf("&authkey=%s", ldc.cfg.Token))
}
req, err := http.NewRequestWithContext(ctx, method, ldc.decortURL+restmachine+url, body)
if err != nil {
return nil, err
@@ -159,22 +159,20 @@ func (ldc *LegacyDecortClient) do(req *http.Request, ctype string) (*http.Respon
// var resp *http.Response
// var err error
buf, _ := io.ReadAll(req.Body)
// req = req.Clone(req.Context())
// for i := uint64(0); i < ldc.cfg.Retries; i++ {
// req = req.Clone(req.Context())
req.Body = io.NopCloser(bytes.NewBuffer(buf))
resp, err := ldc.client.Do(req)
// if err == nil {
if resp.StatusCode == 200 {
return resp, err
if err == nil {
if resp.StatusCode == 200 {
return resp, err
}
}
// }
respBytes, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("%s", respBytes)
resp.Body.Close()
// }
// }
return nil, fmt.Errorf("could not execute request: %w", err)
}
@@ -402,7 +400,7 @@ func createK8sCloudBrokerLegacy(req k8s_cb.CreateRequest, token string) (*bytes.
}
_ = writer.WriteField("extnetOnly", strconv.FormatBool(req.ExtNetOnly))
_ = writer.WriteField("authkey", token)
ct := writer.FormDataContentType()

View 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
}

View 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