From a0dc6410a0faebea4e564daa691275d9d0bbe817 Mon Sep 17 00:00:00 2001 From: ManInDark <61268856+ManInDark@users.noreply.github.com> Date: Sat, 31 Jan 2026 00:45:23 +0100 Subject: [PATCH] feat: working create --- go.mod | 7 ++ go.sum | 1 + proxmox.go | 151 +++++++++++++++++++++++++++++++++++++---- proxmox_test.go | 95 ++++++++++++++++++++++++++ schema/pkl/proxmox.pkl | 5 +- 5 files changed, 244 insertions(+), 15 deletions(-) create mode 100644 proxmox_test.go diff --git a/go.mod b/go.mod index 37d79df..b570aea 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,12 @@ require ( github.com/platform-engineering-labs/formae/pkg/plugin-conformance-tests v0.1.9 ) +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + require ( ergo.services/actor/statemachine v0.0.0-20251202053101-c0aa08b403e5 // indirect ergo.services/ergo v1.999.310 // indirect @@ -20,6 +26,7 @@ require ( github.com/masterminds/semver v1.5.0 // indirect github.com/platform-engineering-labs/formae/pkg/api/model v0.1.1 // indirect github.com/platform-engineering-labs/formae/pkg/model v0.1.2 // indirect + github.com/stretchr/testify v1.11.1 github.com/theory/jsonpath v0.10.2 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect diff --git a/go.sum b/go.sum index f882214..e59a4a3 100644 --- a/go.sum +++ b/go.sum @@ -89,5 +89,6 @@ google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/proxmox.go b/proxmox.go index b64137a..d81d0df 100644 --- a/proxmox.go +++ b/proxmox.go @@ -5,13 +5,77 @@ package main import ( + "bytes" "context" + "encoding/json" "errors" + "fmt" + "io" + "log" + "net/http" + "os" + "strconv" "github.com/platform-engineering-labs/formae/pkg/plugin" "github.com/platform-engineering-labs/formae/pkg/plugin/resource" ) +// https://pve.proxmox.com/pve-docs/api-viewer/ +type TargetConfig struct { + URL string `json:"url"` + NODE string `json:"node"` +} + +type LXCProperties struct { + VMID int `json:"vmid"` + NAME string `json:"name"` + DESCRIPTION string `json:"description"` + OSTEMPLATE string `json:"ostemplate"` +} + +func parseTargetConfig(data json.RawMessage) (*TargetConfig, error) { + var cfg TargetConfig + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("invalid target config: %w", err) + } + if cfg.URL == "" { + return nil, fmt.Errorf("target config missing 'url'") + } + if cfg.NODE == "" { + return nil, fmt.Errorf("target config missing 'node'") + } + return &cfg, nil +} + +func getCredentials() (username, token string, err error) { + username = os.Getenv("PROXMOX_USERNAME") + token = os.Getenv("PROXMOX_TOKEN") + if username == "" { + return "", "", fmt.Errorf("PROXMOX_USERNAME not set") + } + if token == "" { + return "", "", fmt.Errorf("PROXMOX_TOKEN not set") + } + return username, token, nil +} + +func parseLXCProperties(data json.RawMessage) (*LXCProperties, error) { + var props LXCProperties + if err := json.Unmarshal(data, &props); err != nil { + return nil, fmt.Errorf("invalid file properties: %w", err) + } + if props.VMID == 0 { + return nil, fmt.Errorf("vmid missing") + } + if props.NAME == "" { + return nil, fmt.Errorf("name missing") + } + if props.OSTEMPLATE == "" { + return nil, fmt.Errorf("ostemplate missing") + } + return &props, nil +} + // ErrNotImplemented is returned by stub methods that need implementation. var ErrNotImplemented = errors.New("not implemented") @@ -58,7 +122,7 @@ func (p *Plugin) LabelConfig() plugin.LabelConfig { return plugin.LabelConfig{ // Default JSONPath query to extract label from resources // Example for tagged resources: $.Tags[?(@.Key=='Name')].Value - DefaultQuery: "$.Name", // TODO: Adjust for your provider + DefaultQuery: "$.name", // Override for specific resource types ResourceOverrides: map[string]string{ @@ -73,24 +137,83 @@ func (p *Plugin) LabelConfig() plugin.LabelConfig { // Create provisions a new resource. func (p *Plugin) Create(ctx context.Context, req *resource.CreateRequest) (*resource.CreateResult, error) { - // TODO: Implement resource creation - // - // 1. Parse req.Properties to get resource configuration (json.RawMessage) - // 2. Parse req.TargetConfig to get provider credentials/config - // 3. Call your provider's API to create the resource - // 4. Return ProgressResult with: - // - NativeID: the provider's identifier for the resource - // - OperationStatus: Success, Failure, or InProgress - // - If InProgress, set RequestID for status polling + + log.Println(req.Properties) + + props, err := parseLXCProperties(req.Properties) + if err != nil { + log.Println(err.Error()) + return &resource.CreateResult{ + ProgressResult: &resource.ProgressResult{ + Operation: resource.OperationCreate, + OperationStatus: resource.OperationStatusFailure, + ErrorCode: resource.OperationErrorCodeInvalidRequest, + StatusMessage: err.Error(), + }, + }, nil + } + + log.Println("LXC Properties: ", props.VMID, props.NAME, props.OSTEMPLATE, props.DESCRIPTION) + + config, err := parseTargetConfig(req.TargetConfig) + if err != nil { + return &resource.CreateResult{ + ProgressResult: &resource.ProgressResult{ + Operation: resource.OperationCreate, + OperationStatus: resource.OperationStatusFailure, + ErrorCode: resource.OperationErrorCodeInternalFailure, + StatusMessage: err.Error(), + }, + }, nil + } + + username, token, err := getCredentials() + if err != nil { + return &resource.CreateResult{ + ProgressResult: &resource.ProgressResult{ + Operation: resource.OperationCreate, + OperationStatus: resource.OperationStatusFailure, + ErrorCode: resource.OperationErrorCodeInternalFailure, + StatusMessage: err.Error(), + }, + }, nil + } + + client := &http.Client{} + + // data := map[string]any{"node": config.NODE, "ostemplate": props.OSTEMPLATE, "id": props.VMID, "hostname": props.NAME, "description": props.DESCRIPTION} + // jsonBody, err := json.Marshal(data) + + arguments := "vmid=" + strconv.Itoa(props.VMID) + "&ostemplate=" + props.OSTEMPLATE + "&hostname=" + props.NAME + + request, err := http.NewRequest("POST", config.URL+"/api2/json/nodes/"+config.NODE+"/lxc", bytes.NewBuffer([]byte(arguments))) + request.Header.Set("Authorization", "PVEAPIToken="+username+"="+token) + + resp, err := client.Do(request) + + if err != nil { + return &resource.CreateResult{ + ProgressResult: &resource.ProgressResult{ + Operation: resource.OperationCreate, + OperationStatus: resource.OperationStatusFailure, + ErrorCode: resource.OperationErrorCodeInternalFailure, + StatusMessage: err.Error(), + }, + }, nil + } + + body, err := io.ReadAll(resp.Body) + + log.Println("Response StatusCode: ", resp.Status) + log.Println("Response Body: ", string(body)) return &resource.CreateResult{ ProgressResult: &resource.ProgressResult{ Operation: resource.OperationCreate, - OperationStatus: resource.OperationStatusFailure, - ErrorCode: resource.OperationErrorCodeInternalFailure, - StatusMessage: "Create not implemented", + OperationStatus: resource.OperationStatusSuccess, + NativeID: strconv.Itoa(props.VMID), }, - }, ErrNotImplemented + }, nil } // Read retrieves the current state of a resource. diff --git a/proxmox_test.go b/proxmox_test.go new file mode 100644 index 0000000..8d64400 --- /dev/null +++ b/proxmox_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "encoding/json" + "io" + "net/http" + "os" + "testing" + "time" + + "github.com/platform-engineering-labs/formae/pkg/plugin/resource" + "github.com/stretchr/testify/require" +) + +func testTargetConfig() json.RawMessage { + return json.RawMessage(`{"url": "https://proxmox.mid:8006", "node": "proxmox"}`) +} + +type LXC struct { + VMID int `json:"vmid"` + NAME string `json:"name"` +} + +type RESP_DATA struct { + DATA []LXC `json:"data"` +} + +func TestCreate(t *testing.T) { + username := os.Getenv("PROXMOX_USERNAME") + token := os.Getenv("PROXMOX_TOKEN") + if username == "" { + t.Skip("PROXMOX_USERNAME not set") + } + if token == "" { + t.Skip("PROXMOX_TOKEN not set") + } + + plugin := &Plugin{} + ctx := context.Background() + + properties := map[string]any{ + "vmid": 200, + "name": "testlxc", + "description": "none", + "ostemplate": "local:vztmpl/alpine-3.22-default_20250617_amd64.tar.xz", + } + + propertiesJSON, err := json.Marshal(properties) + + require.NoError(t, err, "failed to marshal properties") + + req := &resource.CreateRequest{ + ResourceType: "PROXMOX::Service::LXC", + Label: "test-create", + Properties: propertiesJSON, + TargetConfig: testTargetConfig(), + } + + config, err := parseTargetConfig(testTargetConfig()) + + result, err := plugin.Create(ctx, req) + + require.NoError(t, err, "Create should not return error") + require.NotNil(t, result.ProgressResult, "Create should return ProgressResult") + + require.Eventually(t, func() bool { + client := &http.Client{} + + var props RESP_DATA + + request, err := http.NewRequest("GET", config.URL+"/api2/json/nodes/"+config.NODE+"/lxc", nil) + if err != nil { + t.Logf("Something unexpected happened") + return false + } + request.Header.Set("Authorization", "PVEAPIToken="+username+"="+token) + + resp, err := client.Do(request) + + data, err := io.ReadAll(resp.Body) + json.Unmarshal(data, &props) + + for i := 0; i < len(props.DATA); i++ { + lxccontainer := props.DATA[i] + t.Logf("Found container: %s", lxccontainer.NAME) + if lxccontainer.VMID == 200 { + t.Logf("Created Successfully: %s", lxccontainer.NAME) + return true + } + } + + return false + }, 10*time.Second, time.Second, "Create operation should complete successfully") +} diff --git a/schema/pkl/proxmox.pkl b/schema/pkl/proxmox.pkl index 3e66c02..f4108f4 100644 --- a/schema/pkl/proxmox.pkl +++ b/schema/pkl/proxmox.pkl @@ -1,4 +1,4 @@ -module proxmox.lxc +module proxmox import "@formae/formae.pkl" @@ -12,6 +12,9 @@ class ExampleResource extends formae.Resource { @formae.FieldHint { createOnly = true } vmid: String + @formae.FieldHint { createOnly = true } + ostemplate: String + @formae.FieldHint {} name: String