agent

package
v0.18.0-rc.3 Latest Latest
Warning

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

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

Documentation

Overview

Package agent provides packages and functions to create a new ShellHub Agent instance.

The ShellHub Agent is a lightweight software component that runs the device and provide communication between the device and ShellHub's server. Its main role is to provide a reserve SSH server always connected to the ShellHub server, allowing SSH connections to be established to the device even when it is behind a firewall or NAT.

This package provides a simple API to create a new agent instance and start the communication with the server. The agent will automatically connect to the server and start listening for incoming connections. Once connected, the agent will also automatically reconnect to the server if the connection is lost.

The update process isn't handled by this package. This feature is provided by its main implementation in ShellHub Agent. Check the ShellHub Agent documentation for more information.

Example:

Creates the agent configuration with the minimum required fields:

func main() {
    cfg := Config{
        ServerAddress: "http://localhost:80",
        TenantID:      "00000000-0000-4000-0000-000000000000",
        PrivateKey:    "/tmp/shellhub.key",
    }

    ctx := context.Background()
    ag, err := NewAgentWithConfig(&cfg)
    if err != nil {
        panic(err)
    }

    if err := ag.Initialize(); err != nil {
        panic(err)
    }

    ag.Listen(ctx)
}

Index

Examples

Constants

View Source
const AgentPingDefaultInterval = 10 * time.Minute

AgentPingDefaultInterval is the default time interval between ping on agent.

Variables

View Source
var (
	ErrNewAgentWithConfigEmptyServerAddress   = errors.New("address is empty")
	ErrNewAgentWithConfigInvalidServerAddress = errors.New("address is invalid")
	ErrNewAgentWithConfigEmptyTenant          = errors.New("tenant is empty")
	ErrNewAgentWithConfigEmptyPrivateKey      = errors.New("private key is empty")
	ErrNewAgentWithConfigNilMode              = errors.New("agent's mode is nil")
)
View Source
var AgentPlatform string

AgentPlatform stores what platform the agent is running on. This is injected in build time in the ShellHub Agent implementation.

View Source
var AgentVersion string

AgentVersion store the version to be embed inside the binary. This is injected using `-ldflags` build option.

go build -ldflags "-X main.AgentVersion=1.2.3"

If set to `latest`, the auto-updating mechanism is disabled. This is intended to be used during development only.

Functions

func GetInfo added in v0.16.0

func GetInfo(cfg *Config) (*models.Info, error)

GetInfo gets information like the version and the enpoints for HTTP and SSH to ShellHub server.

func NewSFTPServer

func NewSFTPServer(mode command.SFTPServerMode)

NewSFTPServer creates a new SFTP server when a new session is created between the agent and the server.

Types

type Agent

type Agent struct {
	Identity *models.DeviceIdentity
	Info     *models.DeviceInfo
	// contains filtered or unexported fields
}

func NewAgent

func NewAgent(address string, tenantID string, privateKey string, mode Mode) (*Agent, error)

NewAgent creates a new agent instance, requiring the ShellHub server's address to connect to, the namespace's tenant where device own and the path to the private key on the file system.

To create a new Agent instance with all configurations, you can use NewAgentWithConfig.

Example
_, err := NewAgent("http://localhost:80", "00000000-0000-4000-0000-000000000000", "./shellhub.key", new(HostMode))
if err != nil {
	panic(err)
}
Output:

func NewAgentWithConfig

func NewAgentWithConfig(config *Config, mode Mode) (*Agent, error)

NewAgentWithConfig creates a new agent instance with all configurations.

Check Config for more information.

Example
_, err := NewAgentWithConfig(&Config{
	ServerAddress: "http://localhost:80",
	TenantID:      "00000000-0000-4000-0000-000000000000",
	PrivateKey:    "./shellhub.key",
}, new(HostMode))
if err != nil {
	panic(err)
}
Output:

func (*Agent) CheckUpdate

func (a *Agent) CheckUpdate() (*semver.Version, error)

CheckUpdate gets the ShellHub's server version.

func (*Agent) Close added in v0.13.0

func (a *Agent) Close() error

Close closes the ShellHub Agent's listening, stoping it from receive new connection requests.

func (*Agent) GetInfo

func (a *Agent) GetInfo() (*models.Info, error)

GetInfo gets the ShellHub's server information like version and endpoints, and updates the Agent's server's info.

func (*Agent) Initialize

func (a *Agent) Initialize() error

Initialize initializes the ShellHub Agent, generating device identity, loading device information, generating private key, reading public key, probing server information and authorizing device on ShellHub server.

When any of the steps fails, the agent will return an error, and the agent will not be able to start.

func (*Agent) Listen

func (a *Agent) Listen(ctx context.Context) error

Listen creates the SSH server and listening for connections.

type Config

type Config struct {
	// Set the ShellHub Cloud server address the agent will use to connect.
	// This is required.
	ServerAddress string `env:"SERVER_ADDRESS,required" validate:"required"`

	// Specify the path to the device private key.
	// If not provided, the agent will generate a new one.
	// This is required.
	PrivateKey string `env:"PRIVATE_KEY,required" validate:"required"`

	// Sets the account tenant id used during communication to associate the
	// device to a specific tenant.
	// This is required.
	TenantID string `env:"TENANT_ID,required" validate:"required"`

	// Determine the interval to send the keep alive message to the server. This
	// has a direct impact of the bandwidth used by the device when in idle
	// state. Default is 30 seconds.
	KeepAliveInterval uint `env:"KEEPALIVE_INTERVAL,overwrite,default=30"`

	// Set the device preferred hostname. This provides a hint to the server to
	// use this as hostname if it is available.
	PreferredHostname string `env:"PREFERRED_HOSTNAME"`

	// Set the device preferred identity. This provides a hint to the server to
	// use this identity if it is available.
	PreferredIdentity string `env:"PREFERRED_IDENTITY,default="`

	// Stores the password for single-user mode (without root privileges). If not
	// provided, multi-user mode (with root privileges) is enabled by default.
	// NOTE: The password hash could be generated by “`openssl passwd“`.
	SingleUserPassword string `env:"SINGLE_USER_PASSWORD,default=$SIMPLE_USER_PASSWORD"`

	// SimpleUserPassword exists due to a typo on the environmental variable that stores the password for single user
	// mode that was wrongly named `SIMPLE_USER_PASSWORD` instead of `SINGLE_USER_PASSWORD`, and willing to keep the
	// compatibility, this new variable was created.
	SimpleUserPassword string `env:"SIMPLE_USER_PASSWORD"`

	// MaxRetryConnectionTimeout specifies the maximum time, in seconds, that an agent will wait
	// before attempting to reconnect to the ShellHub server. Default is 60 seconds.
	MaxRetryConnectionTimeout int `env:"MAX_RETRY_CONNECTION_TIMEOUT,default=60" validate:"min=10,max=120"`
}

Config provides the configuration for the agent service.

func LoadConfigFromEnv added in v0.15.0

func LoadConfigFromEnv() (*Config, map[string]interface{}, error)

type ConnectorMode added in v0.14.0

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

ModeConnector is the Agent execution mode for `Connector`.

The `Connector` mode is used to turn a container inside a host into a single device ShellHub's Agent. The host is responsible for the SSH server, but the authentication and authorization is made by either the conainer internals, `passwd` or `shadow`, or by the ShellHub API.

func (*ConnectorMode) GetInfo added in v0.14.0

func (m *ConnectorMode) GetInfo() (*Info, error)

func (*ConnectorMode) Serve added in v0.14.0

func (m *ConnectorMode) Serve(agent *Agent)

type HostMode added in v0.14.0

type HostMode struct{}

ModeHost is the Agent execution mode for `Host`.

The host mode is the default mode one, and turns the host machine into a ShellHub's Agent. The host is responsible for the SSH server, authentication and authorization, `/etc/passwd`, `/etc/shadow`, and etc.

func (*HostMode) GetInfo added in v0.14.0

func (m *HostMode) GetInfo() (*Info, error)

func (*HostMode) Serve added in v0.14.0

func (m *HostMode) Serve(agent *Agent)

type Info added in v0.14.0

type Info struct {
	ID   string
	Name string
}

type Mode added in v0.13.0

type Mode interface {
	// Serve prepares the Agent for listening, setting up the SSH server, its modes and values on Agent's.
	Serve(agent *Agent)
	// GetInfo gets information about Agent according to Agent's mode.
	//
	// When Agent is running on [HostMode], the info got is from the system where the Agent is running, but when running
	// in [ConnectorMode], the data is retrieved from Docker Engine.
	GetInfo() (*Info, error)
}

Mode is the Agent execution mode.

Check HostMode and ConnectorMode for more information.

func NewConnectorMode added in v0.14.0

func NewConnectorMode(cli *dockerclient.Client, identity string) (Mode, error)

Directories

Path Synopsis
pkg
modes
Package mode defines the interfaces used by the server to determine how to handle authentication and sessions.
Package mode defines the interfaces used by the server to determine how to handle authentication and sessions.
modes/connector
Package connector defines methods for authentication and sessions handles to SSH when it is running in connector mode.
Package connector defines methods for authentication and sessions handles to SSH when it is running in connector mode.
modes/host
Package host defines authentication and sessions handles to SSH when it is running in host mode.
Package host defines authentication and sessions handles to SSH when it is running in host mode.

Jump to

Keyboard shortcuts

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