agent

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 34 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 time.Duration = 0

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 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.

address is the ShellHub Server address the agent will use to connect, tenantID is the namespace where the device will be registered and privateKey is the path to the device private key. If privateKey is empty, a new key will be generated.

To add a full customisation configuration, use NewAgentWithConfig instead.

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 a custom configuration.

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

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 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 a new SSH server, through a reverse connection between the Agent and the ShellHub server.

func (*Agent) NewReverseListener

func (a *Agent) NewReverseListener(ctx context.Context) (*revdial.Listener, error)

func (*Agent) Ping

func (a *Agent) Ping(ctx context.Context, durantion time.Duration) error

Ping sends an authtorization request to the server every ticker interval.

If the durantion is 0, the default value set to it will be the 10 minutes.

Ping will only sends its requests to the server if the agent is listening for connections. If the agent is not listening, the ping will be stopped.

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,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="`

	// Set 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:"SIMPLE_USER_PASSWORD"`
}

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.

The Agent can be executed in two different modes: `Host` and `Connector`. The `Host` mode is the default one, where the agent will listen for incoming connections and use the host device as source of any information needed to start itself. When running in `Connector` mode, it uses the Docker engine as this source.

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