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

470 lines
21 KiB
Go

package provider
import (
"context"
"sort"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"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"
)
// ---------------------------------------------------------------- shared nested models
type priceModel struct {
BillingCycle types.String `tfsdk:"billing_cycle"`
Months types.Int64 `tfsdk:"months"`
Price types.Float64 `tfsdk:"price"`
SetupFee types.Float64 `tfsdk:"setup_fee"`
}
func priceAttributes() map[string]schema.Attribute {
return map[string]schema.Attribute{
"billing_cycle": schema.StringAttribute{Computed: true, MarkdownDescription: "Billing cycle, such as `monthly`."},
"months": schema.Int64Attribute{Computed: true, MarkdownDescription: "Months in the cycle, when known."},
"price": schema.Float64Attribute{Computed: true, MarkdownDescription: "Price of the cycle."},
"setup_fee": schema.Float64Attribute{Computed: true, MarkdownDescription: "Setup fee."},
}
}
func prices(in []client.Price) []priceModel {
out := make([]priceModel, 0, len(in))
for _, p := range in {
m := priceModel{BillingCycle: types.StringValue(p.BillingCycle), Price: types.Float64Value(p.Price), SetupFee: types.Float64Value(p.SetupFee), Months: types.Int64Null()}
if p.Months > 0 {
m.Months = types.Int64Value(p.Months)
}
out = append(out, m)
}
return out
}
func floatMap(in map[string]float64) map[string]types.Float64 {
out := map[string]types.Float64{}
for k, v := range in {
out[k] = types.Float64Value(v)
}
return out
}
func configure(req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) *client.Client {
return clientFrom(req.ProviderData, &resp.Diagnostics)
}
// ---------------------------------------------------------------- catalog_products
// NewCatalogProductsDataSource returns the catalog_products data source.
func NewCatalogProductsDataSource() datasource.DataSource { return &catalogProductsDS{} }
type catalogProductsDS struct{ c *client.Client }
type productItem struct {
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Kind types.String `tfsdk:"kind"`
GroupID types.Int64 `tfsdk:"group_id"`
GroupName types.String `tfsdk:"group_name"`
Currency types.String `tfsdk:"currency"`
Purchasable types.Bool `tfsdk:"purchasable"`
Prices []priceModel `tfsdk:"prices"`
}
type catalogProductsModel struct {
Kind types.String `tfsdk:"kind"`
Currency types.String `tfsdk:"currency"`
Products []productItem `tfsdk:"products"`
}
func (d *catalogProductsDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_catalog_products"
}
func (d *catalogProductsDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "The " + brand.Name + " products for sale, with the price of each billing cycle.",
Attributes: map[string]schema.Attribute{
"kind": schema.StringAttribute{Optional: true, MarkdownDescription: "Only this kind: `vps`, `dedicated`, `hosting`, `reseller_hosting`, `radio`, `ai_plan`, `extra` or `other`."},
"currency": schema.StringAttribute{Optional: true, MarkdownDescription: "Currency code of the prices, such as `USD`. Default: the account currency."},
"products": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "The products.",
NestedObject: schema.NestedAttributeObject{Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{Computed: true, MarkdownDescription: "Product id, used as `product_id`."},
"name": schema.StringAttribute{Computed: true, MarkdownDescription: "Name."},
"kind": schema.StringAttribute{Computed: true, MarkdownDescription: "Kind."},
"group_id": schema.Int64Attribute{Computed: true, MarkdownDescription: "Group id."},
"group_name": schema.StringAttribute{Computed: true, MarkdownDescription: "Group name."},
"currency": schema.StringAttribute{Computed: true, MarkdownDescription: "Currency."},
"purchasable": schema.BoolAttribute{Computed: true, MarkdownDescription: "Whether it can be bought through the API."},
"prices": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "Price of each billing cycle.",
NestedObject: schema.NestedAttributeObject{Attributes: priceAttributes()},
},
}},
},
},
}
}
func (d *catalogProductsDS) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if c := configure(req, resp); c != nil {
d.c = c
}
}
func (d *catalogProductsDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m catalogProductsModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
list, err := d.c.Products(ctx, m.Currency.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not list the products", err)
return
}
m.Products = []productItem{}
for _, p := range list {
if !m.Kind.IsNull() && m.Kind.ValueString() != "" && p.Kind != m.Kind.ValueString() {
continue
}
m.Products = append(m.Products, productItem{
ID: types.Int64Value(p.ID), Name: types.StringValue(p.Name), Kind: types.StringValue(p.Kind),
GroupID: types.Int64Value(p.Group.ID), GroupName: types.StringValue(p.Group.Name),
Currency: types.StringValue(p.Currency), Purchasable: types.BoolValue(p.Purchasable), Prices: prices(p.Prices),
})
}
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}
// ---------------------------------------------------------------- catalog_product
// NewCatalogProductDataSource returns the catalog_product data source.
func NewCatalogProductDataSource() datasource.DataSource { return &catalogProductDS{} }
type catalogProductDS struct{ c *client.Client }
type choiceItem struct {
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
}
type optionItem struct {
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
DefaultChoiceID types.Int64 `tfsdk:"default_choice_id"`
Choices []choiceItem `tfsdk:"choices"`
}
type catalogProductModel struct {
ID types.Int64 `tfsdk:"id"`
Currency types.String `tfsdk:"currency"`
Name types.String `tfsdk:"name"`
Kind types.String `tfsdk:"kind"`
GroupName types.String `tfsdk:"group_name"`
Purchasable types.Bool `tfsdk:"purchasable"`
NotPurchasableReason types.String `tfsdk:"not_purchasable_reason"`
BillingCycles []priceModel `tfsdk:"billing_cycles"`
ConfigOptions []optionItem `tfsdk:"config_options"`
}
func (d *catalogProductDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_catalog_product"
}
func (d *catalogProductDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "One " + brand.Name + " product with its billing cycles and the options the buyer picks (operating system, data center and others).",
Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{Required: true, MarkdownDescription: "Product id."},
"currency": schema.StringAttribute{Optional: true, MarkdownDescription: "Currency code of the prices. Default: the account currency."},
"name": schema.StringAttribute{Computed: true, MarkdownDescription: "Name."},
"kind": schema.StringAttribute{Computed: true, MarkdownDescription: "Kind."},
"group_name": schema.StringAttribute{Computed: true, MarkdownDescription: "Group name."},
"purchasable": schema.BoolAttribute{Computed: true, MarkdownDescription: "Whether it can be bought through the API."},
"not_purchasable_reason": schema.StringAttribute{Computed: true, MarkdownDescription: "Why it cannot be bought through the API, when it cannot."},
"billing_cycles": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "Billing cycles with a price.",
NestedObject: schema.NestedAttributeObject{Attributes: priceAttributes()},
},
"config_options": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "Options, used in `config_options` as `{ \"option id\" = choice id }`.",
NestedObject: schema.NestedAttributeObject{Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{Computed: true, MarkdownDescription: "Option id."},
"name": schema.StringAttribute{Computed: true, MarkdownDescription: "Option name."},
"default_choice_id": schema.Int64Attribute{Computed: true, MarkdownDescription: "Choice used when the option is left out."},
"choices": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "Choices.",
NestedObject: schema.NestedAttributeObject{Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{Computed: true, MarkdownDescription: "Choice id."},
"name": schema.StringAttribute{Computed: true, MarkdownDescription: "Choice name."},
}},
},
}},
},
},
}
}
func (d *catalogProductDS) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if c := configure(req, resp); c != nil {
d.c = c
}
}
func (d *catalogProductDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m catalogProductModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
p, err := d.c.Product(ctx, m.ID.ValueInt64(), m.Currency.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not read the product", err)
return
}
m.Name, m.Kind, m.GroupName = types.StringValue(p.Name), types.StringValue(p.Kind), types.StringValue(p.Group.Name)
m.Purchasable = types.BoolValue(p.Purchasable)
m.NotPurchasableReason = strOrNull(p.NotPurchasableReason)
m.BillingCycles = prices(p.BillingCycles)
m.ConfigOptions = []optionItem{}
for _, o := range p.ConfigOptions {
item := optionItem{ID: types.Int64Value(o.ID), Name: types.StringValue(o.Name), DefaultChoiceID: types.Int64Value(o.DefaultChoiceID), Choices: []choiceItem{}}
for _, ch := range o.Choices {
item.Choices = append(item.Choices, choiceItem{ID: types.Int64Value(ch.ID), Name: types.StringValue(ch.Name)})
}
m.ConfigOptions = append(m.ConfigOptions, item)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}
// ---------------------------------------------------------------- catalog_tlds
// NewCatalogTLDsDataSource returns the catalog_tlds data source.
func NewCatalogTLDsDataSource() datasource.DataSource { return &catalogTLDsDS{} }
type catalogTLDsDS struct{ c *client.Client }
type tldItem struct {
Extension types.String `tfsdk:"extension"`
Currency types.String `tfsdk:"currency"`
Register map[string]types.Float64 `tfsdk:"register"`
Renew map[string]types.Float64 `tfsdk:"renew"`
Transfer map[string]types.Float64 `tfsdk:"transfer"`
DNSManagement types.Bool `tfsdk:"dns_management"`
TransferCodeRequired types.Bool `tfsdk:"transfer_code_required"`
}
type catalogTLDsModel struct {
Extension types.String `tfsdk:"extension"`
Currency types.String `tfsdk:"currency"`
TLDs []tldItem `tfsdk:"tlds"`
}
func (d *catalogTLDsDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_catalog_tlds"
}
func (d *catalogTLDsDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
years := func(what string) schema.MapAttribute {
return schema.MapAttribute{Computed: true, ElementType: types.Float64Type, MarkdownDescription: what + " price by number of years (`\"1\"`, `\"2\"`...)."}
}
resp.Schema = schema.Schema{
MarkdownDescription: "The domain extensions sold by " + brand.Name + ", with the register, renew and transfer prices.",
Attributes: map[string]schema.Attribute{
"extension": schema.StringAttribute{Optional: true, MarkdownDescription: "Only this extension, such as `.com`."},
"currency": schema.StringAttribute{Optional: true, MarkdownDescription: "Currency code of the prices. Default: the account currency."},
"tlds": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "The extensions.",
NestedObject: schema.NestedAttributeObject{Attributes: map[string]schema.Attribute{
"extension": schema.StringAttribute{Computed: true, MarkdownDescription: "Extension."},
"currency": schema.StringAttribute{Computed: true, MarkdownDescription: "Currency."},
"register": years("Register"),
"renew": years("Renew"),
"transfer": years("Transfer"),
"dns_management": schema.BoolAttribute{Computed: true, MarkdownDescription: "DNS management available."},
"transfer_code_required": schema.BoolAttribute{Computed: true, MarkdownDescription: "A transfer needs the EPP code."},
}},
},
},
}
}
func (d *catalogTLDsDS) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if c := configure(req, resp); c != nil {
d.c = c
}
}
func (d *catalogTLDsDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m catalogTLDsModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
ext := m.Extension.ValueString()
if ext != "" && !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
list, err := d.c.TLDs(ctx, ext, m.Currency.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not list the extensions", err)
return
}
sort.Slice(list, func(i, j int) bool { return list[i].Extension < list[j].Extension })
m.TLDs = []tldItem{}
for _, t := range list {
m.TLDs = append(m.TLDs, tldItem{
Extension: types.StringValue(t.Extension), Currency: types.StringValue(t.Currency),
Register: floatMap(t.Register), Renew: floatMap(t.Renew), Transfer: floatMap(t.Transfer),
DNSManagement: types.BoolValue(t.Features.DNSManagement), TransferCodeRequired: types.BoolValue(t.Features.TransferCodeRequired),
})
}
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}
// ---------------------------------------------------------------- domain_availability
// NewDomainAvailabilityDataSource returns the domain_availability data source.
func NewDomainAvailabilityDataSource() datasource.DataSource { return &availabilityDS{} }
type availabilityDS struct{ c *client.Client }
type availabilityModel struct {
Domain types.String `tfsdk:"domain"`
Available types.Bool `tfsdk:"available"`
Status types.String `tfsdk:"status"`
Extension types.String `tfsdk:"extension"`
Currency types.String `tfsdk:"currency"`
RegisterPrice types.Float64 `tfsdk:"register_price"`
RenewPrice types.Float64 `tfsdk:"renew_price"`
TransferPrice types.Float64 `tfsdk:"transfer_price"`
PanelOnly types.Bool `tfsdk:"panel_only"`
}
func (d *availabilityDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_domain_availability"
}
func (d *availabilityDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "Whether a domain name can be registered, with the price for one year. Limit of 30 checks per minute.",
Attributes: map[string]schema.Attribute{
"domain": schema.StringAttribute{Required: true, MarkdownDescription: "Domain name, such as `example.com`."},
"available": schema.BoolAttribute{Computed: true, MarkdownDescription: "True when it can be registered."},
"status": schema.StringAttribute{Computed: true, MarkdownDescription: "`available`, `registered` or `unknown` (could not be confirmed)."},
"extension": schema.StringAttribute{Computed: true, MarkdownDescription: "Extension."},
"currency": schema.StringAttribute{Computed: true, MarkdownDescription: "Currency of the prices."},
"register_price": schema.Float64Attribute{Computed: true, MarkdownDescription: "Register price for one year."},
"renew_price": schema.Float64Attribute{Computed: true, MarkdownDescription: "Renew price for one year."},
"transfer_price": schema.Float64Attribute{Computed: true, MarkdownDescription: "Transfer price."},
"panel_only": schema.BoolAttribute{Computed: true, MarkdownDescription: "True when this name is handled in " + brand.PanelName + " and not through the API."},
},
}
}
func (d *availabilityDS) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if c := configure(req, resp); c != nil {
d.c = c
}
}
func floatOrNull(p *float64) types.Float64 {
if p == nil {
return types.Float64Null()
}
return types.Float64Value(*p)
}
func (d *availabilityDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m availabilityModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
a, err := d.c.Availability(ctx, m.Domain.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not check the domain", err)
return
}
m.Available, m.Status, m.Extension, m.Currency = types.BoolValue(a.Available), types.StringValue(a.Status), types.StringValue(a.Extension), types.StringValue(a.Currency)
m.RegisterPrice, m.RenewPrice, m.TransferPrice = floatOrNull(a.OneYearPrice.Register), floatOrNull(a.OneYearPrice.Renew), floatOrNull(a.OneYearPrice.Transfer)
m.PanelOnly = types.BoolValue(a.PortalOnly)
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}
// ---------------------------------------------------------------- servers
// NewServersDataSource returns the servers data source.
func NewServersDataSource() datasource.DataSource { return &serversDS{} }
type serversDS struct{ c *client.Client }
type serverItem struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
Product types.String `tfsdk:"product"`
IP types.String `tfsdk:"ip"`
PowerState types.String `tfsdk:"power_state"`
}
type serversModel struct {
Status types.String `tfsdk:"status"`
Servers []serverItem `tfsdk:"servers"`
}
func (d *serversDS) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_servers"
}
func (d *serversDS) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "The active and suspended VPS servers of the account.",
Attributes: map[string]schema.Attribute{
"status": schema.StringAttribute{Optional: true, MarkdownDescription: "Only this status: `active` or `suspended`."},
"servers": schema.ListNestedAttribute{
Computed: true, MarkdownDescription: "The servers, newest first.",
NestedObject: schema.NestedAttributeObject{Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true, MarkdownDescription: "Server id, used as `server_id` (as a number) or to import."},
"name": schema.StringAttribute{Computed: true, MarkdownDescription: "Name."},
"status": schema.StringAttribute{Computed: true, MarkdownDescription: "Status."},
"product": schema.StringAttribute{Computed: true, MarkdownDescription: "Plan name."},
"ip": schema.StringAttribute{Computed: true, MarkdownDescription: "Main IP address."},
"power_state": schema.StringAttribute{Computed: true, MarkdownDescription: "Power state, from a copy up to a minute old."},
}},
},
},
}
}
func (d *serversDS) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if c := configure(req, resp); c != nil {
d.c = c
}
}
func (d *serversDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var m serversModel
resp.Diagnostics.Append(req.Config.Get(ctx, &m)...)
if resp.Diagnostics.HasError() {
return
}
list, err := d.c.Servers(ctx, m.Status.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not list the servers", err)
return
}
m.Servers = []serverItem{}
for _, s := range list {
m.Servers = append(m.Servers, serverItem{
ID: types.StringValue(strconv.FormatInt(s.ID, 10)), Name: types.StringValue(s.Name), Status: types.StringValue(s.Status),
Product: types.StringValue(s.Product), IP: types.StringValue(s.IP), PowerState: types.StringValue(s.PowerState),
})
}
resp.Diagnostics.Append(resp.State.Set(ctx, &m)...)
}