terraform-provider-mozout/internal/provider/resource_vps.go
2026-11-28 15:28:08 +02:00

521 lines
21 KiB
Go

package provider
import (
"context"
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/mozout-com/terraform-provider-mozout/internal/brand"
"github.com/mozout-com/terraform-provider-mozout/internal/client"
)
var (
_ resource.Resource = &vpsResource{}
_ resource.ResourceWithConfigure = &vpsResource{}
_ resource.ResourceWithImportState = &vpsResource{}
_ resource.ResourceWithValidateConfig = &vpsResource{}
)
// NewVPSResource returns the VPS resource.
func NewVPSResource() resource.Resource { return &vpsResource{} }
type vpsResource struct{ c *client.Client }
type vpsModel struct {
ID types.String `tfsdk:"id"`
ServerID types.Int64 `tfsdk:"server_id"`
ProductID types.Int64 `tfsdk:"product_id"`
BillingCycle types.String `tfsdk:"billing_cycle"`
ConfigOptions types.Map `tfsdk:"config_options"`
PromoCode types.String `tfsdk:"promo_code"`
PowerState types.String `tfsdk:"power_state"`
Timezone types.String `tfsdk:"timezone"`
ReverseDNS types.Map `tfsdk:"reverse_dns"`
WaitMinutes types.Int64 `tfsdk:"wait_minutes"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
Product types.String `tfsdk:"product"`
IP types.String `tfsdk:"ip"`
AdditionalIPs types.List `tfsdk:"additional_ips"`
OperatingSystem types.String `tfsdk:"operating_system"`
Location types.String `tfsdk:"location"`
VCPU types.Int64 `tfsdk:"vcpu"`
RAMGB types.Int64 `tfsdk:"ram_gb"`
DiskGB types.Int64 `tfsdk:"disk_gb"`
NextDueDate types.String `tfsdk:"next_due_date"`
OrderID types.Int64 `tfsdk:"order_id"`
InvoiceID types.Int64 `tfsdk:"invoice_id"`
Simulated types.Bool `tfsdk:"simulated"`
}
func (r *vpsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_vps"
}
func (r *vpsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
keep := []planmodifier.String{stringplanmodifier.UseStateForUnknown()}
keepInt := []planmodifier.Int64{int64planmodifier.UseStateForUnknown()}
resp.Schema = schema.Schema{
MarkdownDescription: "A " + brand.Name + " VPS. Set `product_id` and `billing_cycle` to buy a new server with credit, or `server_id` " +
"to manage a server you already have. Destroying only removes it from the state: the API cannot cancel services, " +
"use " + brand.PanelName + " for that. With a `sandbox_` key the purchase is simulated and nothing is created.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true, MarkdownDescription: "Server id (the same as its service id).",
PlanModifiers: keep,
},
"server_id": schema.Int64Attribute{
Optional: true, Computed: true,
MarkdownDescription: "Id of a server you already have. Set it to manage that server instead of buying one.",
PlanModifiers: []planmodifier.Int64{int64planmodifier.UseStateForUnknown(), int64planmodifier.RequiresReplace()},
},
"product_id": schema.Int64Attribute{
Optional: true, MarkdownDescription: "Catalog product to buy (see the `" + brand.TypeName + "_catalog_products` data source, `kind = \"vps\"`).",
PlanModifiers: []planmodifier.Int64{lockedInt64{}},
},
"billing_cycle": schema.StringAttribute{
Optional: true, MarkdownDescription: "Billing cycle of the purchase: `monthly`, `quarterly`, `semi_annually`, `annually`, `biennially` or `triennially`.",
Validators: []validator.String{stringOneOf("monthly", "quarterly", "semi_annually", "annually", "biennially", "triennially")},
PlanModifiers: []planmodifier.String{lockedString{}},
},
"config_options": schema.MapAttribute{
Optional: true, ElementType: types.Int64Type,
MarkdownDescription: "Choices of the purchase, as `{ \"option id\" = choice id }` (see the `" + brand.TypeName + "_catalog_product` data source). Options left out get the first choice.",
PlanModifiers: []planmodifier.Map{lockedMap{}},
},
"promo_code": schema.StringAttribute{
Optional: true, MarkdownDescription: "Promo code for the purchase.",
PlanModifiers: []planmodifier.String{lockedString{}},
},
"power_state": schema.StringAttribute{
Optional: true, Computed: true,
MarkdownDescription: "Wanted power state: `running` or `stopped`. When not set, it is only read.",
Validators: []validator.String{stringOneOf("running", "stopped")},
PlanModifiers: keep,
},
"timezone": schema.StringAttribute{
Optional: true, Computed: true,
MarkdownDescription: "Time zone of the server, such as `UTC`. The list is in the API (`GET /v1/servers/{id}/timezone`).",
PlanModifiers: keep,
},
"reverse_dns": schema.MapAttribute{
Optional: true, ElementType: types.StringType,
MarkdownDescription: "Reverse DNS name of each IP of the server, as `{ \"ip\" = \"hostname\" }`. Only the IPs listed here are managed. An empty name goes back to the default one.",
},
"wait_minutes": schema.Int64Attribute{
Optional: true, Computed: true, Default: int64default.StaticInt64(30),
MarkdownDescription: "How long to wait for a new server to be ready and for power actions to finish. Default 30.",
},
"name": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Server name."},
"status": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Service status, such as `active` or `suspended`."},
"product": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Plan name."},
"ip": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Main IP address."},
"additional_ips": schema.ListAttribute{Computed: true, ElementType: types.StringType, PlanModifiers: []planmodifier.List{listplanmodifier.UseStateForUnknown()}, MarkdownDescription: "Other IP addresses."},
"operating_system": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Operating system and version."},
"location": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Data center."},
"vcpu": schema.Int64Attribute{Computed: true, PlanModifiers: keepInt, MarkdownDescription: "Virtual CPUs."},
"ram_gb": schema.Int64Attribute{Computed: true, PlanModifiers: keepInt, MarkdownDescription: "Memory in GB."},
"disk_gb": schema.Int64Attribute{Computed: true, PlanModifiers: keepInt, MarkdownDescription: "Disk in GB."},
"next_due_date": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Next renewal date."},
"order_id": schema.Int64Attribute{Computed: true, PlanModifiers: keepInt, MarkdownDescription: "Order of the purchase (only when bought by Terraform)."},
"invoice_id": schema.Int64Attribute{Computed: true, PlanModifiers: keepInt, MarkdownDescription: "Invoice of the purchase (only when bought by Terraform)."},
"simulated": schema.BoolAttribute{Computed: true, MarkdownDescription: "True when the purchase was simulated (`sandbox_` key): no server exists."},
},
}
}
func (r *vpsResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if c := clientFrom(req.ProviderData, &resp.Diagnostics); c != nil {
r.c = c
}
}
func (r *vpsResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var m vpsModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
if m.ServerID.IsUnknown() || m.ProductID.IsUnknown() {
return
}
if !m.ServerID.IsNull() && !m.ProductID.IsNull() {
resp.Diagnostics.AddError("Conflicting settings", "Set server_id to manage an existing server, or product_id to buy one, not both.")
}
if m.ServerID.IsNull() && m.ProductID.IsNull() {
resp.Diagnostics.AddError("Missing settings", "Set product_id and billing_cycle to buy a server, or server_id to manage an existing one.")
}
if !m.ProductID.IsNull() && m.BillingCycle.IsNull() {
resp.Diagnostics.AddAttributeError(path.Root("billing_cycle"), "Missing billing cycle", "billing_cycle is required with product_id.")
}
}
func (r *vpsResource) wait(m *vpsModel) time.Duration {
n := m.WaitMinutes.ValueInt64()
if n <= 0 {
n = 30
}
return time.Duration(n) * time.Minute
}
func (r *vpsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan vpsModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
plan.Simulated = types.BoolValue(false)
plan.OrderID = types.Int64Null()
plan.InvoiceID = types.Int64Null()
var id int64
adopted := !plan.ServerID.IsNull() && !plan.ServerID.IsUnknown()
if adopted {
id = plan.ServerID.ValueInt64()
} else {
body := map[string]interface{}{
"product_id": plan.ProductID.ValueInt64(),
"billing_cycle": plan.BillingCycle.ValueString(),
}
if !plan.ConfigOptions.IsNull() && !plan.ConfigOptions.IsUnknown() {
opts := map[string]int64{}
resp.Diagnostics.Append(plan.ConfigOptions.ElementsAs(ctx, &opts, false)...)
if resp.Diagnostics.HasError() {
return
}
body["config_options"] = opts
}
if !plan.PromoCode.IsNull() && plan.PromoCode.ValueString() != "" {
body["promo_code"] = plan.PromoCode.ValueString()
}
p, err := r.c.Purchase(ctx, body, client.NewIdempotencyKey())
if err != nil {
apiError(&resp.Diagnostics, "Could not buy the server", err)
return
}
if p.OrderID != 0 {
plan.OrderID = types.Int64Value(p.OrderID)
}
if p.InvoiceID != 0 {
plan.InvoiceID = types.Int64Value(p.InvoiceID)
}
if p.Simulated {
// Sandbox: nothing was created. Keep a placeholder so the plan can be tested end to end.
plan.Simulated = types.BoolValue(true)
plan.ID = types.StringValue("simulated-" + p.ActionID)
plan.ServerID = types.Int64Value(0)
fillUnknownVPS(&plan)
resp.Diagnostics.AddWarning("Simulated purchase", "The API key is a sandbox_ key: the purchase was simulated and no server exists.")
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
id = p.ServiceID
if id == 0 && p.ActionID != "" {
if _, err := r.c.WaitAction(ctx, p.ActionID, r.wait(&plan)); err != nil {
resp.Diagnostics.AddWarning("Purchase still in progress", err.Error())
}
}
if id == 0 {
resp.Diagnostics.AddError("Purchase without a server", fmt.Sprintf(
"The purchase was accepted (order %d, invoice %d) but the API did not give a server id. Check it in %s and import it with server_id.",
p.OrderID, p.InvoiceID, brand.PanelName))
return
}
}
plan.ID = types.StringValue(strconv.FormatInt(id, 10))
plan.ServerID = types.Int64Value(id)
var srv *client.Server
var err error
if adopted {
if srv, err = r.c.Server(ctx, id); err != nil {
apiError(&resp.Diagnostics, "Could not read the server", err)
return
}
} else if srv, err = r.waitServer(ctx, id, r.wait(&plan)); err != nil {
// Save what we know: the server was paid for and must stay in the state.
fillUnknownVPS(&plan)
resp.Diagnostics.AddWarning("Server not ready yet", err.Error()+" It stays in the state; run terraform apply again later.")
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
// Errors here must not lose the server from the state (a tainted resource would buy another one),
// so after a purchase they become warnings and the next apply tries again.
var steps diag.Diagnostics
r.apply(ctx, &plan, nil, srv, &steps)
for _, d := range steps {
if adopted || d.Severity() != diag.SeverityError {
resp.Diagnostics.Append(d)
} else {
resp.Diagnostics.AddWarning(d.Summary(), d.Detail()+" The server is saved in the state; run terraform apply again.")
}
}
if resp.Diagnostics.HasError() {
return
}
fillUnknownVPS(&plan)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
// waitServer waits until GET /v1/servers/{id} answers with an active server.
func (r *vpsResource) waitServer(ctx context.Context, id int64, timeout time.Duration) (*client.Server, error) {
deadline := time.Now().Add(timeout)
for {
srv, err := r.c.Server(ctx, id)
if err == nil && srv.Status == "active" && srv.PowerState != "unknown" {
return srv, nil
}
if err != nil && !client.IsNotFound(err) {
return nil, err
}
if time.Now().After(deadline) {
if err == nil {
return srv, nil
}
return nil, fmt.Errorf("server %d is not ready after %s", id, timeout)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(20 * time.Second):
}
}
}
// apply brings power state, time zone and reverse DNS to the plan and fills the computed values.
// It does every step it can and reports the failures in diags; the caller decides how to save the state.
func (r *vpsResource) apply(ctx context.Context, plan, state *vpsModel, srv *client.Server, diags *diag.Diagnostics) {
id := plan.ServerID.ValueInt64()
if want := plan.PowerState.ValueString(); !plan.PowerState.IsNull() && !plan.PowerState.IsUnknown() && want != normPower(srv.PowerState, "") {
action := "start"
if want == "stopped" {
action = "stop"
}
a, err := r.c.Power(ctx, id, action)
switch {
case err != nil && !client.HasCode(err, "already_running") && !client.HasCode(err, "already_stopped"):
apiError(diags, "Could not "+action+" the server", err)
case err == nil && !a.Simulated && a.ActionID != "":
if _, err := r.c.WaitAction(ctx, a.ActionID, r.wait(plan)); err != nil {
diags.AddWarning("Power action not confirmed", err.Error())
}
}
}
if !plan.Timezone.IsNull() && !plan.Timezone.IsUnknown() {
current := ""
if state != nil {
current = state.Timezone.ValueString()
} else if tz, _, err := r.c.Timezone(ctx, id); err == nil {
current = tz
}
if plan.Timezone.ValueString() != current {
if _, err := r.c.SetTimezone(ctx, id, plan.Timezone.ValueString()); err != nil {
apiError(diags, "Could not change the time zone", err)
}
}
}
if !plan.ReverseDNS.IsNull() && !plan.ReverseDNS.IsUnknown() {
want := map[string]string{}
diags.Append(plan.ReverseDNS.ElementsAs(ctx, &want, false)...)
if have, err := r.c.ReverseDNS(ctx, id); err != nil {
apiError(diags, "Could not read the reverse DNS", err)
} else {
changed := map[string]string{}
for ip, h := range want {
if have[ip] != h {
changed[ip] = h
}
}
if len(changed) > 0 {
if err := r.c.SetReverseDNS(ctx, id, changed); err != nil {
apiError(diags, "Could not change the reverse DNS", err)
}
}
}
}
if fresh, err := r.c.Server(ctx, id); err == nil {
srv = fresh
}
fillVPS(plan, srv)
// A wanted power state is kept as it is: the copy of the state the API reads can be up to a minute old.
if plan.PowerState.IsNull() || plan.PowerState.IsUnknown() {
plan.PowerState = types.StringValue(normPower(srv.PowerState, "unknown"))
}
if plan.Timezone.IsUnknown() {
if tz, _, err := r.c.Timezone(ctx, id); err == nil && tz != "" {
plan.Timezone = types.StringValue(tz)
} else {
plan.Timezone = types.StringNull()
}
}
}
func (r *vpsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var st vpsModel
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if resp.Diagnostics.HasError() {
return
}
if st.Simulated.ValueBool() {
return // sandbox placeholder: nothing to read
}
id, err := strconv.ParseInt(st.ID.ValueString(), 10, 64)
if err != nil {
resp.Diagnostics.AddError("Invalid id", "The server id must be a number, got "+st.ID.ValueString())
return
}
srv, err := r.c.Server(ctx, id)
if client.IsNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
if err != nil {
apiError(&resp.Diagnostics, "Could not read the server", err)
return
}
st.ServerID = types.Int64Value(id)
fillVPS(&st, srv)
st.PowerState = types.StringValue(normPower(srv.PowerState, st.PowerState.ValueString()))
if tz, _, err := r.c.Timezone(ctx, id); err == nil {
if tz == "" {
st.Timezone = types.StringNull()
} else {
st.Timezone = types.StringValue(tz)
}
}
if !st.ReverseDNS.IsNull() {
managed := map[string]string{}
resp.Diagnostics.Append(st.ReverseDNS.ElementsAs(ctx, &managed, false)...)
if have, err := r.c.ReverseDNS(ctx, id); err == nil {
for ip := range managed {
managed[ip] = have[ip]
}
st.ReverseDNS, _ = types.MapValueFrom(ctx, types.StringType, managed)
}
}
if st.WaitMinutes.IsNull() {
st.WaitMinutes = types.Int64Value(30)
}
if st.Simulated.IsNull() {
st.Simulated = types.BoolValue(false)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
}
func (r *vpsResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan, st vpsModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if resp.Diagnostics.HasError() {
return
}
plan.ID, plan.ServerID, plan.OrderID, plan.InvoiceID, plan.Simulated = st.ID, st.ServerID, st.OrderID, st.InvoiceID, st.Simulated
if st.Simulated.ValueBool() {
fillUnknownVPS(&plan)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
srv, err := r.c.Server(ctx, st.ServerID.ValueInt64())
if err != nil {
apiError(&resp.Diagnostics, "Could not read the server", err)
return
}
r.apply(ctx, &plan, &st, srv, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
fillUnknownVPS(&plan)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *vpsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var st vpsModel
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if st.Simulated.ValueBool() {
return
}
resp.Diagnostics.AddWarning("Server kept in the account", removedFromStateWarning)
}
func (r *vpsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
id, err := strconv.ParseInt(req.ID, 10, 64)
if err != nil {
resp.Diagnostics.AddError("Invalid import id", "Use the server id, a number, such as 12345.")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), strconv.FormatInt(id, 10))...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("server_id"), id)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("wait_minutes"), int64(30))...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("simulated"), false)...)
}
// normPower maps the power states of the API to running or stopped; other states keep the fallback.
func normPower(s, fallback string) string {
switch s {
case "running", "starting", "restarting":
return "running"
case "stopped", "stopping":
return "stopped"
}
if fallback == "" {
return s
}
return fallback
}
func fillVPS(m *vpsModel, s *client.Server) {
m.Name = types.StringValue(s.Name)
m.Status = types.StringValue(s.Status)
m.Product = types.StringValue(s.Product)
m.IP = types.StringValue(s.IP)
m.AdditionalIPs = listOfStrings(s.AdditionalIPs)
osName := s.OperatingSystem.Name
if s.OperatingSystem.Version != "" {
osName += " " + s.OperatingSystem.Version
}
m.OperatingSystem = types.StringValue(osName)
m.Location = types.StringValue(s.Location)
m.VCPU = types.Int64Value(s.Resources.VCPU)
m.RAMGB = types.Int64Value(s.Resources.RAMGB)
m.DiskGB = types.Int64Value(s.Resources.DiskGB)
m.NextDueDate = strOrNull(s.NextDueDate)
}
// fillUnknownVPS turns the computed values still unknown into nulls, so the state can be saved.
func fillUnknownVPS(m *vpsModel) {
for _, v := range []*types.String{&m.Name, &m.Status, &m.Product, &m.IP, &m.OperatingSystem, &m.Location, &m.NextDueDate, &m.PowerState, &m.Timezone} {
if v.IsUnknown() {
*v = types.StringNull()
}
}
for _, v := range []*types.Int64{&m.VCPU, &m.RAMGB, &m.DiskGB, &m.OrderID, &m.InvoiceID, &m.ServerID} {
if v.IsUnknown() {
*v = types.Int64Null()
}
}
if m.AdditionalIPs.IsUnknown() {
m.AdditionalIPs = types.ListNull(types.StringType)
}
if m.Simulated.IsUnknown() {
m.Simulated = types.BoolValue(false)
}
}