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: introduce new api client based on netbox-community/go-netbox #600

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ require (
github.com/go-openapi/strfmt v0.23.0
github.com/goware/urlx v0.3.2
github.com/hashicorp/terraform-plugin-sdk/v2 v2.33.0
github.com/netbox-community/go-netbox/v3 v3.7.7-0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678
)

require (
Expand Down Expand Up @@ -96,6 +96,7 @@ require (
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.15.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect
google.golang.org/grpc v1.61.1 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RR
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/netbox-community/go-netbox/v3 v3.7.7-0 h1:LgqVZtPSMKazezJVCrnajTXEHxDl6xlJNpH/UBsHp8U=
github.com/netbox-community/go-netbox/v3 v3.7.7-0/go.mod h1:rk3PBE/6oWvgmFH2dxoD2JyN+lkDWJ0dhNmy6HXBvVs=
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
Expand Down Expand Up @@ -263,8 +265,6 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w=
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
Expand Down
49 changes: 42 additions & 7 deletions netbox/client.go → netbox/client/client.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package netbox
package client

import (
"crypto/tls"
"fmt"
"net/http"
"time"

netboxclient "github.com/fbreckle/go-netbox/netbox/client"
netboxlegacy "github.com/fbreckle/go-netbox/netbox/client"
httptransport "github.com/go-openapi/runtime/client"
"github.com/goware/urlx"
netbox "github.com/netbox-community/go-netbox/v3"
log "github.com/sirupsen/logrus"
)

Expand All @@ -28,11 +30,13 @@ type customHeaderTransport struct {
headers map[string]interface{}
}

// Client does the heavy lifting of establishing a base Open API client to Netbox.
func (cfg *Config) Client() (*netboxclient.NetBoxAPI, error) {
// NewLegacyClient creates a NetBox API client based of github.com/fbreckle/go-netbox.
// It uses the legacy API client, which is based on the OpenAPI 2.0 specification.
// This client is deprecated and will be removed in the future.
func NewLegacyClient(cfg *Config) (*netboxlegacy.NetBoxAPI, error) {
log.WithFields(log.Fields{
"server_url": cfg.ServerURL,
}).Debug("Initializing Netbox client")
}).Debug("Initializing Netbox legacy client")

if cfg.APIToken == "" {
return nil, fmt.Errorf("missing netbox API key")
Expand Down Expand Up @@ -76,14 +80,45 @@ func (cfg *Config) Client() (*netboxclient.NetBoxAPI, error) {
Timeout: time.Second * time.Duration(cfg.RequestTimeout),
}

transport := httptransport.NewWithClient(parsedURL.Host, parsedURL.Path+netboxclient.DefaultBasePath, desiredRuntimeClientSchemes, httpClient)
transport := httptransport.NewWithClient(parsedURL.Host, parsedURL.Path+netboxlegacy.DefaultBasePath, desiredRuntimeClientSchemes, httpClient)
transport.DefaultAuthentication = httptransport.APIKeyAuth("Authorization", "header", fmt.Sprintf("Token %v", cfg.APIToken))
transport.SetLogger(log.StandardLogger())
netboxClient := netboxclient.New(transport, nil)
netboxClient := netboxlegacy.New(transport, nil)

return netboxClient, nil
}

// NewClient creates a NetBox API client based on github.com/netbox-community/go-netbox.
// This client is based on the OpenAPI 3.0 specification.
func NewClient(cfg *Config) (*netbox.APIClient, error) {
log.WithFields(log.Fields{
"server_url": cfg.ServerURL,
}).Debug("Initializing Netbox client")
if cfg.APIToken == "" {
return nil, fmt.Errorf("missing netbox API key")
}

headers := map[string]string{}
for k, v := range cfg.Headers {
headers[k] = fmt.Sprintf("%v", v)
}
headers["Authorization"] = fmt.Sprintf("Token %v", cfg.APIToken)

return netbox.NewAPIClient(&netbox.Configuration{
Servers: []netbox.ServerConfiguration{{
URL: cfg.ServerURL,
Description: "NetBox",
}},
HTTPClient: &http.Client{
Timeout: time.Second * time.Duration(cfg.RequestTimeout),
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: cfg.AllowInsecureHTTPS},
},
},
DefaultHeader: headers,
}), nil
}

// RoundTrip adds the headers specified in the transport on every request.
func (t customHeaderTransport) RoundTrip(r *http.Request) (*http.Response, error) {
for key, value := range t.headers {
Expand Down
60 changes: 44 additions & 16 deletions netbox/client_test.go → netbox/client/client_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package netbox
package client

import (
"context"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -10,56 +11,76 @@ import (
)

func TestValidClientWithAllData(t *testing.T) {
config := Config{
config := &Config{
APIToken: "07b12b765127747e4afd56cb531b7bf9c61f3c30",
ServerURL: "https://localhost:8080",
}

client, err := config.Client()
client, err := NewClient(config)
assert.NotNil(t, client)
assert.NoError(t, err)

legacyClient, err := NewLegacyClient(config)
assert.NotNil(t, legacyClient)
assert.NoError(t, err)
}

func TestURLMissingSchemaShouldWork(t *testing.T) {
config := Config{
config := &Config{
APIToken: "07b12b765127747e4afd56cb531b7bf9c61f3c30",
ServerURL: "localhost:8080",
}

client, err := config.Client()
client, err := NewClient(config)
assert.NotNil(t, client)
assert.NoError(t, err)

legacyClient, err := NewLegacyClient(config)
assert.NotNil(t, legacyClient)
assert.NoError(t, err)
}

func TestURLMaleformedUrlShouldFail(t *testing.T) {
config := Config{
func TestURLMalformedUrlShouldFail(t *testing.T) {
config := &Config{
APIToken: "07b12b765127747e4afd56cb531b7bf9c61f3c30",
ServerURL: "xyz:/localhost:8080",
}

_, err := config.Client()
_, err := NewClient(config)
assert.Error(t, err)

_, err = NewLegacyClient(config)
assert.Error(t, err)
}

func TestURLMissingPortShouldWork(t *testing.T) {
config := Config{
config := &Config{
APIToken: "07b12b765127747e4afd56cb531b7bf9c61f3c30",
ServerURL: "http://localhost",
}

client, err := config.Client()
client, err := NewClient(config)
assert.NotNil(t, client)
assert.NoError(t, err)

legacyClient, err := NewLegacyClient(config)

assert.NotNil(t, legacyClient)
assert.NoError(t, err)
}

func TestURLMissingAccessKey(t *testing.T) {
config := Config{
config := &Config{
APIToken: "",
ServerURL: "http://localhost",
}

_, err := config.Client()
_, err := NewClient(config)
assert.Error(t, err)

_, err = NewLegacyClient(config)
assert.Error(t, err)

}

func TestAdditionalHeadersSet(t *testing.T) {
Expand All @@ -72,19 +93,26 @@ func TestAdditionalHeadersSet(t *testing.T) {
}))
defer ts.Close()

config := Config{
config := &Config{
APIToken: "07b12b765127747e4afd56cb531b7bf9c61f3c30",
ServerURL: ts.URL,
Headers: map[string]interface{}{
"Hello": "World!",
},
}

client, err := config.Client()
client, err := NewClient(config)
assert.NoError(t, err)

req := status.NewStatusListParams()
client.Status.StatusList(req, nil)
req := client.StatusAPI.StatusRetrieve(context.Background())
req.Execute()

legacyClient, err := NewLegacyClient(config)
assert.NoError(t, err)

legacyReq := status.NewStatusListParams()
legacyClient.Status.StatusList(legacyReq, nil)

}

/* TODO
Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_asn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/ipam"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -46,7 +45,7 @@ for more information on available lookup expressions.`,
}

func dataSourceNetboxAsnRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

params := ipam.NewIpamAsnsListParams()

Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_asns.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"fmt"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/ipam"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
Expand Down Expand Up @@ -64,7 +63,7 @@ func dataSourceNetboxAsns() *schema.Resource {
}

func dataSourceNetboxAsnsRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

params := ipam.NewIpamAsnsListParams()

Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_available_prefix.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package netbox

import (
"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/ipam"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
Expand Down Expand Up @@ -41,7 +40,7 @@ func dataSourceNetboxAvailablePrefix() *schema.Resource {
}

func dataSourceNetboxAvailablePrefixRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

params := ipam.NewIpamPrefixesAvailablePrefixesListParams()

Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/virtualization"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -63,7 +62,7 @@ func dataSourceNetboxCluster() *schema.Resource {
}

func dataSourceNetboxClusterRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

params := virtualization.NewVirtualizationClustersListParams()

Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_cluster_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/virtualization"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand All @@ -27,7 +26,7 @@ func dataSourceNetboxClusterGroup() *schema.Resource {
}

func dataSourceNetboxClusterGroupRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

name := d.Get("name").(string)
params := virtualization.NewVirtualizationClusterGroupsListParams()
Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_cluster_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/virtualization"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand All @@ -27,7 +26,7 @@ func dataSourceNetboxClusterType() *schema.Resource {
}

func dataSourceNetboxClusterTypeRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

name := d.Get("name").(string)
params := virtualization.NewVirtualizationClusterTypesListParams()
Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/tenancy"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -39,7 +38,7 @@ func dataSourceNetboxContact() *schema.Resource {
}

func dataSourceNetboxContactRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient
params := tenancy.NewTenancyContactsListParams()

if name, ok := d.Get("name").(string); ok && name != "" {
Expand Down
3 changes: 1 addition & 2 deletions netbox/data_source_netbox_contact_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/tenancy"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -35,7 +34,7 @@ func dataSourceNetboxContactGroup() *schema.Resource {
}

func dataSourceNetboxContactGroupRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
api := m.(*Config).LegacyClient

name := d.Get("name").(string)
params := tenancy.NewTenancyContactGroupsListParams()
Expand Down
Loading
Loading