Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ability to set specific context fields #11

Merged
merged 2 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cloud/instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ type Template struct {
MemoryMax string
MemoryResizeMode string
MemorySlots string
Name string
NIC []NIC
NICAlias []NICAlias
NICDefault string
Expand Down Expand Up @@ -156,6 +157,7 @@ type Context struct {
Network bool
SSHPublicKey string
Target string
ProjectName string
}

// OS is the API payload based on the legacy xmlrpc backend.
Expand Down
66 changes: 43 additions & 23 deletions cloud/instance/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,35 +232,55 @@ func newInstanceContext(m map[string]any) (*Context, error) {
var dst Context

for key, value := range m {
if v, ok := value.(string); ok {
switch key {
case "DISK_ID":
n, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("invalid DISK_ID value %q: %w", v, err)
}
dst.DiskID = n
case "FIRMWARE":
dst.Firmware = v
case "GUESTOS":
dst.GuestOS = v
case "NETWORK":
b, err := api.Str2Bool(v)
if err != nil {
return nil, fmt.Errorf("invalid NETWORK value %q: %w", v, err)
}
dst.Network = b
case "SSH_PUBLIC_KEY":
dst.SSHPublicKey = v
case "TARGET":
dst.Target = v
}
err := dst.Set(key, value)
if err != nil {
return nil, err
}
}

return &dst, nil
}

// Set sets a key:value for the given context
// The key must match known fields and named with capital letters with underscores
// e.g. DISK_ID, SSH_PUBLIC_KEY, etc.
func (c *Context) Set(key string, value any) error {
return setContextValue(c, key, value)
}

func setContextValue(dst *Context, key string, value any) error {
if v, ok := value.(string); ok {
switch key {
case "DISK_ID":
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("invalid DISK_ID value %q: %w", v, err)
}
dst.DiskID = n
case "FIRMWARE":
dst.Firmware = v
case "GUESTOS":
dst.GuestOS = v
case "NETWORK":
b, err := api.Str2Bool(v)
if err != nil {
return fmt.Errorf("invalid NETWORK value %q: %w", v, err)
}
dst.Network = b
case "SSH_PUBLIC_KEY":
dst.SSHPublicKey = v
case "TARGET":
dst.Target = v
case "PROJECT_NAME":
dst.ProjectName = v
default:
return fmt.Errorf("unknown key: %s", key)
}
}

return nil
}

func newInstanceCPUModel(m map[string]any) *CPUModel {
var dst CPUModel

Expand Down
Loading