client

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2023 License: GPL-3.0 Imports: 18 Imported by: 3

Documentation

Overview

Package client implements a Go client for Pebble's HTTP-over-unix-socket API.

To use the API, first create a client using New, and then call the methods on the returned Client to interact with the API, such as Client.Start or Client.ListFiles.

Example
package main

import (
	"log"

	"github.com/canonical/pebble/client"
)

var runExample = false // example won't actually be run, just type-checked

func main() {
	if !runExample {
		return
	}

	pebble, err := client.New(&client.Config{Socket: ".pebble.socket"})
	if err != nil {
		log.Fatal(err)
	}
	changeID, err := pebble.Stop(&client.ServiceOptions{Names: []string{"mysvc"}})
	if err != nil {
		log.Fatal(err)
	}
	_, err = pebble.WaitChange(changeID, &client.WaitChangeOptions{})
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Index

Examples

Constants

View Source
const (
	ErrorKindLoginRequired     = "login-required"
	ErrorKindSystemRestart     = "system-restart"
	ErrorKindDaemonRestart     = "daemon-restart"
	ErrorKindNoDefaultServices = "no-default-services"
)

Variables

View Source
var ErrNoData = fmt.Errorf("data entry not found")

ErrNoData is returned when there is no data associated with a given key.

Functions

func FakeDoRetry

func FakeDoRetry(retry, timeout time.Duration) (restore func())

FakeDoRetry fakes the delays used by the do retry loop (intended for testing). Calling restore will revert the changes.

Types

type AddLayerOptions

type AddLayerOptions struct {
	// Combine true means combine the new layer with an existing layer that
	// has the given label. False (the default) means append a new layer.
	Combine bool

	// Label is the label for the new layer if appending, and the label of the
	// layer to combine with if Combine is true.
	Label string

	// LayerData is the new layer in YAML format.
	LayerData []byte
}

type Change

type Change struct {
	ID      string  `json:"id"`
	Kind    string  `json:"kind"`
	Summary string  `json:"summary"`
	Status  string  `json:"status"`
	Tasks   []*Task `json:"tasks,omitempty"`
	Ready   bool    `json:"ready"`
	Err     string  `json:"err,omitempty"`

	SpawnTime time.Time `json:"spawn-time,omitempty"`
	ReadyTime time.Time `json:"ready-time,omitempty"`
	// contains filtered or unexported fields
}

Change is a modification to the system state.

func (*Change) Get

func (c *Change) Get(key string, value interface{}) error

Get unmarshals into value the kind-specific data with the provided key.

type ChangeSelector

type ChangeSelector uint8

ChangeSelector represents a selection of changes to query for.

const (
	ChangesInProgress ChangeSelector = 1 << iota
	ChangesReady
	ChangesAll = ChangesReady | ChangesInProgress
)

func (ChangeSelector) String

func (c ChangeSelector) String() string

type ChangesOptions

type ChangesOptions struct {
	ServiceName string // if empty, no filtering by service is done
	Selector    ChangeSelector
}

type CheckInfo

type CheckInfo struct {
	// Name is the name of this check, from the layer configuration.
	Name string `json:"name"`

	// Level is this check's level, from the layer configuration.
	Level CheckLevel `json:"level"`

	// Status is the status of this check: "up" if healthy, "down" if the
	// number of failures has reached the configured threshold.
	Status CheckStatus `json:"status"`

	// Failures is the number of times in a row this check has failed. It is
	// reset to zero as soon as the check succeeds.
	Failures int `json:"failures"`

	// Threshold is this check's failure threshold, from the layer
	// configuration.
	Threshold int `json:"threshold"`
}

CheckInfo holds status information for a single health check.

type CheckLevel

type CheckLevel string

CheckLevel represents the level of a health check.

const (
	UnsetLevel CheckLevel = ""
	AliveLevel CheckLevel = "alive"
	ReadyLevel CheckLevel = "ready"
)

type CheckStatus

type CheckStatus string

CheckStatus represents the status of a health check.

const (
	CheckStatusUp   CheckStatus = "up"
	CheckStatusDown CheckStatus = "down"
)

type ChecksOptions

type ChecksOptions struct {
	// Level is the check level to query for. A check is included in the
	// results if this field is not set, or if it is equal to the check's
	// level.
	Level CheckLevel

	// Names is the list of check names to query for. A check is included in
	// the results if this field is nil or empty slice, or if one of the
	// values in the slice is equal to the check's name.
	Names []string
}

type Client

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

A Client knows how to talk to the Pebble daemon.

func New

func New(config *Config) (*Client, error)

func (*Client) Abort

func (client *Client) Abort(id string) (*Change, error)

Abort attempts to abort a change that is not yet ready.

func (*Client) AddLayer

func (client *Client) AddLayer(opts *AddLayerOptions) error

AddLayer adds a layer to the plan's configuration layers.

func (*Client) AutoStart

func (client *Client) AutoStart(opts *ServiceOptions) (changeID string, err error)

AutoStart starts the services makes as "startup: enabled". opts.Names must be empty for this call.

func (*Client) Change

func (client *Client) Change(id string) (*Change, error)

Change fetches information about a Change given its ID.

func (*Client) Changes

func (client *Client) Changes(opts *ChangesOptions) ([]*Change, error)

Changes fetches information for the changes specified.

func (*Client) Checks

func (client *Client) Checks(opts *ChecksOptions) ([]*CheckInfo, error)

Checks fetches information about specific health checks (or all of them), ordered by check name.

func (*Client) CloseIdleConnections

func (client *Client) CloseIdleConnections()

CloseIdleConnections closes any API connections that are currently unused.

func (*Client) DebugGet

func (client *Client) DebugGet(action string, result interface{}, params map[string]string) error

DebugGet sends a GET debug action to the server with the provided parameters.

func (*Client) DebugPost

func (client *Client) DebugPost(action string, params interface{}, result interface{}) error

DebugPost sends a POST debug action to the server with the provided parameters.

func (*Client) Exec

func (client *Client) Exec(opts *ExecOptions) (*ExecProcess, error)

Exec starts a command with the given options, returning a value representing the process.

func (*Client) FollowLogs

func (client *Client) FollowLogs(ctx context.Context, opts *LogsOptions) error

FollowLogs requests logs from the given services and follows them until the context is cancelled.

func (*Client) Health added in v1.4.0

func (client *Client) Health(opts *HealthOptions) (health bool, err error)

Health fetches healthy status of specified checks.

func (*Client) Hijack

func (client *Client) Hijack(f func(*http.Request) (*http.Response, error))

Hijack lets the caller take over the raw HTTP request.

func (*Client) ListFiles

func (client *Client) ListFiles(opts *ListFilesOptions) ([]*FileInfo, error)

ListFiles obtains the contents of a directory or glob, or information about a file.

func (*Client) Logs

func (client *Client) Logs(opts *LogsOptions) error

Logs fetches previously-written logs from the given services.

func (*Client) Maintenance

func (client *Client) Maintenance() error

Maintenance returns an error reflecting the daemon maintenance status or nil.

func (*Client) MakeDir

func (client *Client) MakeDir(opts *MakeDirOptions) error

MakeDir creates a directory or directory tree.

func (*Client) Okay

func (client *Client) Okay(t time.Time) error

Okay asks the server to silence the warnings that would have been returned by Warnings at the given time.

func (*Client) PlanBytes

func (client *Client) PlanBytes(_ *PlanOptions) (data []byte, err error)

PlanBytes fetches the plan in YAML format.

func (*Client) RemovePath

func (client *Client) RemovePath(opts *RemovePathOptions) error

RemovePath deletes a file or directory. The error returned is a *Error if the request went through successfully but there was an OS-level error deleting a file or directory, with the Kind field set to the specific error kind, for example "permission-denied".

func (*Client) Replan

func (client *Client) Replan(opts *ServiceOptions) (changeID string, err error)

Replan stops and (re)starts the services whose configuration has changed since they were started. opts.Names must be empty for this call.

func (*Client) Restart

func (client *Client) Restart(opts *ServiceOptions) (changeID string, err error)

Restart stops and then starts the services named in opts.Names in dependency order.

func (*Client) SendSignal

func (client *Client) SendSignal(opts *SendSignalOptions) error

SendSignal sends a signal to each of the specified services.

func (*Client) Services

func (client *Client) Services(opts *ServicesOptions) ([]*ServiceInfo, error)

Services fetches information about specific services (or all of them), ordered by service name.

func (*Client) Start

func (client *Client) Start(opts *ServiceOptions) (changeID string, err error)

Start starts the services named in opts.Names in dependency order.

func (*Client) Stop

func (client *Client) Stop(opts *ServiceOptions) (changeID string, err error)

Stop stops the services named in opts.Names in dependency order.

func (*Client) SysInfo

func (client *Client) SysInfo() (*SysInfo, error)

SysInfo gets system information from the remote API.

func (*Client) WaitChange

func (client *Client) WaitChange(id string, opts *WaitChangeOptions) (*Change, error)

WaitChange waits for the change to be finished. If the wait operation succeeds, the returned Change.Err string will be non-empty if the change itself had an error.

func (*Client) Warnings

func (client *Client) Warnings(opts WarningsOptions) ([]*Warning, error)

Warnings returns the list of un-okayed warnings.

func (*Client) WarningsSummary

func (client *Client) WarningsSummary() (count int, timestamp time.Time)

WarningsSummary returns the number of warnings that are ready to be shown to the user, and the timestamp of the most recently added warning (useful for silencing the warning alerts, and OKing the returned warnings).

type Config

type Config struct {
	// BaseURL contains the base URL where the Pebble daemon is expected to be.
	// It can be empty for a default behavior of talking over a unix socket.
	BaseURL string

	// Socket is the path to the unix socket to use.
	Socket string

	// DisableKeepAlive indicates that the connections should not be kept
	// alive for later reuse (the default is to keep them alive).
	DisableKeepAlive bool

	// UserAgent is the User-Agent header sent to the Pebble daemon.
	UserAgent string
}

Config allows the user to customize client behavior.

type ConnectionError

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

ConnectionError represents a connection or communication error.

func (ConnectionError) Error

func (e ConnectionError) Error() string

func (ConnectionError) Unwrap

func (e ConnectionError) Unwrap() error

type Error

type Error struct {
	Kind    string      `json:"kind"`
	Value   interface{} `json:"value"`
	Message string      `json:"message"`

	StatusCode int
}

Error is the real value of response.Result when an error occurs.

func (*Error) Error

func (e *Error) Error() string

type ExecOptions

type ExecOptions struct {
	// Required: command and arguments (first element is the executable).
	Command []string

	// Optional: run the command in the context of this service. Specifically,
	// inherit its environment variables, user/group settings, and working
	// and working directory. The other options in this struct will override
	// the service context; Environment will be merged on top of the service's.
	ServiceContext string

	// Optional environment variables.
	Environment map[string]string

	// Optional working directory (default is $HOME or "/" if $HOME not set).
	WorkingDir string

	// Optional user ID and group ID for the process to run as.
	UserID  *int
	User    string
	GroupID *int
	Group   string

	// Optional timeout for the command execution, after which the process
	// will be terminated. If zero, no timeout applies.
	Timeout time.Duration

	// True to ask the server to set up a pseudo-terminal (PTY) for stdout
	// (this also allows window resizing). The default is no PTY, and just
	// to use pipes for stdout/stderr.
	Terminal bool

	// True to use the pseudo-terminal for stdin (only allowed when Terminal
	// is true). The default is to use a pipe for stdin.
	Interactive bool

	// Initial terminal width and height (only apply if Terminal is true).
	// If not specified, the Pebble server uses the target's default (usually
	// 80x25). When using the "pebble exec" CLI, these are set to the host's
	// terminal size automatically.
	Width  int
	Height int

	// Standard input stream. If nil, no input is sent.
	Stdin io.Reader

	// Standard output stream. If nil, output is discarded.
	Stdout io.Writer

	// Standard error stream. If nil, error output is combined with standard
	// output and goes to the Stdout stream.
	Stderr io.Writer
}

type ExecProcess

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

ExecProcess represents a running process. Use Wait to wait for it to finish.

func (*ExecProcess) SendResize

func (p *ExecProcess) SendResize(width, height int) error

SendResize sends a resize message to the running process.

func (*ExecProcess) SendSignal

func (p *ExecProcess) SendSignal(signal string) error

SendSignal sends a signal to the running process.

func (*ExecProcess) Wait

func (p *ExecProcess) Wait() error

Wait waits for the command process to finish. The returned error is nil if the process runs successfully and returns a zero exit code. If the command fails with a nonzero exit code, the error is of type *ExitError.

type ExitError

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

ExitError reports an unsuccessful exit by a command (a nonzero exit code).

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) ExitCode

func (e *ExitError) ExitCode() int

ExitCode returns the command's exit code (it will always be nonzero).

type FileInfo

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

func (*FileInfo) Group

func (fi *FileInfo) Group() string

Group is the string representing the owner user group.

func (*FileInfo) GroupID

func (fi *FileInfo) GroupID() *int

GroupID is the ID of the owner group (can be nil).

func (*FileInfo) IsDir

func (fi *FileInfo) IsDir() bool

IsDir is an abbreviation for Mode().IsDir().

func (*FileInfo) ModTime

func (fi *FileInfo) ModTime() time.Time

ModTime returns the file modification time.

func (*FileInfo) Mode

func (fi *FileInfo) Mode() os.FileMode

Mode returns the file mode and permission bits.

func (*FileInfo) Name

func (fi *FileInfo) Name() string

Name returns the base name of the file.

func (*FileInfo) Path

func (fi *FileInfo) Path() string

Path is the full absolute path of the file.

func (*FileInfo) Size

func (fi *FileInfo) Size() int64

Size returns the length in bytes for regular files. For others, its behavior is system-dependent.

func (*FileInfo) Sys

func (fi *FileInfo) Sys() interface{}

Sys returns the underlying data source (always nil for client.FileInfo).

func (*FileInfo) User

func (fi *FileInfo) User() string

User is the string representing the owner user name.

func (*FileInfo) UserID

func (fi *FileInfo) UserID() *int

UserID is the ID of the owner user (can be nil).

type HealthOptions added in v1.4.0

type HealthOptions struct {
	// Level may be set to CheckAlive, to query whether alive checks are up, and
	// CheckReady, to query whether both alive and ready checks are up.
	// Defaults to CheckReady if unset.
	Level CheckLevel

	// Names defines which checks should be considered for the query. Defaults to all.
	Names []string
}

HealthOptions holds query options to pass to a Health call.

type ListFilesOptions

type ListFilesOptions struct {
	// Path is the absolute path of the file system entry to be listed.
	Path string

	// Pattern is the glob-like pattern string to filter results by. When
	// present, only file system entries with names matching this pattern will
	// be included in the call results.
	Pattern string

	// Itself, when set, will force directory entries not to be listed, but
	// instead have their information returned as if they were regular files.
	Itself bool
}

type LogEntry

type LogEntry struct {
	Time    time.Time `json:"time"`
	Service string    `json:"service"`
	Message string    `json:"message"`
}

LogEntry is the struct passed to the WriteLog function.

type LogsOptions

type LogsOptions struct {
	// WriteLog is called to write a single log to the output (required).
	WriteLog func(entry LogEntry) error

	// Services is the list of service names to fetch logs for (nil or empty
	// slice means all services).
	Services []string

	// N defines the number of log lines to return from the buffer. In follow
	// mode, the default is zero, in non-follow mode it's server-defined
	// (currently 30). Set to -1 to return the entire buffer.
	N int
}

type MakeDirOptions

type MakeDirOptions struct {
	// Path is the absolute path of the directory to be created (required).
	Path string

	// MakeParents, if true, specifies that any non-existent parent directories
	// should be created. If false (the default), the call will fail if the
	// directory to be created has at least one parent directory that does not
	// exist.
	MakeParents bool

	// Permissions specifies the permission bits of the directories to be created.
	// If 0 or unset, defaults to 0755.
	Permissions os.FileMode

	// UserID indicates the user ID of the owner for the created directories.
	UserID *int

	// User indicates the user name of the owner for the created directories.
	// If used together with UserID, this value must match the name of the user
	// with that ID.
	User string

	// GroupID indicates the group ID of the owner for the created directories.
	GroupID *int

	// Group indicates the name of the owner group for the created directories.
	// If used together with GroupID, this value must match the name of the group
	// with that ID.
	Group string
}

MakeDirOptions holds the options for a call to MakeDir.

type PlanOptions

type PlanOptions struct{}

type RemovePathOptions

type RemovePathOptions struct {
	// Path is the absolute path to be deleted (required).
	Path string

	// Recursive, if true, will delete all files and directories contained
	// within the specified path, recursively. Defaults to false.
	Recursive bool
}

RemovePathOptions holds the options for a call to RemovePath.

type RequestError

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

RequestError is returned when there's an error processing the request.

func (RequestError) Error

func (e RequestError) Error() string

type ResultInfo

type ResultInfo struct{}

ResultInfo is empty for now, but this is the mechanism that conveys general information that makes sense to requests at a more general level, and might be disconnected from the specific request at hand.

type SendSignalOptions

type SendSignalOptions struct {
	Signal   string
	Services []string
}

type ServiceInfo

type ServiceInfo struct {
	Name         string         `json:"name"`
	Startup      ServiceStartup `json:"startup"`
	Current      ServiceStatus  `json:"current"`
	CurrentSince time.Time      `json:"current-since"`
}

ServiceInfo holds status information for a single service.

type ServiceOptions

type ServiceOptions struct {
	Names []string
}

type ServiceStartup

type ServiceStartup string

ServiceStartup defines the different startup modes for a service.

const (
	StartupEnabled  ServiceStartup = "enabled"
	StartupDisabled ServiceStartup = "disabled"
)

type ServiceStatus

type ServiceStatus string

ServiceStatus defines the current states for a service.

const (
	StatusActive   ServiceStatus = "active"
	StatusBackoff  ServiceStatus = "backoff"
	StatusError    ServiceStatus = "error"
	StatusInactive ServiceStatus = "inactive"
)

type ServicesOptions

type ServicesOptions struct {
	// Names is the list of service names to query for. If slice is nil or
	// empty, fetch information for all services.
	Names []string
}

type SocketNotFoundError

type SocketNotFoundError struct {
	// Err is the wrapped error.
	Err error

	// Path is the path of the non-existent socket.
	Path string
}

SocketNotFoundError is the error type returned when the client fails to find a unix socket at the specified path.

func (SocketNotFoundError) Error

func (s SocketNotFoundError) Error() string

func (SocketNotFoundError) Unwrap

func (s SocketNotFoundError) Unwrap() error

type SysInfo

type SysInfo struct {
	// Version is the server version.
	Version string `json:"version,omitempty"`

	// BootID is a unique string that represents this boot of the server.
	BootID string `json:"boot-id,omitempty"`
}

type Task

type Task struct {
	ID       string       `json:"id"`
	Kind     string       `json:"kind"`
	Summary  string       `json:"summary"`
	Status   string       `json:"status"`
	Log      []string     `json:"log,omitempty"`
	Progress TaskProgress `json:"progress"`

	SpawnTime time.Time `json:"spawn-time,omitempty"`
	ReadyTime time.Time `json:"ready-time,omitempty"`

	Data map[string]*json.RawMessage
}

Task represents a single operation done to change the system's state.

func (*Task) Get

func (t *Task) Get(key string, value interface{}) error

Get unmarshals into value the kind-specific data with the provided key.

type TaskProgress

type TaskProgress struct {
	Label string `json:"label"`
	Done  int    `json:"done"`
	Total int    `json:"total"`
}

TaskProgress represents the completion progress of a task.

type WaitChangeOptions

type WaitChangeOptions struct {
	// If nonzero, wait at most this long before returning. If a timeout
	// occurs, WaitChange will return an error.
	Timeout time.Duration
}

type Warning

type Warning struct {
	Message     string        `json:"message"`
	FirstAdded  time.Time     `json:"first-added"`
	LastAdded   time.Time     `json:"last-added"`
	LastShown   time.Time     `json:"last-shown,omitempty"`
	ExpireAfter time.Duration `json:"expire-after,omitempty"`
	RepeatAfter time.Duration `json:"repeat-after,omitempty"`
}

Warning holds a short message that's meant to alert about system events. There'll only ever be one Warning with the same message, and it can be silenced for a while before repeating. After a (supposedly longer) while it'll go away on its own (unless it recurs).

type WarningsOptions

type WarningsOptions struct {
	// All means return all warnings, instead of only the un-okayed ones.
	All bool
}

Jump to

Keyboard shortcuts

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