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

Add session data source #6

Merged
merged 7 commits into from
Jul 20, 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
212 changes: 212 additions & 0 deletions internal/provider/bgpsession_datasource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
package provider

import (
"context"
"fmt"

"github.com/ffddorf/terraform-provider-netbox-bgp/client"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/types"
)

// Ensure provider defined types fully satisfy framework interfaces.
var _ datasource.DataSource = &SessionDataSource{}

func NewSessionDataSource() datasource.DataSource {
return &SessionDataSource{}
}

type SessionDataSource struct {
client *client.Client
}

type SessionDataSourceModel struct {
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
Comments types.String `tfsdk:"comments"`
Status types.String `tfsdk:"status"`

Site *NestedSite `tfsdk:"site"`
Tenant *NestedTenant `tfsdk:"tenant"`
Device *NestedDevice `tfsdk:"device"`

LocalAddress *NestedIPAddress `tfsdk:"local_address"`
RemoteAddress *NestedIPAddress `tfsdk:"remote_address"`
LocalAS *NestedASN `tfsdk:"local_as"`
RemoteAS *NestedASN `tfsdk:"remote_as"`
PeerGroup *NestedBGPPeerGroup `tfsdk:"peer_group"`

ImportPolicyIDs types.List `tfsdk:"import_policy_ids"`
ExportPolicyIDs types.List `tfsdk:"export_policy_ids"`

PrefixListIn *NestedPrefixList `tfsdk:"prefix_list_in"`
PrefixListOut *NestedPrefixList `tfsdk:"prefix_list_out"`

Tags types.List `tfsdk:"tags"`
}

func (m *SessionDataSourceModel) FillFromAPIModel(ctx context.Context, resp *client.BGPSession, diags diag.Diagnostics) {
m.ID = maybeInt64Value(resp.Id)
m.Comments = maybeStringValue(resp.Comments)
m.Description = maybeStringValue(resp.Description)
m.Device = NestedDeviceFromAPI(resp.Device)
if resp.ExportPolicies != nil && len(*resp.ExportPolicies) > 0 {
var ds diag.Diagnostics
m.ExportPolicyIDs, ds = types.ListValueFrom(ctx, types.Int64Type, resp.ExportPolicies)
for _, d := range ds {
diags.Append(diag.WithPath(path.Root("export_policy_ids"), d))
}
}
if resp.ImportPolicies != nil && len(*resp.ImportPolicies) > 0 {
var ds diag.Diagnostics
m.ImportPolicyIDs, ds = types.ListValueFrom(ctx, types.Int64Type, resp.ImportPolicies)
for _, d := range ds {
diags.Append(diag.WithPath(path.Root("import_policy_ids"), d))
}
}
m.LocalAddress = NestedIPAddressFromAPI(&resp.LocalAddress)
m.LocalAS = NestedASNFromAPI(&resp.LocalAs)
m.Name = maybeStringValue(resp.Name)
m.PeerGroup = NestedBGPPeerGroupFromAPI(resp.PeerGroup)
m.PrefixListIn = NestedPrefixListFromAPI(resp.PrefixListIn)
m.PrefixListOut = NestedPrefixListFromAPI(resp.PrefixListOut)
m.RemoteAddress = NestedIPAddressFromAPI(&resp.RemoteAddress)
m.RemoteAS = NestedASNFromAPI(&resp.RemoteAs)
m.Site = NestedSiteFromAPI(resp.Site)
m.Status = maybeStringValue((*string)(resp.Status.Value))
m.Tenant = NestedTenantFromAPI(resp.Tenant)

m.Tags = TagsFromAPI(ctx, resp.Tags, diags)

// todo: custom fields
}

func (d *SessionDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_session"
}

func (d *SessionDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "BGP Session data source",

Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{
MarkdownDescription: "ID of the resource in Netbox to use for lookup",
Required: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"description": schema.StringAttribute{
Computed: true,
},
"comments": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
MarkdownDescription: `One of: "active", "failed", "offline", "planned"`,
},
"site": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedSite)(nil).SchemaAttributes(),
},
"tenant": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedTenant)(nil).SchemaAttributes(),
},
"device": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedDevice)(nil).SchemaAttributes(),
},
"local_address": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedIPAddress)(nil).SchemaAttributes(),
},
"remote_address": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedIPAddress)(nil).SchemaAttributes(),
},
"local_as": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedASN)(nil).SchemaAttributes(),
},
"remote_as": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedASN)(nil).SchemaAttributes(),
},
"peer_group": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedBGPPeerGroup)(nil).SchemaAttributes(),
},
"import_policy_ids": schema.ListAttribute{
ElementType: types.Int64Type,
Computed: true,
},
"export_policy_ids": schema.ListAttribute{
ElementType: types.Int64Type,
Computed: true,
},
"prefix_list_in": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedPrefixList)(nil).SchemaAttributes(),
},
"prefix_list_out": schema.SingleNestedAttribute{
Computed: true,
Attributes: (*NestedPrefixList)(nil).SchemaAttributes(),
},
TagFieldName: TagSchema,
},
}
}

func (d *SessionDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}

data, ok := req.ProviderData.(*configuredProvider)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *configuredProvider, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}

d.client = data.Client
}

func (d *SessionDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var data SessionDataSourceModel

// Read Terraform configuration data into the model
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)

httpRes, err := d.client.PluginsBgpBgpsessionRetrieve(ctx, int(data.ID.ValueInt64()))
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("failed to retrieve session: %s", err))
return
}
res, err := client.ParsePluginsBgpSessionRetrieveResponse(httpRes)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("failed to parse session: %s", err))
return
}
if res.JSON200 == nil {
resp.Diagnostics.AddError("Client Error", httpError(httpRes, res.Body))
return
}

data.FillFromAPIModel(ctx, res.JSON200, resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}

resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
41 changes: 41 additions & 0 deletions internal/provider/bgpsession_datasource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package provider

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
)

func TestAccSessionDataSource(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
ExternalProviders: testExternalProviders,
Steps: []resource.TestStep{
// Read testing
{
Config: fmt.Sprintf(`%s
resource "netboxbgp_session" "test" {
name = "My session"
status = "active"
device_id = netbox_device.test.id
local_address_id = netbox_ip_address.local.id
remote_address_id = netbox_ip_address.remote.id
local_as_id = netbox_asn.test.id
remote_as_id = netbox_asn.test.id
}

data "netboxbgp_session" "test" {
depends_on = [netboxbgp_session.test]
id = netboxbgp_session.test.id
}
`, baseResources(t)),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.netboxbgp_session.test", "name", "My session"),
resource.TestCheckResourceAttrPair("data.netboxbgp_session.test", "device.name", "netbox_device.test", "name"),
),
},
},
})
}
92 changes: 28 additions & 64 deletions internal/provider/bgpsession_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,43 +63,21 @@ type SessionResourceModel struct {
func (m *SessionResourceModel) ToAPIModel(ctx context.Context, diags diag.Diagnostics) client.WritableBGPSessionRequest {
p := client.WritableBGPSessionRequest{}

if !m.Name.IsNull() {
p.Name = m.Name.ValueStringPointer()
}
if !m.Description.IsNull() {
p.Description = m.Description.ValueStringPointer()
}
if !m.Comments.IsNull() {
p.Comments = m.Comments.ValueStringPointer()
}
p.Name = m.Name.ValueStringPointer()
p.Description = m.Description.ValueStringPointer()
p.Comments = m.Comments.ValueStringPointer()
if !m.Status.IsNull() {
status := client.WritableBGPSessionRequestStatus(m.Status.ValueString())
p.Status = &status
}
if !m.SiteID.IsNull() {
p.Site = toIntPointer(m.SiteID.ValueInt64())
}
if !m.TenantID.IsNull() {
p.Tenant = toIntPointer(m.TenantID.ValueInt64())
}
if !m.DeviceID.IsNull() {
p.Device = toIntPointer(m.DeviceID.ValueInt64())
}
if !m.LocalAddressID.IsNull() {
p.LocalAddress = int(m.LocalAddressID.ValueInt64())
}
if !m.RemoteAddressID.IsNull() {
p.RemoteAddress = int(m.RemoteAddressID.ValueInt64())
}
if !m.LocalASID.IsNull() {
p.LocalAs = int(m.LocalASID.ValueInt64())
}
if !m.RemoteASID.IsNull() {
p.RemoteAs = int(m.RemoteASID.ValueInt64())
}
if !m.PeerGroupID.IsNull() {
p.PeerGroup = toIntPointer(m.PeerGroupID.ValueInt64())
}
p.Site = fromInt64Value(m.SiteID)
p.Tenant = fromInt64Value(m.TenantID)
p.Device = fromInt64Value(m.DeviceID)
p.LocalAddress = *fromInt64Value(m.LocalAddressID)
p.RemoteAddress = *fromInt64Value(m.RemoteAddressID)
p.LocalAs = *fromInt64Value(m.LocalASID)
p.RemoteAs = *fromInt64Value(m.RemoteASID)
p.PeerGroup = fromInt64Value(m.PeerGroupID)
if !m.ImportPolicyIDs.IsNull() {
policies, ds := toIntListPointer(ctx, m.ImportPolicyIDs)
for _, d := range ds {
Expand All @@ -114,12 +92,8 @@ func (m *SessionResourceModel) ToAPIModel(ctx context.Context, diags diag.Diagno
}
p.ExportPolicies = &policies
}
if !m.PrefixListInID.IsNull() {
p.PrefixListIn = toIntPointer(m.PrefixListInID.ValueInt64())
}
if !m.PrefixListOutID.IsNull() {
p.PrefixListOut = toIntPointer(m.PrefixListOutID.ValueInt64())
}
p.PrefixListIn = fromInt64Value(m.PrefixListInID)
p.PrefixListOut = fromInt64Value(m.PrefixListOutID)

p.Tags = TagsForAPIModel(ctx, m.Tags, diags)

Expand All @@ -129,17 +103,11 @@ func (m *SessionResourceModel) ToAPIModel(ctx context.Context, diags diag.Diagno
}

func (m *SessionResourceModel) FillFromAPIModel(ctx context.Context, resp *client.BGPSession, diags diag.Diagnostics) {
if resp.Id != nil {
m.ID = types.Int64Value(int64(*resp.Id))
}
if resp.Comments != nil && *resp.Comments != "" {
m.Comments = types.StringPointerValue(resp.Comments)
}
if resp.Description != nil && *resp.Description != "" {
m.Description = types.StringPointerValue(resp.Description)
}
m.ID = maybeInt64Value(resp.Id)
m.Comments = maybeStringValue(resp.Comments)
m.Description = maybeStringValue(resp.Description)
if resp.Device != nil {
m.DeviceID = types.Int64Value(int64(*resp.Device.Id))
m.DeviceID = maybeInt64Value(resp.Device.Id)
}
if resp.ExportPolicies != nil && len(*resp.ExportPolicies) > 0 {
var ds diag.Diagnostics
Expand All @@ -155,30 +123,26 @@ func (m *SessionResourceModel) FillFromAPIModel(ctx context.Context, resp *clien
diags.Append(diag.WithPath(path.Root("import_policy_ids"), d))
}
}
m.LocalAddressID = types.Int64Value(int64(*resp.LocalAddress.Id))
m.LocalASID = types.Int64Value(int64(*resp.LocalAs.Id))
if resp.Name != nil {
m.Name = types.StringPointerValue(resp.Name)
}
m.LocalAddressID = maybeInt64Value(resp.LocalAddress.Id)
m.LocalASID = maybeInt64Value(resp.LocalAs.Id)
m.Name = maybeStringValue(resp.Name)
if resp.PeerGroup != nil {
m.PeerGroupID = types.Int64Value(int64(*resp.PeerGroup.Id))
m.PeerGroupID = maybeInt64Value(resp.PeerGroup.Id)
}
if resp.PrefixListIn != nil {
m.PrefixListInID = types.Int64Value(int64(*resp.PrefixListIn.Id))
m.PrefixListInID = maybeInt64Value(resp.PrefixListIn.Id)
}
if resp.PrefixListOut != nil {
m.PrefixListOutID = types.Int64Value(int64(*resp.PrefixListOut.Id))
m.PrefixListOutID = maybeInt64Value(resp.PrefixListOut.Id)
}
m.RemoteAddressID = types.Int64Value(int64(*resp.RemoteAddress.Id))
m.RemoteASID = types.Int64Value(int64(*resp.RemoteAs.Id))
m.RemoteAddressID = maybeInt64Value(resp.RemoteAddress.Id)
m.RemoteASID = maybeInt64Value(resp.RemoteAs.Id)
if resp.Site != nil {
m.SiteID = types.Int64Value(int64(*resp.Site.Id))
}
if resp.Status != nil {
m.Status = types.StringPointerValue((*string)(resp.Status.Value))
m.SiteID = maybeInt64Value(resp.Site.Id)
}
m.Status = maybeStringValue((*string)(resp.Status.Value))
if resp.Tenant != nil {
m.TenantID = types.Int64Value(int64(*resp.Tenant.Id))
m.TenantID = maybeInt64Value(resp.Tenant.Id)
}

m.Tags = TagsFromAPI(ctx, resp.Tags, diags)
Expand Down
Loading