metadata

package module
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 13, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

README

Linode Metadata Service Client for Go

Release GoDoc

This package allows Go projects to easily interact with the Linode Metadata Service.

Getting Started

Prerequisites
Installation
go get github.com/linode/go-metadata
Basic Example

The following sample shows a simple Go project that initializes a new metadata client and retrieves various information about the current Linode.

package main

import (
	"context"
	"fmt"
	"log"

	metadata "github.com/linode/go-metadata"
)

func main() {
	// Create a new client
	client, err := metadata.NewClient(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve metadata about the current instance from the metadata API
	instanceInfo, err := client.GetInstance(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Instance Label:", instanceInfo.Label)
}
Without Token Management

By default, metadata API tokens are automatically generated and refreshed without any user intervention. If you would like to manage API tokens yourself, this functionality can be disabled:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	metadata "github.com/linode/go-metadata"
)

func main() {
	// Get a token from the environment
	token := os.Getenv("LINODE_METADATA_TOKEN")

	// Create a new client
	client, err := metadata.NewClient(
		context.Background(), 
		metadata.ClientWithoutManagedToken(), 
		metadata.ClientWithToken(token),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve metadata about the current instance from the metadata API
	instanceInfo, err := client.GetInstance(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Instance Label:", instanceInfo.Label)
}

For more examples, visit the examples directory.

Documentation

See godoc for a complete documentation reference.

Testing

Before running tests on this project, please ensure you have a Linode Personal Access Token exported under the LINODE_TOKEN environment variable.

End-to-End Testing Using Ansible

This project contains an Ansible playbook to automatically deploy the necessary infrastructure and run end-to-end tests on it.

To install the dependencies for this playbook, ensure you have Python 3 installed and run the following:

make test-deps

After all dependencies have been installed, you can run the end-to-end test suite by running the following:

make e2e

If your local SSH public key is stored in a location other than ~/.ssh/id_rsa.pub, you may need to override the TEST_PUBKEY argument:

make TEST_PUBKEY=/path/to/my/pubkey e2e

NOTE: To speed up subsequent test runs, the infrastructure provisioned for testing will persist after the test run is complete. This infrastructure is safe to manually remove.

Manual End-to-End Testing

End-to-end tests can also be manually run using the make e2e-local target. This test suite is expected to run from within a Linode instance and will likely fail in other environments.

Contribution Guidelines

Want to improve metadata-go? Please start here.

License

This software is Copyright Akamai Technologies, Inc. and is released under the Apache 2.0 license.

Documentation

Index

Constants

View Source
const (
	APIHost    = "169.254.169.254"
	APIProto   = "http"
	APIVersion = "v1"
)
View Source
const DefaultWatcherInterval = 5 * time.Minute

Variables

View Source
var (
	Version = "dev"

	// DefaultUserAgent is the default User-Agent sent in HTTP request headers
	DefaultUserAgent string
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Errors []APIErrorReason `json:"errors"`
}

APIError is the error-set returned by the Linode API when presented with an invalid request

func (APIError) Error

func (e APIError) Error() string

type APIErrorReason

type APIErrorReason struct {
	Reason string `json:"reason"`
	Field  string `json:"field"`
}

APIErrorReason is an individual invalid request message returned by the Linode API

func (APIErrorReason) Error

func (r APIErrorReason) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an instance of a Linode Metadata Service client.

func NewClient

func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error)

NewClient creates a new Metadata API client configured with the given options.

func (*Client) GenerateToken

func (c *Client) GenerateToken(ctx context.Context, opts ...TokenOption) (string, error)

GenerateToken generates a token to access the Metadata API.

func (*Client) GetInstance

func (c *Client) GetInstance(ctx context.Context) (*InstanceData, error)

GetInstance gets various information about the current instance.

func (*Client) GetNetwork

func (c *Client) GetNetwork(ctx context.Context) (*NetworkData, error)

GetNetwork gets networking information about the current Linode instance.

func (*Client) GetSSHKeys

func (c *Client) GetSSHKeys(ctx context.Context) (*SSHKeysData, error)

GetSSHKeys gets all SSH keys for the current instance.

func (*Client) GetUserData

func (c *Client) GetUserData(ctx context.Context) (string, error)

GetUserData returns the user data for the current instance. NOTE: The result of this endpoint is automatically decoded from base64 and un-gzipped if needed.

func (*Client) NewInstanceWatcher

func (c *Client) NewInstanceWatcher(opts ...WatcherOption) *InstanceWatcher

NewInstanceWatcher creates a new InstanceWatcher for monitoring changes to the current Linode instance.

func (*Client) NewNetworkWatcher

func (c *Client) NewNetworkWatcher(opts ...WatcherOption) *NetworkWatcher

NewNetworkWatcher creates a new NetworkWatcher for monitoring changes to the current Linode instance.

func (*Client) R

func (c *Client) R(ctx context.Context) *resty.Request

R wraps resty's R method

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, opts ...TokenOption) (*Client, error)

RefreshToken generates and applies a new token for this client.

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string) *Client

SetBaseURL configures the target URL for metadata API this client accesses.

func (*Client) SetVersion

func (c *Client) SetVersion(version string) *Client

SetVersion configures the target metadata API version for this client.

func (*Client) UseToken

func (c *Client) UseToken(token string) *Client

UseToken applies the given token to this Metadata client.

type ClientOption

type ClientOption func(options *clientCreateConfig)

ClientOption is an option that can be used during client creation.

func ClientWithBaseURL

func ClientWithBaseURL(baseURL string) ClientOption

ClientWithBaseURL configures the target host of the Metadata API this client points to. Default: "169.254.169.254"

func ClientWithDebug

func ClientWithDebug() ClientOption

ClientWithDebug enables debug mode for the metadata client. If this option is specified, all metadata service API requests and responses will be written to the client logger (default: stderr).

To override the client logger, refer to ClientWithLogger.

func ClientWithHTTPClient

func ClientWithHTTPClient(client *http.Client) ClientOption

ClientWithHTTPClient configures the underlying HTTP client to communicate with the Metadata API.

func ClientWithLogger

func ClientWithLogger(logger Logger) ClientOption

ClientWithLogger specifies the logger that should be used when outputting debug logs. The logger argument should implement the Logger interface. Default: stderr

func ClientWithManagedToken

func ClientWithManagedToken(opts ...TokenOption) ClientOption

ClientWithManagedToken configures the metadata client to automatically generate and refresh the API token for the Metadata client.

func ClientWithToken

func ClientWithToken(token string) ClientOption

ClientWithToken configures the starting token for the metadata client. If this option is specified and managed tokens are enabled for a client, the client will not generate an initial Metadata API token.

func ClientWithUAPrefix

func ClientWithUAPrefix(uaPrefix string) ClientOption

ClientWithUAPrefix configures the prefix for user agents on API requests made by this client.

func ClientWithVersion

func ClientWithVersion(version string) ClientOption

ClientWithVersion configures the Metadata API version this client should target. Default: "v1"

func ClientWithoutManagedToken

func ClientWithoutManagedToken() ClientOption

ClientWithoutManagedToken configures the metadata client to disable automatic token management.

type Error

type Error struct {
	Response *http.Response
	Code     int
	Message  string
}

Error wraps the LinodeGo error with the relevant http.Response

func (Error) Error

func (g Error) Error() string

type IPv4Data

type IPv4Data struct {
	Public  []netip.Prefix `json:"public"`
	Private []netip.Prefix `json:"private"`
	Shared  []netip.Prefix `json:"shared"`
}

type IPv6Data

type IPv6Data struct {
	SLAAC        netip.Prefix   `json:"slaac"`
	LinkLocal    netip.Prefix   `json:"link_local"`
	Ranges       []netip.Prefix `json:"ranges"`
	SharedRanges []netip.Prefix `json:"shared_ranges"`
}

type InstanceBackupsData

type InstanceBackupsData struct {
	Enabled bool    `json:"enabled"`
	Status  *string `json:"status"`
}

InstanceBackupsData contains information about the current Linode instance's backups enrollment.

type InstanceData

type InstanceData struct {
	ID       int                 `json:"id"`
	Label    string              `json:"label"`
	Region   string              `json:"region"`
	Type     string              `json:"type"`
	HostUUID string              `json:"host_uuid"`
	Tags     []string            `json:"tags"`
	Specs    InstanceSpecsData   `json:"specs"`
	Backups  InstanceBackupsData `json:"backups"`
	Image    InstanceImageData   `json:"image"`
}

InstanceData contains various metadata about the current Linode instance.

type InstanceImageData

type InstanceImageData struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

InstanceImageData contains information about the Disk Image used during instance provisioning

type InstanceSpecsData

type InstanceSpecsData struct {
	VCPUs    int `json:"vcpus"`
	Memory   int `json:"memory"`
	GPUs     int `json:"gpus"`
	Transfer int `json:"transfer"`
	Disk     int `json:"disk"`
}

InstanceSpecsData contains various information about the specifications of the current Linode instance.

type InstanceWatcher

type InstanceWatcher struct {
	Updates chan *InstanceData
	Errors  chan error
	// contains filtered or unexported fields
}

InstanceWatcher watches for any changes that are reflected in the Client.GetInstance(...) function result.

func (*InstanceWatcher) Close

func (watcher *InstanceWatcher) Close()

Close closes the watcher and all related channels. If applicable, close will also cancel the poller for this watcher.

func (*InstanceWatcher) Start

func (watcher *InstanceWatcher) Start(ctx context.Context)

Start starts the watcher. NOTE: Start should only be called once per-watcher.

type InterfaceData

type InterfaceData struct {
	Label       string       `json:"label"`
	Purpose     string       `json:"purpose"`
	IPAMAddress netip.Prefix `json:"ipam_address"`
}

type Logger

type Logger = resty.Logger

type NetworkData

type NetworkData struct {
	Interfaces []InterfaceData `json:"interfaces"`
	IPv4       IPv4Data        `json:"ipv4"`
	IPv6       IPv6Data        `json:"ipv6"`
}

type NetworkWatcher

type NetworkWatcher struct {
	Updates chan *NetworkData
	Errors  chan error
	// contains filtered or unexported fields
}

NetworkWatcher watches for any changes that are reflected in the Client.GetNetwork(...) function result.

func (*NetworkWatcher) Close

func (watcher *NetworkWatcher) Close()

Close closes the watcher and all related channels. If applicable, close will also cancel the poller for this watcher.

func (*NetworkWatcher) Start

func (watcher *NetworkWatcher) Start(ctx context.Context)

Start starts the watcher. NOTE: Start should only be called once per-watcher.

type SSHKeysData

type SSHKeysData struct {
	Users map[string][]string `json:"users"`
}

SSHKeysData contains information about SSH keys relevant to the current Linode instance.

type TokenOption

type TokenOption func(opts *tokenCreateOpts)

func TokenWithExpiry

func TokenWithExpiry(seconds int) TokenOption

TokenWithExpiry configures the expiry in seconds for a token. Default: 3600

type WatcherOption

type WatcherOption func(options *watcherConfig)

WatcherOption represents an option that can be used to configure a watcher.

func WatcherWithInterval

func WatcherWithInterval(duration time.Duration) WatcherOption

WatcherWithInterval configures the interval at which a watcher should poll for changes. Default: 5 minutes

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL