rig

package module
v0.11.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2023 License: Apache-2.0 Imports: 41 Imported by: 36

README

Rig

A golang package for adding multi-protocol connectivity and multi-os operation functionality to your application's Host objects.

Design goals

Rig's intention is to be easy to use and extend.

It should be easy to add support for new operating systems and to add new commands to the multi-os support mechanism without breaking go's type checking.

All of the relevant structs have YAML tags and default values to make unmarshaling from YAML configurations as easy as possible.

Protocols

Currently rig comes with the most common ways to connect to hosts:

  • SSH for connecting to hosts that accept SSH connections. Pageant or openssh agent can be used on Windows.
  • WinRM as an alternative to SSH for windows hosts (SSH works too)
  • Local for treating the localhost as it was one of the remote hosts

Usage

The intended way to use rig is to embed the rig.Connection struct into your own.

Example:

package main

import "github.com/k0sproject/rig"

type host struct {
  rig.Connection
}

func main() {
  h := host{
    connection: rig.Connection{
      SSH: &rig.SSH{
        Address: 10.0.0.1
      }
    }
  }

  if err := h.Connect(); err != nil {
    panic(err)
  }

  output, err := h.ExecOutput("ls -al")
  if err != nil {
    panic(err)
  }
  println(output)
}

But of course you can use it directly on its own too:

package main

import "github.com/k0sproject/rig"

func main() {
  h := rig.Connection{
    SSH: &rig.SSH{
      Address: 10.0.0.1
    }
  }

  if err := h.Connect(); err != nil {
    panic(err)
  }
}

See more usage examples in the examples/ directory.

Documentation

Overview

Package rig provides an easy way to add multi-protocol connectivity and multi-os operation support to your application's Host objects

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrOS               = errstring.New("local os")              // ErrOS is returned when an action fails on local OS
	ErrInvalidPath      = errstring.New("invalid path")          // ErrInvalidPath is returned when a path is invalid
	ErrValidationFailed = errstring.New("validation failed")     // ErrValidationFailed is returned when a validation fails
	ErrSudoRequired     = errstring.New("sudo required")         // ErrSudoRequired is returned when sudo is required
	ErrNotFound         = errstring.New("not found")             // ErrNotFound is returned when a resource is not found
	ErrNotImplemented   = errstring.New("not implemented")       // ErrNotImplemented is returned when a feature is not implemented
	ErrNotSupported     = errstring.New("not supported")         // ErrNotSupported is returned when a feature is not supported
	ErrAuthFailed       = errstring.New("authentication failed") // ErrAuthFailed is returned when authentication fails
	ErrUploadFailed     = errstring.New("upload failed")         // ErrUploadFailed is returned when an upload fails
	ErrNotConnected     = errstring.New("not connected")         // ErrNotConnected is returned when a connection is not established
	ErrCantConnect      = errstring.New("can't connect")         // ErrCantConnect is returned when a connection is not established and retrying will fail
	ErrCommandFailed    = errstring.New("command failed")        // ErrCommandFailed is returned when a command fails
)
View Source
var (
	// ErrNotRunning is returned when the rigrcp process is not running
	ErrNotRunning = errstring.New("rigrcp is not running")
	// ErrRcpCommandFailed is returned when a command to the rigrcp process fails
	ErrRcpCommandFailed = errstring.New("rigrcp command failed")
)
View Source
var (

	// ErrChecksumMismatch is returned when the checksum of an uploaded file does not match expectation
	ErrChecksumMismatch = errstring.New("checksum mismatch")
)
View Source
var ErrSSHAgent = errstring.New("connect ssh agent")

ErrSSHAgent is returned when connection to SSH agent fails

View Source
var (
	// Resolvers exposes an array of resolve functions where you can add your own if you need to detect some OS rig doesn't already know about
	// (consider making a PR)
	Resolvers = []resolveFunc{resolveLinux, resolveDarwin, resolveWindows}
)
View Source
var SSHConfigGetAll = ssh_config.GetAll

SSHConfigGetAll by default points to ssh_config package's GetAll() function you can override it with your own implementation for testing purposes

Functions

func GroupParams added in v0.4.3

func GroupParams(params ...any) ([]exec.Option, []any)

GroupParams separates exec.Options from other sprintf templating args

func SetLogger

func SetLogger(logger log.Logger)

SetLogger can be used to assign your own logger to rig

Types

type Command added in v0.11.0

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

Command implements the Waiter interface

func (*Command) Wait added in v0.11.0

func (c *Command) Wait() error

Wait blocks until the command finishes

type Connection

type Connection struct {
	WinRM     *WinRM     `yaml:"winRM,omitempty"`
	SSH       *SSH       `yaml:"ssh,omitempty"`
	Localhost *Localhost `yaml:"localhost,omitempty"`

	OSVersion *OSVersion `yaml:"-"`
	// contains filtered or unexported fields
}

Connection is a Struct you can embed into your application's "Host" types to give them multi-protocol connectivity.

All of the important fields have YAML tags.

If you have a host like this:

type Host struct {
  rig.Connection `yaml:"connection"`
}

and a YAML like this:

hosts:
  - connection:
      ssh:
        address: 10.0.0.1
        port: 8022

you can then simply do this:

var hosts []*Host
if err := yaml.Unmarshal(data, &hosts); err != nil {
  panic(err)
}
for _, h := range hosts {
  err := h.Connect()
  if err != nil {
    panic(err)
  }
  output, err := h.ExecOutput("echo hello")
}

func (*Connection) Address added in v0.3.3

func (c *Connection) Address() string

Address returns the connection address

func (*Connection) Connect

func (c *Connection) Connect() error

Connect to the host and identify the operating system and sudo capability

func (*Connection) Disconnect

func (c *Connection) Disconnect()

Disconnect from the host

func (Connection) Exec

func (c Connection) Exec(cmd string, opts ...exec.Option) error

Exec runs a command on the host

func (Connection) ExecInteractive

func (c Connection) ExecInteractive(cmd string) error

ExecInteractive executes a command on the host and passes control of local input to the remote command

func (Connection) ExecOutput

func (c Connection) ExecOutput(cmd string, opts ...exec.Option) (string, error)

ExecOutput runs a command on the host and returns the output as a String

func (Connection) ExecOutputf

func (c Connection) ExecOutputf(s string, params ...any) (string, error)

ExecOutputf is like ExecOutput but you can use Sprintf templating for the command

func (Connection) ExecStreams added in v0.11.0

func (c Connection) ExecStreams(cmd string, stdin io.ReadCloser, stdout, stderr io.Writer, opts ...exec.Option) (Waiter, error)

ExecStreams executes a command on the remote host and uses the passed in streams for stdin, stdout and stderr. It returns a Waiter with a .Wait() function that blocks until the command finishes and returns an error if the exit code is not zero.

func (Connection) Execf

func (c Connection) Execf(s string, params ...any) error

Execf is just like `Exec` but you can use Sprintf templating for the command

func (*Connection) Fsys added in v0.11.0

func (c *Connection) Fsys() FS

Fsys returns a fs.FS compatible filesystem interface for accessing files on remote hosts

func (*Connection) IsConnected

func (c *Connection) IsConnected() bool

IsConnected returns true if the client is assumed to be connected. "Assumed" - as in `Connect()` has been called and no error was returned. The underlying client may actually have disconnected and has become inoperable, but rig won't know that until you try to execute commands on the connection.

func (*Connection) IsWindows

func (c *Connection) IsWindows() bool

IsWindows returns true on windows hosts

func (*Connection) Protocol added in v0.3.3

func (c *Connection) Protocol() string

Protocol returns the connection protocol name

func (*Connection) SetDefaults

func (c *Connection) SetDefaults()

SetDefaults sets a connection

func (Connection) String

func (c Connection) String() string

String returns a printable representation of the connection, which will look like: `[ssh] address:port`

func (Connection) Sudo added in v0.4.0

func (c Connection) Sudo(cmd string) (string, error)

Sudo formats a command string to be run with elevated privileges

func (*Connection) SudoFsys added in v0.11.0

func (c *Connection) SudoFsys() FS

SudoFsys returns a fs.FS compatible filesystem interface for accessing files on remote hosts with sudo permissions

func (*Connection) Upload

func (c *Connection) Upload(src, dst string, opts ...exec.Option) error

Upload copies a file from a local path src to the remote host path dst. For smaller files you should probably use os.WriteFile

type FS

type FS interface {
	Open(name string) (fs.File, error)
	OpenFile(name string, mode FileMode, perm int) (File, error)
	Stat(name string) (fs.FileInfo, error)
	Sha256(name string) (string, error)
	ReadDir(name string) ([]fs.DirEntry, error)
	Delete(name string) error
}

FS is a fs.FS compatible filesystem interface for filesystems on remote hosts

type File

type File interface {
	Seek(int64, int) (int64, error)
	CopyFromN(io.Reader, int64, io.Writer) (int64, error)
	Copy(io.Writer) (int, error)
	Write([]byte) (int, error)
	Read([]byte) (int, error)
	Stat() (fs.FileInfo, error)
	Close() error
}

File is a file on a remote host

type FileInfo

type FileInfo struct {
	FName    string      `json:"name"`
	FSize    int64       `json:"size"`
	FMode    fs.FileMode `json:"mode"`
	FUnix    fs.FileMode `json:"unixMode"`
	FModTime time.Time   `json:"-"`
	FIsDir   bool        `json:"isDir"`
	ModtimeS int64       `json:"modTime"`
	// contains filtered or unexported fields
}

FileInfo implements fs.FileInfo for stat on remote files

func (*FileInfo) FullPath

func (f *FileInfo) FullPath() string

FullPath returns the full path

func (*FileInfo) Info

func (f *FileInfo) Info() (fs.FileInfo, error)

Info returns self. It's here to satisfy fs.DirEntry interface.

func (*FileInfo) IsDir

func (f *FileInfo) IsDir() bool

IsDir returns true if the file path points to a directory

func (*FileInfo) ModTime

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

ModTime returns the last modification time of a file

func (*FileInfo) Mode

func (f *FileInfo) Mode() fs.FileMode

Mode returns the file permission mode

func (*FileInfo) Name

func (f *FileInfo) Name() string

Name returns the file name

func (*FileInfo) Size

func (f *FileInfo) Size() int64

Size returns the file size

func (*FileInfo) Sys

func (f *FileInfo) Sys() any

Sys returns the underlying data source

func (*FileInfo) Type

func (f *FileInfo) Type() fs.FileMode

Type returns the file type. It's here to satisfy fs.DirEntry interface.

func (*FileInfo) UnmarshalJSON

func (f *FileInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler

type FileMode

type FileMode int

FileMode is used to set the type of allowed operations when opening remote files

const (
	ModeRead      FileMode = 1                    // ModeRead = Read only
	ModeWrite     FileMode = 2                    // ModeWrite = Write only
	ModeReadWrite FileMode = ModeRead | ModeWrite // ModeReadWrite = Read and Write
	ModeCreate    FileMode = 4 | ModeWrite        // ModeCreate = Create a new file or truncate an existing one. Includes write permission.
	ModeAppend    FileMode = 8 | ModeCreate       // ModeAppend = Append to an existing file. Includes create and write permissions.
)

type Localhost

type Localhost struct {
	Enabled bool `yaml:"enabled" validate:"required,eq=true" default:"true"`
}

Localhost is a direct localhost connection

func (*Localhost) Connect

func (c *Localhost) Connect() error

Connect on local connection does nothing

func (*Localhost) Disconnect

func (c *Localhost) Disconnect()

Disconnect on local connection does nothing

func (*Localhost) Exec

func (c *Localhost) Exec(cmd string, opts ...exec.Option) error

Exec executes a command on the host

func (*Localhost) ExecInteractive

func (c *Localhost) ExecInteractive(cmd string) error

ExecInteractive executes a command on the host and copies stdin/stdout/stderr from local host

func (*Localhost) ExecStreams added in v0.11.0

func (c *Localhost) ExecStreams(cmd string, stdin io.ReadCloser, stdout, stderr io.Writer, opts ...exec.Option) (Waiter, error)

ExecStreams executes a command on the remote host and uses the passed in streams for stdin, stdout and stderr. It returns a Waiter with a .Wait() function that blocks until the command finishes and returns an error if the exit code is not zero.

func (*Localhost) IPAddress added in v0.3.3

func (c *Localhost) IPAddress() string

IPAddress returns the connection address

func (*Localhost) IsConnected

func (c *Localhost) IsConnected() bool

IsConnected for local connections is always true

func (*Localhost) IsWindows

func (c *Localhost) IsWindows() bool

IsWindows is true when running on a windows host

func (*Localhost) Protocol added in v0.3.3

func (c *Localhost) Protocol() string

Protocol returns the protocol name, "Local"

func (*Localhost) String

func (c *Localhost) String() string

String returns the connection's printable name

type OSVersion

type OSVersion struct {
	ID      string
	IDLike  string
	Name    string
	Version string
}

OSVersion host operating system version information

func GetOSVersion

func GetOSVersion(conn *Connection) (OSVersion, error)

GetOSVersion runs through the Resolvers and tries to figure out the OS version information

func (*OSVersion) String

func (o *OSVersion) String() string

String returns a human readable representation of OSVersion

type PasswordCallback added in v0.7.0

type PasswordCallback func() (secret string, err error)

PasswordCallback is a function that is called when a passphrase is needed to decrypt a private key

type SSH

type SSH struct {
	Address          string           `yaml:"address" validate:"required,hostname|ip"`
	User             string           `yaml:"user" validate:"required" default:"root"`
	Port             int              `yaml:"port" default:"22" validate:"gt=0,lte=65535"`
	KeyPath          *string          `yaml:"keyPath" validate:"omitempty"`
	HostKey          string           `yaml:"hostKey,omitempty"`
	Bastion          *SSH             `yaml:"bastion,omitempty"`
	PasswordCallback PasswordCallback `yaml:"-"`
	// contains filtered or unexported fields
}

SSH describes an SSH connection

func (*SSH) Connect

func (c *SSH) Connect() error

Connect opens the SSH connection

func (*SSH) Disconnect

func (c *SSH) Disconnect()

Disconnect closes the SSH connection

func (*SSH) Exec

func (c *SSH) Exec(cmd string, opts ...exec.Option) error

Exec executes a command on the host

func (*SSH) ExecInteractive

func (c *SSH) ExecInteractive(cmd string) error

ExecInteractive executes a command on the host and copies stdin/stdout/stderr from local host

func (*SSH) ExecStreams added in v0.11.0

func (c *SSH) ExecStreams(cmd string, stdin io.ReadCloser, stdout, stderr io.Writer, opts ...exec.Option) (Waiter, error)

ExecStreams executes a command on the remote host and uses the passed in streams for stdin, stdout and stderr. It returns a Waiter with a .Wait() function that blocks until the command finishes and returns an error if the exit code is not zero.

func (*SSH) IPAddress added in v0.3.3

func (c *SSH) IPAddress() string

IPAddress returns the connection address

func (*SSH) IsConnected

func (c *SSH) IsConnected() bool

IsConnected returns true if the client is connected

func (*SSH) IsWindows

func (c *SSH) IsWindows() bool

IsWindows is true when the host is running windows

func (*SSH) Protocol added in v0.3.3

func (c *SSH) Protocol() string

Protocol returns the protocol name, "SSH"

func (*SSH) SetDefaults

func (c *SSH) SetDefaults()

SetDefaults sets various default values

func (*SSH) String

func (c *SSH) String() string

String returns the connection's printable name

type Waiter

type Waiter interface {
	Wait() error
}

Waiter is an interface that has a Wait() function that blocks until a command is finished

type WinRM

type WinRM struct {
	Address       string `yaml:"address" validate:"required,hostname|ip"`
	User          string `yaml:"user" validate:"omitempty,gt=2" default:"Administrator"`
	Port          int    `yaml:"port" default:"5985" validate:"gt=0,lte=65535"`
	Password      string `yaml:"password,omitempty"`
	UseHTTPS      bool   `yaml:"useHTTPS" default:"false"`
	Insecure      bool   `yaml:"insecure" default:"false"`
	UseNTLM       bool   `yaml:"useNTLM" default:"false"`
	CACertPath    string `yaml:"caCertPath,omitempty" validate:"omitempty,file"`
	CertPath      string `yaml:"certPath,omitempty" validate:"omitempty,file"`
	KeyPath       string `yaml:"keyPath,omitempty" validate:"omitempty,file"`
	TLSServerName string `yaml:"tlsServerName,omitempty" validate:"omitempty,hostname|ip"`
	Bastion       *SSH   `yaml:"bastion,omitempty"`
	// contains filtered or unexported fields
}

WinRM describes a WinRM connection with its configuration options

func (*WinRM) Connect

func (c *WinRM) Connect() error

Connect opens the WinRM connection

func (*WinRM) Disconnect

func (c *WinRM) Disconnect()

Disconnect closes the WinRM connection

func (*WinRM) Exec

func (c *WinRM) Exec(cmd string, opts ...exec.Option) error

Exec executes a command on the host

func (*WinRM) ExecInteractive

func (c *WinRM) ExecInteractive(cmd string) error

ExecInteractive executes a command on the host and copies stdin/stdout/stderr from local host

func (*WinRM) ExecStreams added in v0.11.0

func (c *WinRM) ExecStreams(cmd string, stdin io.ReadCloser, stdout, stderr io.Writer, opts ...exec.Option) (Waiter, error)

ExecStreams executes a command on the remote host and uses the passed in streams for stdin, stdout and stderr. It returns a Waiter with a .Wait() function that blocks until the command finishes and returns an error if the exit code is not zero.

func (*WinRM) IPAddress added in v0.3.3

func (c *WinRM) IPAddress() string

IPAddress returns the connection address

func (*WinRM) IsConnected

func (c *WinRM) IsConnected() bool

IsConnected returns true if the client is connected

func (*WinRM) IsWindows

func (c *WinRM) IsWindows() bool

IsWindows always returns true on winrm

func (*WinRM) Protocol added in v0.3.3

func (c *WinRM) Protocol() string

Protocol returns the protocol name, "WinRM"

func (*WinRM) SetDefaults

func (c *WinRM) SetDefaults()

SetDefaults sets various default values

func (*WinRM) String

func (c *WinRM) String() string

String returns the connection's printable name

Directories

Path Synopsis
cmd
rigtest command
Package errstring defines a simple error struct
Package errstring defines a simple error struct
examples
confirmation command
logging command
os/stock command
password command
upload command
Package exec provides helpers for setting execution options for commands
Package exec provides helpers for setting execution options for commands
Package log provides a simple pluggable logging interface
Package log provides a simple pluggable logging interface
os
Package os provides a platform-independent interface to operating system functionality.
Package os provides a platform-independent interface to operating system functionality.
initsystem
Package initsystem provides an abstraction over several supported init systems.
Package initsystem provides an abstraction over several supported init systems.
linux
Package linux contains configurers for various linux based distributions
Package linux contains configurers for various linux based distributions
linux/enterpriselinux
Package enterpriselinux provides OS modules for Enterprise Linux based distributions
Package enterpriselinux provides OS modules for Enterprise Linux based distributions
mac
Package darwin provides a configurer for macOS
Package darwin provides a configurer for macOS
registry
Package registry is a registry of OS support modules
Package registry is a registry of OS support modules
support
Package support can be imported to load all the stock os support packages.
Package support can be imported to load all the stock os support packages.
windows
Package windows provides OS support for Windows.
Package windows provides OS support for Windows.
pkg
ssh/hostkey
Package hostkey implements a callback for the ssh.ClientConfig.HostKeyCallback
Package hostkey implements a callback for the ssh.ClientConfig.HostKeyCallback
Package powershell provides helpers for powershell command generation
Package powershell provides helpers for powershell command generation

Jump to

Keyboard shortcuts

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