This commit is contained in:
2023-12-14 18:32:46 +03:00
parent 2453a32d01
commit ce4b847596
9 changed files with 220 additions and 261 deletions

View File

@@ -21,7 +21,6 @@ limitations under the License.
package controller
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
@@ -39,8 +38,6 @@ import (
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
@@ -170,27 +167,27 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) {
case MODE_OAUTH2:
// on success getOAuth2JWT will set config.jwt to the obtained JWT, so there is no
// need to set it once again here
_, err := ret_config.getOAuth2JWT()
if err != nil {
return nil, err
}
// we are not verifying the JWT when parsing because actual verification is done on the
// OVC controller side. Here we do parsing solely to extract Oauth2 user name (claim "user")
// and JWT issuer name (claim "iss")
parser := jwt.Parser{}
token, _, err := parser.ParseUnverified(ret_config.jwt, jwt.MapClaims{})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
var tbuf bytes.Buffer
tbuf.WriteString(claims["username"].(string))
tbuf.WriteString("@")
tbuf.WriteString(claims["iss"].(string))
ret_config.decort_username = tbuf.String()
} else {
return nil, fmt.Errorf("Failed to extract user and iss fields from JWT token in oauth2 mode.")
}
// _, err := ret_config.getOAuth2JWT()
// if err != nil {
// return nil, err
// }
// // we are not verifying the JWT when parsing because actual verification is done on the
// // OVC controller side. Here we do parsing solely to extract Oauth2 user name (claim "user")
// // and JWT issuer name (claim "iss")
// parser := jwt.Parser{}
// token, _, err := parser.ParseUnverified(ret_config.jwt, jwt.MapClaims{})
// if err != nil {
// return nil, err
// }
// if claims, ok := token.Claims.(jwt.MapClaims); ok {
// var tbuf bytes.Buffer
// tbuf.WriteString(claims["username"].(string))
// tbuf.WriteString("@")
// tbuf.WriteString(claims["iss"].(string))
// ret_config.decort_username = tbuf.String()
// } else {
// return nil, fmt.Errorf("Failed to extract user and iss fields from JWT token in oauth2 mode.")
// }
sdkConf := config.Config{
AppID: ret_config.app_id,
@@ -212,57 +209,57 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) {
return ret_config, nil
}
func (config *ControllerCfg) GetDecortUsername() string {
return config.decort_username
}
// func (config *ControllerCfg) GetDecortUsername() string {
// return config.decort_username
// }
func (config *ControllerCfg) getOAuth2JWT() (string, error) {
// Obtain JWT from the Oauth2 provider using application ID and application secret provided in config.
if config.auth_mode_code == MODE_UNDEF {
return "", fmt.Errorf("getOAuth2JWT method called for undefined authorization mode.")
}
if config.auth_mode_code != MODE_OAUTH2 {
return "", fmt.Errorf("getOAuth2JWT method called for incompatible authorization mode %q.", config.auth_mode_txt)
}
// func (config *ControllerCfg) getOAuth2JWT() (string, error) {
// // Obtain JWT from the Oauth2 provider using application ID and application secret provided in config.
// if config.auth_mode_code == MODE_UNDEF {
// return "", fmt.Errorf("getOAuth2JWT method called for undefined authorization mode.")
// }
// if config.auth_mode_code != MODE_OAUTH2 {
// return "", fmt.Errorf("getOAuth2JWT method called for incompatible authorization mode %q.", config.auth_mode_txt)
// }
params := url.Values{}
params.Add("grant_type", "client_credentials")
params.Add("client_id", config.app_id)
params.Add("client_secret", config.app_secret)
params.Add("response_type", "id_token")
params.Add("validity", "3600")
params_str := params.Encode()
// params := url.Values{}
// params.Add("grant_type", "client_credentials")
// params.Add("client_id", config.app_id)
// params.Add("client_secret", config.app_secret)
// params.Add("response_type", "id_token")
// params.Add("validity", "3600")
// params_str := params.Encode()
req, err := http.NewRequest("POST", config.oauth2_url+"/v1/oauth/access_token", strings.NewReader(params_str))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Content-Length", strconv.Itoa(len(params_str)))
// req, err := http.NewRequest("POST", config.oauth2_url+"/v1/oauth/access_token", strings.NewReader(params_str))
// if err != nil {
// return "", err
// }
// req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// req.Header.Set("Content-Length", strconv.Itoa(len(params_str)))
resp, err := config.cc_client.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
// fmt.Println("response Status:", resp.Status)
// fmt.Println("response Headers:", resp.Header)
// fmt.Println("response Headers:", req.URL)
return "", fmt.Errorf("getOauth2JWT: unexpected status code %d when obtaining JWT from %q for APP_ID %q, request Body %q",
resp.StatusCode, req.URL, config.app_id, params_str)
}
defer resp.Body.Close()
// resp, err := config.cc_client.Do(req)
// if err != nil {
// return "", err
// }
// if resp.StatusCode != http.StatusOK {
// // fmt.Println("response Status:", resp.Status)
// // fmt.Println("response Headers:", resp.Header)
// // fmt.Println("response Headers:", req.URL)
// return "", fmt.Errorf("getOauth2JWT: unexpected status code %d when obtaining JWT from %q for APP_ID %q, request Body %q",
// resp.StatusCode, req.URL, config.app_id, params_str)
// }
// defer resp.Body.Close()
responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// responseData, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// return "", err
// }
// validation successful - store JWT in the corresponding field of the ControllerCfg structure
config.jwt = strings.TrimSpace(string(responseData))
// // validation successful - store JWT in the corresponding field of the ControllerCfg structure
// config.jwt = strings.TrimSpace(string(responseData))
return config.jwt, nil
}
// return config.jwt, nil
// }
func (config *ControllerCfg) validateJWT(jwt string) (bool, error) {
/*

View File

@@ -735,7 +735,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
Name: d.Get("name").(string),
}
if desc, ok := d.GetOk("desc"); ok {
if desc, ok := d.GetOk("description"); ok {
req.Description = desc.(string)
}
@@ -1504,8 +1504,8 @@ func disksSubresourceSchemaMake() map[string]*schema.Schema {
},
"permanently": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
Default: true,
Description: "Disk deletion status",
},
"disk_id": {
@@ -1613,15 +1613,15 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema {
Description: "Name of this compute. Compute names are case sensitive and must be unique in the resource group.",
},
"rg_id": {
Type: schema.TypeInt,
Required: true,
Type: schema.TypeInt,
Required: true,
// ForceNew: true,
ValidateFunc: validation.IntAtLeast(1),
Description: "ID of the resource group where this compute should be deployed.",
},
"driver": {
Type: schema.TypeString,
Required: true,
Type: schema.TypeString,
Required: true,
// ForceNew: true,
StateFunc: statefuncs.StateFuncToUpper,
ValidateFunc: validation.StringInSlice([]string{"SVA_KVM_X86", "KVM_X86", "KVM_PPC"}, false), // observe case while validating

View File

@@ -97,14 +97,13 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter
setQuota = true
}
log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d",
c.GetDecortUsername(),
log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d",
// c.GetDecortUsername(),
rgName.(string), d.Get("account_id").(int))
req.AccountID = uint64(d.Get("account_id").(int))
req.Name = rgName.(string)
req.GID = uint64(location.DefaultGridID)
req.Owner = c.GetDecortUsername()
if setQuota {
req.MaxCPUCapacity = int64(quotaRecord.Cpu)
@@ -121,6 +120,11 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter
d.Set("def_net_type", "PRIVATE")
}
owner, ok := d.GetOk("owner")
if ok {
req.Owner = owner.(string)
}
ipcidr, ok := d.GetOk("ipcidr")
if ok {
req.IPCIDR = ipcidr.(string)
@@ -658,6 +662,11 @@ func ResourceRgSchemaMake() map[string]*schema.Schema {
Description: "Address of the netowrk inside the private network segment (aka ViNS) if def_net_type=PRIVATE",
},
"owner": {
Type: schema.TypeString,
Optional: true,
},
"ext_net_id": {
Type: schema.TypeInt,
Optional: true,

View File

@@ -105,14 +105,14 @@ func flattenAccRGResources(argr account.RGResuorces) []map[string]interface{} {
func flattenAccResources(r account.RecordResourceConsumption) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"current": flattenAccResource(r.Current),
"current": flattenAccResource(r.Consumed),
"reserved": flattenAccResource(r.Reserved),
}
res = append(res, temp)
return res
}
func flattenAccConsumed(c account.Consumed) []map[string]interface{} {
func flattenAccConsumed(c account.Resource) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"cpu": c.CPU,

View File

@@ -65,15 +65,14 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter
}
c := m.(*controller.ControllerCfg)
log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d",
c.GetDecortUsername(),
log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d",
// c.GetDecortUsername(),
rg_name.(string), d.Get("account_id").(int))
req := rg.CreateRequest{
AccountID: uint64(d.Get("account_id").(int)),
Name: rg_name.(string),
GID: uint64(location.DefaultGridID),
Owner: c.GetDecortUsername(),
}
// pass quota values as set
@@ -91,7 +90,10 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter
if arg_set {
req.DefNet = def_net_type.(string)
}
owner, ok := d.GetOk("owner")
if ok {
req.Owner = owner.(string)
}
ipcidr, arg_set := d.GetOk("ipcidr")
if arg_set {
req.IPCIDR = ipcidr.(string)
@@ -338,6 +340,11 @@ func ResourceResgroup() *schema.Resource {
Description: "IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0",
},
"owner": {
Type: schema.TypeString,
Optional: true,
},
/* commented out, as in this version of provider we use default Grid ID
"grid_id": {
Type: schema.TypeInt,