hawkbit

package
v0.1.0-M4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2023 License: Apache-2.0, EPL-2.0 Imports: 9 Imported by: 0

README

Eclipse hawkBit™ - Client library for Golang

This repository contains the Golang implementation of hawkBit SoftwareUpdatable feature.

The Eclipse Ditto Client for Golang is used for communication.

Table of Contents

Installation

go get github.com/eclipse/hawkbit-clients-golang

Creating and activating a software updatable feature

Each software updatable feature instance requires a ditto.Client and hawkbit.Configuration.

var su *hawkbit.SoftwareUpdatable

// Activate the SoftwareUpdatable feature after Ditto Client is connected.
configDitto := ditto.NewConfiguration().
	WithBroker("mqtt-host:1883").
	WithConnectHandler(func(dittoClient *ditto.Client) {
		if err := su.Activate(); err != nil {
			panic(fmt.Errorf("cannot activate software updatable feature: %v", err))
		}
	})

// Create new Ditto Client instance.
dittoClient := ditto.NewClient(configDitto)

// Create hawkBit SoftwareUpdatable feature configuration.
config := hawkbit.NewConfiguration().
	WithDittoClient(dittoClient).
	WithThingID(model.NewNamespacedIDFrom("my.namespace:thing.id")).
	WithSoftwareType("my-type").
	WithInstallHandler(installHandler)

// Create new hawkBit SoftwareUpdatable instance.
su, err = hawkbit.NewSoftwareUpdatable(config)
if err != nil {
	panic(fmt.Errorf("failed to create software updatable: %v", err))
}

NOTE: All feature propertires can be modified before the feature activation. This will change the initial feature property values.

After you have configured and created software updatable instance, the Ditto client is ready to be connected.

if err := dittoClient.Connect(); err != nil {
    panic(fmt.Errorf("cannot connect to broker: %v", err))
}

It's a good practice to deactivate the feature on client disconnect.

su.Deactivate()
dittoClient.Disconnect()

Working with software updatable feature

Update installed and context dependencies
// Create new DependencyDescription.
dependency := &hawkbit.DependencyDescription{Group: "My Group", Name: "App #1", Version: "1.0.0", Type: "my-type"}

// Update installed dependencies property.
if err := su.SetInstalledDependencies(dependency); err != nil {
	fmt.Println(fmt.Errorf("could not update installed dependencies property: %v", err))
}

// Update context dependencies property.
if err := su.SetContextDependencies(dependency); err != nil {
	fmt.Println(fmt.Errorf("could not update context dependencies property: %v", err))
}
Handle install operation
func installHandler(update *hawkbit.SoftwareUpdateAction, su *hawkbit.SoftwareUpdatable) {
    // Install provided software modules.
	for _, module := range update.SoftwareModules {
		status := hawkbit.NewOperationStatusUpdate(update.CorrelationID, hawkbit.StatusStarted, module.SoftwareModule).
			WithProgress(0).WithMessage("install operation just started")
		if err := su.SetLastOperation(status); err != nil {
			fmt.Println(fmt.Errorf("could not update the last operation: %v", err))
		}
		// Do the installation here.
	}
    // Finally update the installed dependencies.
}

NOTE: The last failed operation will be updated automatically, if needed.

Logging

Various levels of logs are provided by assigning the logging endpoints, ERROR, WARN, INFO and DEBUG. For example:

type LogLevel int

const (
	ERROR LogLevel = 1 + iota
	WARN
	INFO
	DEBUG
)

var level = INFO

func init() {
	hawkbit.ERROR = &wrapper{level: ERROR, prefix: "ERROR  "}
	hawkbit.WARN = &wrapper{level: WARN, prefix: "WARN   "}
	hawkbit.INFO = &wrapper{level: INFO, prefix: "INFO   "}
	hawkbit.DEBUG = &wrapper{level: DEBUG, prefix: "DEBUG  "}
}

type wrapper struct {
	level  LogLevel
	prefix string
}

func (w *wrapper) Println(v ...interface{}) {
	if level >= w.level {
		fmt.Println(w.prefix, fmt.Sprint(v...))
	}
}

func (w *wrapper) Printf(format string, v ...interface{}) {
	if level >= w.level {
		fmt.Printf(fmt.Sprint(w.prefix, " ", format), v...)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CancelHandler

type CancelHandler func(update *SoftwareUpdateAction, softwareUpdatable *SoftwareUpdatable)

CancelHandler represents a callback handler that is called on each received cancel message.

type CancelRemoveHandler

type CancelRemoveHandler func(software *SoftwareRemoveAction, softwareUpdatable *SoftwareUpdatable)

CancelRemoveHandler represents a callback handler that is called on each received cancel remove message.

type Configuration

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

Configuration provides the SoftwareUpdatable's configuration.

func NewConfiguration

func NewConfiguration() *Configuration

NewConfiguration returns a SoftwareUpdatable Configuration with the default feature ID.

func (*Configuration) WithCancelHandler

func (cfg *Configuration) WithCancelHandler(handler CancelHandler) *Configuration

WithCancelHandler configures the handler to be notified when the SoftwareUpdatable receive cancel request.

func (*Configuration) WithCancelRemoveHandler

func (cfg *Configuration) WithCancelRemoveHandler(handler CancelRemoveHandler) *Configuration

WithCancelRemoveHandler configures the handler to be notified when the SoftwareUpdatable receive cancelRemove request.

func (*Configuration) WithDittoClient

func (cfg *Configuration) WithDittoClient(dittoClient *ditto.Client) *Configuration

WithDittoClient configures the Ditto client to be used by the SoftwareUpdatable feature.

func (*Configuration) WithDownloadHandler

func (cfg *Configuration) WithDownloadHandler(handler DownloadHandler) *Configuration

WithDownloadHandler configures the handler to be notified when the SoftwareUpdatable receive download request.

func (*Configuration) WithFeatureID

func (cfg *Configuration) WithFeatureID(featureID string) *Configuration

WithFeatureID configures the SoftwareUpdatable feature identifier.

func (*Configuration) WithInstallHandler

func (cfg *Configuration) WithInstallHandler(handler InstallHandler) *Configuration

WithInstallHandler configures the handler to be notified when the SoftwareUpdatable receive install request.

func (*Configuration) WithRemoveHandler

func (cfg *Configuration) WithRemoveHandler(handler RemoveHandler) *Configuration

WithRemoveHandler configures the handler to be notified when the SoftwareUpdatable receive remove request.

func (*Configuration) WithSoftwareType

func (cfg *Configuration) WithSoftwareType(softwareType string) *Configuration

WithSoftwareType configures the SoftwareUpdatable software type.

func (*Configuration) WithThingID

func (cfg *Configuration) WithThingID(thingID *model.NamespacedID) *Configuration

WithThingID configures the identifier of the thing, where SoftwareUpdatable feature will be registered.

type DependencyDescription

type DependencyDescription struct {
	// Group represents an identifier which groups the dependency into a certain category.
	Group string `json:"group"`
	// Name represents the dependency name.
	Name string `json:"name"`
	// Version Name represents the dependency version.
	Version string `json:"version"`
	// Type represents a "category" classifier for the dependency.
	Type string `json:"type,omitempty"`
}

DependencyDescription describes an installed software or other dependencies for a device.

type DownloadHandler

type DownloadHandler func(update *SoftwareUpdateAction, softwareUpdatable *SoftwareUpdatable)

DownloadHandler represents a callback handler that is called on each received download message.

type Hash

type Hash string

Hash is a representation of the defined by SoftwareUpdatable feature hash algorithms.

const (
	SHA1   Hash = "SHA1"
	SHA256 Hash = "SHA256"
	MD5    Hash = "MD5"
)

Supported hash algorithms.

type InstallHandler

type InstallHandler func(update *SoftwareUpdateAction, softwareUpdatable *SoftwareUpdatable)

InstallHandler represents a callback handler that is called on each received install message.

type Links struct {
	// URL to download the artifact.
	URL string `json:"url"`
	// MD5URL to download the MD5SUM file.
	MD5URL string `json:"md5url,omitempty"`
}

Links represents the datatype for the artifact links.

type Logger

type Logger interface {
	Println(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger interface allows plugging of a logger implementation that fits best the needs of the application that is to use the Ditto library

var (
	INFO  Logger = LoggerStub{}
	WARN  Logger = LoggerStub{}
	DEBUG Logger = LoggerStub{}
	ERROR Logger = LoggerStub{}
)

Levels of the library's output that can be configured during package initialization in init()

type LoggerStub

type LoggerStub struct{}

LoggerStub provides an empty default implementation

func (LoggerStub) Printf

func (LoggerStub) Printf(format string, v ...interface{})

Printf formats according to a format specifier and writes log entry.

func (LoggerStub) Println

func (LoggerStub) Println(v ...interface{})

Println writes log entry with spaces between operands and a newline at the end.

type OperationStatus

type OperationStatus struct {
	// CorrelationID is used for correlating the status-update with the operation called before.
	CorrelationID string `json:"correlationId"`
	// Status represents one of the predefined status, representing the failure, progress or sucess of the operation.
	Status Status `json:"status"`
	// SoftwareModule is required in the case of an install/download/cancel operation, absent in case of
	// remove or cancelRemove.
	SoftwareModule *SoftwareModuleID `json:"softwareModule,omitempty"`
	// Software is required for a remove or cancelRemove operation, absent in case of install/download/cancel.
	Software []*DependencyDescription `json:"software,omitempty"`
	// Progress represents the progress indicator in percentage.
	Progress int `json:"progress,omitempty"`
	// Message from the device to give more context to the transmitted status.
	Message string `json:"message,omitempty"`
	// StatusCode represents a custom status code transmitted by the device.
	StatusCode string `json:"statusCode,omitempty"`
}

OperationStatus represents the status of an operation (install/remove) called on a device.

func NewOperationStatusRemove

func NewOperationStatusRemove(correlationID string, status Status,
	software ...*DependencyDescription) *OperationStatus

NewOperationStatusRemove returns an OperationStatus with the mandatory fields needed for software module remove operation.

func NewOperationStatusUpdate

func NewOperationStatusUpdate(correlationID string, status Status, softwareModule *SoftwareModuleID) *OperationStatus

NewOperationStatusUpdate returns an OperationStatus with the mandatory fields needed for software module update operation.

func (*OperationStatus) WithCorrelationID

func (os *OperationStatus) WithCorrelationID(correlationID string) *OperationStatus

WithCorrelationID sets the correlation id of the operation status.

func (*OperationStatus) WithMessage

func (os *OperationStatus) WithMessage(message string) *OperationStatus

WithMessage sets the message of the operation status.

func (*OperationStatus) WithProgress

func (os *OperationStatus) WithProgress(progress int) *OperationStatus

WithProgress sets the progress of the operation status.

func (*OperationStatus) WithSoftware

func (os *OperationStatus) WithSoftware(software ...*DependencyDescription) *OperationStatus

WithSoftware sets the removed software to the operation status.

func (*OperationStatus) WithSoftwareModule

func (os *OperationStatus) WithSoftwareModule(softwareModule *SoftwareModuleID) *OperationStatus

WithSoftwareModule sets the software module id of the operation status.

func (*OperationStatus) WithStatus

func (os *OperationStatus) WithStatus(status Status) *OperationStatus

WithStatus sets the status of the operation status.

func (*OperationStatus) WithStatusCode

func (os *OperationStatus) WithStatusCode(statusCode string) *OperationStatus

WithStatusCode sets the status code of the operation status.

type Protocol

type Protocol string

Protocol is a representation of the defined by SoftwareUpdatable feature transport protocols.

const (
	HTTP  Protocol = "HTTP"
	HTTPS Protocol = "HTTPS"
	FTP   Protocol = "FTP"
	SFTP  Protocol = "SFTP"
)

Supported transport protocols.

type RemoveHandler

type RemoveHandler func(software *SoftwareRemoveAction, softwareUpdatable *SoftwareUpdatable)

RemoveHandler represents a callback handler that is called on each received remove message.

type SoftwareArtifactAction

type SoftwareArtifactAction struct {
	// Filename is the real file name of the artifact behind the provided URLs.
	Filename string `json:"filename"`
	// Download holds the download options for the artifact.
	Download map[Protocol]*Links `json:"download,omitempty"`
	// Checksums to verify the proper download.
	Checksums map[Hash]string `json:"checksums"`
	// Size of the file in bytes.
	Size int `json:"size"`
}

SoftwareArtifactAction specifications which should be installed.

type SoftwareModuleAction

type SoftwareModuleAction struct {
	// SoftwareModule represents an unique indentifier for the software module.
	SoftwareModule *SoftwareModuleID `json:"softwareModule"`
	// Artifacts represents a list of software artifacts contained in the module.
	Artifacts []*SoftwareArtifactAction `json:"artifacts,omitempty"`
	// Metadata represents any other information which should be passed to the device.
	Metadata map[string]string `json:"metaData,omitempty"`
}

SoftwareModuleAction representing a software module - a collection of artifacts to be downloaded and installed.

type SoftwareModuleID

type SoftwareModuleID struct {
	// Name for the software module.
	Name string `json:"name"`
	// Version of the software module.
	Version string `json:"version"`
}

SoftwareModuleID represents an unique identifier for software modules.

type SoftwareRemoveAction

type SoftwareRemoveAction struct {
	// CorrelationID returns an identifier used to correlate the status updates sent from the device for this action.
	CorrelationID string `json:"correlationId"`
	// Software to be removed.
	Software []*DependencyDescription `json:"software,omitempty"`
	// Weight returns the priority in case of multiple, parallel instructions.
	Weight int `json:"weight,omitempty"`
	// Metadata returns any other information which should be passed to the device.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Forced indicates the urgency of the update. When true, the device should install as soon as possible.
	Forced bool `json:"forced,omitempty"`
}

SoftwareRemoveAction is used for instructing the device to remove a defined set of software.

type SoftwareUpdatable

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

SoftwareUpdatable is the HawkBit's library actual implementation. It provides SoftwareUpdatable capabilities to a specified Thing.

func NewSoftwareUpdatable

func NewSoftwareUpdatable(cfg *Configuration) (*SoftwareUpdatable, error)

NewSoftwareUpdatable creates new SoftwareUpdatable instance, which will manage the SoftwareUdpate feature with the specified type to the provided Thing via Ditto client connection.

func (*SoftwareUpdatable) Activate

func (su *SoftwareUpdatable) Activate() error

Activate subscribes for incoming Ditto messages and send SoftwareUpdatable feature initial information. If any error occurs during the feature initiation - it's returned here.

func (*SoftwareUpdatable) Deactivate

func (su *SoftwareUpdatable) Deactivate()

Deactivate unsubscribes from incoming Ditto messages.

func (*SoftwareUpdatable) SetContextDependencies

func (su *SoftwareUpdatable) SetContextDependencies(deps ...*DependencyDescription) error

SetContextDependencies set the entire set of context dependencies of underlying SoftwareUpdatable feature. Note: Involking this function before the feature activation will change its initial context dependencies value.

func (*SoftwareUpdatable) SetInstalledDependencies

func (su *SoftwareUpdatable) SetInstalledDependencies(deps ...*DependencyDescription) error

SetInstalledDependencies set the entire set of installed dependencies of underlying SoftwareUpdatable feature. Note: Involking this function before the feature activation will change its initial installed dependencies value.

func (*SoftwareUpdatable) SetLastOperation

func (su *SoftwareUpdatable) SetLastOperation(os *OperationStatus) error

SetLastOperation set the last operation and last failed operation (if needed) of underlying SoftwareUpdatable feature. Note: Involking this function before the feature activation will change its initial last operation and last failed operation values.

type SoftwareUpdateAction

type SoftwareUpdateAction struct {
	// CorrelationID returns an identifier used to correlate the status updates sent from the device for this action.
	CorrelationID string `json:"correlationId"`
	// SoftwareModules that needs to be processed.
	SoftwareModules []*SoftwareModuleAction `json:"softwareModules,omitempty"`
	// Weight returns the priority in case of multiple, parallel installation instructions.
	Weight int `json:"weight,omitempty"`
	// Metadata returns any other information which should be passed to the device.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Forced indicates the urgency of the update. When true, the device should install as soon as possible.
	Forced bool `json:"forced,omitempty"`
}

SoftwareUpdateAction is used for instructing the device to install or download one or more software.

type Status

type Status string

Status is representing the failure, progress or sucess of the operation.

const (
	StatusStarted            Status = "STARTED"
	StatusDownloading        Status = "DOWNLOADING"
	StatusDownloadingWaiting Status = "DOWNLOADING_WAITING"
	StatusDownloaded         Status = "DOWNLOADED"
	StatusInstalling         Status = "INSTALLING"
	StatusInstallingWaiting  Status = "INSTALLING_WAITING"
	StatusInstalled          Status = "INSTALLED"
	StatusRemoving           Status = "REMOVING"
	StatusRemovingWaiting    Status = "REMOVING_WAITING"
	StatusRemoved            Status = "REMOVED"
	StatusCancelingWaiting   Status = "CANCELING_WAITING"
	StatusCancelRejected     Status = "CANCEL_REJECTED"
	StatusFinishedCanceled   Status = "FINISHED_CANCELED"
	StatusFinishedError      Status = "FINISHED_ERROR"
	StatusFinishedSuccess    Status = "FINISHED_SUCCESS"
	StatusFinishedWarning    Status = "FINISHED_WARNING"
	StatusFinishedRejected   Status = "FINISHED_REJECTED"
)

Supported operation statuses.

Jump to

Keyboard shortcuts

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