f5

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2022 License: BSD-3-Clause Imports: 17 Imported by: 62

Documentation

Overview

Package f5 provides a client for using the F5 API.

Example (Transaction)
package main

import (
	"log"

	"github.com/e-XpertSolutions/f5-rest-client/f5"
	"github.com/e-XpertSolutions/f5-rest-client/f5/ltm"
)

func main() {
	f5Client, err := f5.NewBasicClient("https://192.168.10.40", "admin", "admin")
	if err != nil {
		log.Fatal(err)
	}
	f5Client.DisableCertCheck()

	// Start new transaction.
	tx, err := f5Client.Begin()
	if err != nil {
		log.Fatal(err)
	}

	ltmClient := ltm.New(tx)

	// Create a HTTP monitor
	log.Print("Create a HTTP monitor")

	monitorConfig := ltm.MonitorHTTPConfig{
		Name: "http_monitor_" + tx.TransactionID(),
		Send: "GET / HTTP/1.0\r\n\r\n",
		Recv: "Hello",
	}

	if err := ltmClient.MonitorHTTP().Create(monitorConfig); err != nil {
		log.Fatal(err)
	}

	// Create a Pool
	log.Print("Create a pool")

	poolConfig := ltm.Pool{
		Name:    "pool_" + tx.TransactionID(),
		Monitor: "/Common/http_monitor_" + tx.TransactionID(),
		Members: []string{"10.1.10.10:80", "10.1.10.11:80"},
	}

	if err := ltmClient.Pool().Create(poolConfig); err != nil {
		log.Fatal(err)
	}

	// Create a Virtual Server
	log.Print("Create a Virtual Server")

	vsConfig := ltm.VirtualServer{
		Name:        "vs_http_" + tx.TransactionID(),
		Destination: "10.1.20.130:80",
		IPProtocol:  "tcp",
		Pool:        "pool_" + tx.TransactionID(),
		SourceAddressTranslation: ltm.SourceAddressTranslation{
			Type: "automap",
		},
		Profiles: []string{"tcp-mobile-optimized"},
	}

	if err := ltmClient.Virtual().Create(vsConfig); err != nil {
		log.Fatal(err)
	}

	// Commit to make the changes persistent.
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}

}
Output:

Index

Examples

Constants

View Source
const (
	PathDownloadUCS    = "/mgmt/shared/file-transfer/ucs-downloads"
	PathDownloadImage  = "/mgmt/cm/autodeploy/software-image-downloads"
	PathDownloadQKView = "/mgmt/cm/autodeploy/qkview-downloads"
)

Paths for file download.

View Source
const (
	PathDeviceInfo = "/mgmt/tm/cm/device"
	PathSyncStatus = "/mgmt/tm/cm/sync-status"
)

Cluster Management REST paths.

View Source
const F5TimeLayout = "2006-01-02T15:04:05.999999999-0700"

F5TimeLayout defines the layout to use for decoding dates returned by the F5 iControl REST API.

View Source
const MaxChunkSize = 1048576

MaxChunkSize is the maximum chunk size allowed by the iControl REST

View Source
const (
	PathBackup = "/mgmt/tm/shared/sys/backup"
)

Backup REST paths

View Source
const (
	PathBashCmd = "/mgmt/tm/util/bash"
)

Bash util REST path.

View Source
const (
	PathConfigSync = "/mgmt/tm/cm/config-sync"
)
View Source
const PathTransaction = "/mgmt/tm/transaction"

PathTransaction is the path to transaction API endpoint.

View Source
const (
	QKViewPath = "/mgmt/cm/autodeploy/qkview"
)
View Source
const (
	// For backward compatibility
	// DEPRECATED
	UploadRESTPath = "/mgmt/shared/file-transfer/uploads"
)

Paths for file upload.

Variables

View Source
var (
	// Upload paths
	PathUploadImage = FileTransferPath{"/mgmt/cm/autodeploy/software-image-uploads", "/shared/images"}
	PathUploadFile  = FileTransferPath{"/mgmt/shared/file-transfer/uploads", "/var/config/rest/downloads"}
	PathUploadUCS   = FileTransferPath{"mgmt/shared/file-transfer/ucs-uploads", "/var/local/ucs"}
)

File transfer path, according to:

https://devcentral.f5.com/s/articles/demystifying-icontrol-rest-part-5-transferring-files
View Source
var DefaultTimeout = 5 * time.Second

DefaultTimeout defines the default timeout for HTTP clients.

View Source
var ErrNoToken = errors.New("no token")

ErrNoToken is the error returned when the Client does not have a token.

View Source
var ErrNoTransaction = errors.New("no active transaction")

ErrNoTransaction is the error returned when a function related to transaction management is called when there is no active transaction.

Functions

func CreateToken added in v0.1.0

func CreateToken(baseURL, user, password, loginProvName string) (string, time.Time, error)

CreateToken creates a new token with the given baseURL, user, password and loginProvName.

func IsRequestError

func IsRequestError(err error) bool

IsRequestError reports whether err is a RequestError.

Types

type BackupResponse added in v0.1.0

type BackupResponse struct {
	// Unique ID to identify uniquely the backup action.
	ID string `json:"id"`

	// Name of the file in which the backup is saved to or restord from.
	File string `json:"file"`

	// Type of action performed. Possible values are:
	//    - BACKUP
	//    - RESTORE
	//    - RESTORE_WITH_NO_LICENSE
	//    - BACKUP_WITH_NO_PRIVATE_KEYS
	//    - BACKUP_WITH_ENCRYPTION
	//    - BACKUP_WITH_NO_PRIVATE_KEYS_WITH_ENCRYPTION
	//    - RESTORE_WITH_ENCRYPTION
	//    - RESTORE_WITH_NO_LICENSE_WITH_ENCRYPTION
	//    - CLEANUP
	Action string `json:"action"`

	// Status of the backup. Possible values are:
	//    - CREATED
	//    - STARTED
	//    - CANCEL_REQUESTED
	//    - CANCELED
	//    - FAILED
	//    - FINISHED
	Status string `json:"status"`
}

BackupResponse holds attributes returned by requests on the backup API.

func (BackupResponse) IsCanceled added in v0.1.0

func (resp BackupResponse) IsCanceled() bool

IsCanceled reports whether the status is CANCELED.

func (BackupResponse) IsDone added in v0.1.0

func (resp BackupResponse) IsDone() bool

IsDone reports whether the status indicates that the action is terminated, even if it is an error or that the task has been canceled.

func (BackupResponse) IsFailure added in v0.1.0

func (resp BackupResponse) IsFailure() bool

IsFailure reports whether the status is FAILED.

func (BackupResponse) IsSuccess added in v0.1.0

func (resp BackupResponse) IsSuccess() bool

IsSuccess reports whether the status is FINISHED.

type Client

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

A Client manages communication with the F5 API.

func NewBasicClient

func NewBasicClient(baseURL, user, password string) (*Client, error)

NewBasicClient creates a new F5 client with HTTP Basic Authentication.

baseURL is the base URL of the F5 API server.

func NewTokenClient

func NewTokenClient(baseURL, user, password, loginProvName string) (*Client, error)

NewTokenClient creates a new F5 client with token based authentication.

baseURL is the base URL of the F5 API server.

func TokenClientConnection added in v0.1.0

func TokenClientConnection(baseURL, token string) (*Client, error)

TokenClientConnection creates a new client with the given token.

func (*Client) Backup added in v0.1.0

func (c *Client) Backup(filename string) (*BackupResponse, error)

Backup creates a backup remotely saved into a file named according to the provided filename.

func (*Client) Begin added in v0.1.0

func (c *Client) Begin() (*Client, error)

Begin starts a transaction.

Example
package main

import (
	"log"

	"github.com/e-XpertSolutions/f5-rest-client/f5"
	"github.com/e-XpertSolutions/f5-rest-client/f5/ltm"
)

func main() {
	f5Client, err := f5.NewBasicClient("https://127.0.0.1", "admin", "admin")
	if err != nil {
		log.Fatal(err)
	}
	f5Client.DisableCertCheck()

	// Start new transaction.
	tx, err := f5Client.Begin()
	if err != nil {
		log.Fatal(err)
	}

	ltmClient := ltm.New(tx)

	// Node 1
	nodeConfig := ltm.Node{
		Name:    "test-node-1",
		Address: "1.1.1.1",
	}
	if err := ltmClient.Node().Create(nodeConfig); err != nil {
		log.Fatal(err)
	}

	// Node 2
	nodeConfig = ltm.Node{
		Name:    "test-node-2",
		Address: "2.2.2.2",
	}
	if err := ltmClient.Node().Create(nodeConfig); err != nil {
		log.Fatal(err)
	}

	// Commit to make the changes persistent.
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}
Output:

func (*Client) CheckAuth added in v0.1.0

func (c *Client) CheckAuth() error

CheckAuth verifies that the credentials provided at the client initialization are correct.

func (*Client) CheckBackup added in v0.1.0

func (c *Client) CheckBackup(id string) (*BackupResponse, error)

CheckBackup fetches the status of a backup process.

func (*Client) CheckQKView added in v1.0.1

func (c *Client) CheckQKView(id string) (*QKViewResponse, error)

func (*Client) Commit added in v0.1.0

func (c *Client) Commit() error

Commit commits the transaction.

func (*Client) ConfigSync added in v1.0.1

func (c *Client) ConfigSync(opts ...ConfigSyncOption) error

ConfigSync performs the config-sync operation. It only starts the sync and does not wait for it to complete. The synchronization status must be check manually.

func (*Client) DeleteQKView added in v1.0.1

func (c *Client) DeleteQKView(id string) (*QKViewResponse, error)

func (*Client) DisableCertCheck

func (c *Client) DisableCertCheck()

DisableCertCheck disables certificate verification, meaning that insecure certificate will not cause any error.

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response. It is just a wrapper arround http.Client Do method.

Callers should close resp.Body when done reading from it.

See http package documentation for more information:

https://golang.org/pkg/net/http/#Client.Do

func (*Client) DownloadImage added in v1.0.1

func (c *Client) DownloadImage(w io.Writer, filename string, opts ...FileTransferOption) (n int64, err error)

DownloadImage downloads BIG-IP images from the API and writes it to w.

Download can take some time due to the size of the image files.

func (*Client) DownloadQKView added in v1.0.1

func (c *Client) DownloadQKView(w io.Writer, filename string, opts ...FileTransferOption) (n int64, err error)

DownloadQKView downloads qkview from the API and writes it to w.

Download can take some time due to the size of the file.

func (*Client) DownloadUCS added in v0.1.0

func (c *Client) DownloadUCS(w io.Writer, filename string, opts ...FileTransferOption) (n int64, err error)

DownloadUCS downloads an UCS file and writes its content to w.

func (*Client) Exec added in v0.1.0

func (c *Client) Exec(cmd string) (*ExecOutput, error)

Exec executes remotely a shell command on the Big-IP.

func (*Client) ExecTMSH added in v0.1.0

func (c *Client) ExecTMSH(cmd string) (*ExecOutput, error)

ExecTMSH executes a TMSH command on the Big-IP.

func (*Client) FailoverState added in v0.1.0

func (c *Client) FailoverState(host, ip string) (string, error)

FailoverState returns the status of the BigIP (active, standby, forced-offline, ...).

func (*Client) GenerateQKView added in v1.0.1

func (c *Client) GenerateQKView(filename string) (*QKViewResponse, error)

func (*Client) IsActive added in v0.1.0

func (c *Client) IsActive(host string) bool

IsActive returns true whether the BigIP is active and the iControl REST are accessible. In case of error, false is returned.

func (*Client) ListQKViews added in v1.0.1

func (c *Client) ListQKViews() ([]QKViewResponse, error)

func (*Client) MakeRequest

func (c *Client) MakeRequest(method, restPath string, data interface{}) (*http.Request, error)

MakeRequest creates a request with headers appropriately set to make authenticated requests. This method must be called for every new request.

func (*Client) ModQuery

func (c *Client) ModQuery(method, restPath string, inputData interface{}) error

ModQuery performs a modification query such as POST, PUT or DELETE.

func (*Client) ReadError

func (c *Client) ReadError(resp *http.Response) error

ReadError checks if a HTTP response contains an error and returns it.

func (*Client) ReadQuery

func (c *Client) ReadQuery(restPath string, outputData interface{}) error

ReadQuery performs a GET query and unmarshal the response (from JSON) into outputData.

outputData must be a pointer.

func (*Client) RestoreBackup added in v0.1.0

func (c *Client) RestoreBackup(filename string) (*BackupResponse, error)

RestoreBackup restores a backup from a file having the provided filename and located into /var/local/ucs directory.

func (*Client) RestoreBackupWithNoLicense added in v0.1.0

func (c *Client) RestoreBackupWithNoLicense(filename string) (*BackupResponse, error)

RestoreBackupWithNoLicense works exactly as RestoreBackup but do no check the license.

func (*Client) RevokeToken added in v0.1.0

func (c *Client) RevokeToken() error

RevokeToken revokes the current token. If the Client has not been initialized with NewTokenClient, ErrNoToken is returned.

func (*Client) Rollback added in v0.1.0

func (c *Client) Rollback() error

Rollback aborts the current transaction. If there is no active transaction, ErrNoTransaction is returned.

func (*Client) SendRequest

func (c *Client) SendRequest(method, restPath string, data interface{}) (*http.Response, error)

SendRequest is a shortcut for MakeRequest() + Do() + ReadError().

func (*Client) SetHTTPClient added in v1.0.1

func (c *Client) SetHTTPClient(client http.Client)

SetHTTPClient sets the underlying HTTP used to make requests.

func (*Client) SetTimeout added in v1.0.1

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout sets the HTTP timeout for the underlying HTTP client.

func (*Client) SyncStatus added in v1.0.1

func (c *Client) SyncStatus() (status string, color string, err error)

SyncStatus returns the sync status of the BIG-IP along with the status color.

func (*Client) SyncStatusDetails added in v1.0.1

func (c *Client) SyncStatusDetails() (SyncStatusResp, error)

SyncStatusDetails returns the sync status and if it is different than "In Sync" also the Group Name that is out of sync.

func (*Client) TransactionID added in v0.1.0

func (c *Client) TransactionID() string

TransactionID returns the ID of the current transaction. If there is no active transaction, an empty string is returned.

func (*Client) TransactionState added in v0.1.0

func (c *Client) TransactionState() (*Transaction, error)

TransactionState returns the state of the current transaction. If there is no active transaction, ErrNoTransaction is returned.

func (*Client) UploadFile added in v0.1.0

func (c *Client) UploadFile(r io.Reader, filename string, filesize int64, opts ...FileTransferOption) (*UploadResponse, error)

UploadFile reads the content of a file from r and uploads it to the BigIP. The uploaded file will be named according to the provided filename.

filesize must be the exact file of the file.

The file is split into small chunk, therefore this method may send multiple request.

This method returns the latest upload response received.

func (*Client) UploadImage added in v0.1.0

func (c *Client) UploadImage(r io.Reader, filename string, filesize int64, opts ...FileTransferOption) (*UploadResponse, error)

UploadImage reads the content of an disk image from r and uploads it to the BigIP.

The uploaded image will be named according to the provided filename.

filesize must be the exact file of the file.

The file is split into small chunk, therefore this method may send multiple request.

This method returns the latest upload response received.

func (*Client) UploadUCS added in v0.1.0

func (c *Client) UploadUCS(r io.Reader, filename string, filesize int64, opts ...FileTransferOption) (*UploadResponse, error)

UploadUCS reads the content of an UCS archive from r and uploads it to the BigIP.

The uploaded UCS archive will be named according to the provided filename.

filesize must be the exact file of the file.

The file is split into small chunk, therefore this method may send multiple request.

This method returns the latest upload response received.

func (*Client) UseProxy added in v0.1.0

func (c *Client) UseProxy(proxy string) error

UseProxy configures a proxy to use for outbound connections

func (*Client) UseSystemProxy added in v0.1.0

func (c *Client) UseSystemProxy() error

UseSystemProxy configures the client to use the system proxy

type ConfigSyncOption added in v1.0.1

type ConfigSyncOption func(*ConfigSyncOptions)

ConfigSyncOption is a function prototype that sets the

func WithForceFullLoadPush added in v1.0.1

func WithForceFullLoadPush() ConfigSyncOption

WithForceFullLoadPush sets force-full-load-push parameter to true.

func WithFromGroup added in v1.0.1

func WithFromGroup(name string) ConfigSyncOption

WithFromGroup sets the name of from-group parameter.

func WithRecoverSync added in v1.0.1

func WithRecoverSync() ConfigSyncOption

WithRecoverSync sets recover-sync parameter to true.

func WithToGroup added in v1.0.1

func WithToGroup(name string) ConfigSyncOption

WithToGroup sets the name of to-group parameter.

type ConfigSyncOptions added in v1.0.1

type ConfigSyncOptions struct {
	FromGroup         string `mapstructure:"from-group,omitempty"`
	ToGroup           string `mapstructure:"to-group,omitempty"`
	RecoverSync       bool   `mapstructure:"recover-sync,omitempty"`
	ForceFullLoadPush bool   `mapstructure:"force-full-load-push,omitempty"`
}

ConfigSyncOptions represents available parameters for config-sync query.

type ExecOutput added in v0.1.0

type ExecOutput struct {
	Kind          string `json:"kind"`
	Command       string `json:"command"`
	CommandResult string `json:"commandResult"`
	UtilCmdArgs   string `json:"utilCmdArgs"`
}

ExecOutput represents the output returned by the API afeter having executed a bash command.

type F5Date added in v1.0.1

type F5Date struct {
	time.Time
}

F5Date wraps time.Time in order to override the time layout used during JSON decoding.

func (*F5Date) UnmarshalJSON added in v1.0.1

func (d *F5Date) UnmarshalJSON(b []byte) error

UnmarshalJSON overrides time.Time JSON decoding to support F5 time parsing layout.

type FileTransferOption added in v1.0.1

type FileTransferOption func(*FileTransferOptions)

FileTransferOption is a function type to set the transfer options.

func WithRemotePath added in v1.0.1

func WithRemotePath(path string) FileTransferOption

WithRemotePath sets the source directory on the remote F5 for file download.

func WithSFTP added in v1.0.1

func WithSFTP(config *ssh.ClientConfig) FileTransferOption

WithSFTP sets the ssh configuration for file transfer.

func WithTarget added in v1.0.1

func WithTarget(target FileTransferPath) FileTransferOption

WithTarget overrides the default FileTransferPath. This options has effects only on upload methods.

type FileTransferOptions added in v1.0.1

type FileTransferOptions struct {
	UseSFTP      bool
	ClientConfig *ssh.ClientConfig
	RemotePath   string           // for download only
	Target       FileTransferPath // for upload only
}

FileTransferOptions contains SSH configuration for downloading and uploading UCS using SFTP.

type FileTransferPath added in v1.0.1

type FileTransferPath struct {
	URI       string
	RemoteDir string
}

FileTransferPath holds the REST path and the corresponding remote directory for file transfer.

type QKViewResponse added in v1.0.1

type QKViewResponse struct {
	// Unique ID to identify uniquely the qkview.
	ID string `json:"id"`

	// Name of the file in which the qkview is saved.
	Name string `json:"name"`

	//Status of qkview. Possible values are:
	//	- SUCCEDED
	//	- FAILED
	//	- IN_PROGRESS
	Status string `json:"status"`
}

type RequestError

type RequestError struct {
	Code     int      `json:"code,omitempty"`
	Message  string   `json:"message,omitempty"`
	ErrStack []string `json:"errorStack,omitempty"`
}

A RequestError is returned as a HTTP Response by the F5 Big IP server in case of error.

func NewRequestError

func NewRequestError(body io.Reader) (*RequestError, error)

NewRequestError unmarshal a RequestError from a HTTP response body.

func (RequestError) Error

func (err RequestError) Error() string

Error implements the errors.Error interface

func (RequestError) String

func (err RequestError) String() string

type SyncStatusResp added in v1.0.1

type SyncStatusResp struct {
	Status    string
	Color     string
	Action    string
	GroupName string
}

SyncStatusResp contains the values obtained from the sync-status check.

type Transaction added in v0.1.0

type Transaction struct {
	TransID          int64  `json:"transId"`
	ValidateOnly     bool   `json:"validateOnly"`
	ExecutionTimeout int64  `json:"executionTimeout"`
	SelfLink         string `json:"selfLink"`
	State            string `json:"state"`
	TimeoutSeconds   int64  `json:"timeoutSeconds"`
	AsyncExecution   bool   `json:"asynExecution"`
	FailureReason    string `json:"failureReason"`
	Kind             string `json:"kind"`
}

A Transaction holds the state of a remote transaction identified by its transaction ID.

type UploadResponse added in v0.1.0

type UploadResponse struct {
	RemainingByteCount int64          `json:"remainingByteCount"`
	UsedChunks         map[string]int `json:"usedChunks"`
	TotalByteCount     int64          `json:"totalByteCount"`
	LocalFilePath      string         `json:"localFilePath"`
	TemporaryFilePath  string         `json:"temporaryFilePath"`
	Generation         int64          `json:"generation"`
	LastUpdateMicros   int64          `json:"lastUpdateMicros"`
}

An UploadResponse holds the responses send by the BigIP API while uploading files.

Directories

Path Synopsis
Package ltm provides a REST client for the /tm/ltm F5 BigIP API.
Package ltm provides a REST client for the /tm/ltm F5 BigIP API.

Jump to

Keyboard shortcuts

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