ota

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

OTA Service

The OTA service rolls out firmware to things over the air. A user creates an update for a set of things in a group, the service notifies those things, and each thing reports its progress until it runs the new firmware or fails. Firmware files are stored by the filestore service as group files.

Updates

An update describes the firmware and who should install it.

Field Description
id Update ID (UUID)
group_id Group of the things being updated
file_name Name of the firmware group file in the filestore service
version Version things must report on success
file_size Firmware size in bytes
checksum Hex-encoded SHA-256 of the firmware, for the thing to verify the download
description Free text
timeout Seconds without progress after which a thing is marked failed (default 24h, max 7 days)
status in_progress, completed or completed_with_failures, derived from its things
stats Number of the update's things by status

Each thing of an update has its own progress: status, error, reported_version and updated_at.

Thing status
pending ─► downloading ─► installing ─► succeeded
   │            │              │
   └────────────┴──────────────┴──────► failed
Status Meaning
pending The thing has not started the update yet
downloading The thing is downloading the firmware
installing The thing is installing the firmware
succeeded The thing reported the update's version
failed The thing reported an error or another version, timed out, or was superseded
Update status

The update stores its stats and status, and every change of its things updates them in the same transaction. Use status to filter the updates list with ?status=, and status or a stats count (targets, pending, downloading, installing, succeeded, failed) to sort it with ?order=.

Status Meaning
in_progress At least one thing is pending, downloading or installing
completed No thing is running or failed
completed_with_failures No thing is running and at least one failed

An update whose things were all removed (deleted or moved to another group) is completed.

How it works

  1. Create. A user creates an update for things of a group (POST /groups/{id}/updates). Every thing starts as pending. A thing runs at most one update at a time: its older running update is marked failed with superseded by update <id>.

  2. Notify. The service publishes the update on each thing's things/<id>/ota/update topic. Online things receive it over MQTT by subscribing to things/<id>/ota/update. Only the OTA service can publish there, so other things and users can't send a forged update. Things that were offline fetch it on reconnect with GET /ota/pending, which answers 204 with no body when nothing is pending. The update is:

    {
      "update_id": "…",
      "version": "1.4.0",
      "file_name": "fw-sensor-1.4.0.bin",
      "url": "https://<host>/fs/groupfiles/fw-sensor-1.4.0.bin",
      "size": 421888,
      "checksum": "9f2c…"
    }
    

    GET /ota/pending delivers it as is. MQTT delivers it inside the standard command message, under payload:

    {
      "created": 1793096198368527190,
      "subtopic": "update",
      "recipientID": "<thing id>",
      "protocol": "ota",
      "payload": { "update_id": "…", "version": "1.4.0", … }
    }
    
  3. Download. The thing downloads the firmware from url with its thing key, resuming with HTTP Range requests if needed, and verifies the SHA-256 checksum.

  4. Report. The thing reports {"update_id", "status", "version", "error"} with POST /ota/status, or by publishing on its things/<id>/ota/status topic over MQTT. A thing can report only its own status. Reports are not messages: they reach only the OTA service, are not stored as telemetry and don't trigger rules or webhooks. A succeeded report must include version; without it the report is rejected and the status is unchanged. If version differs from the update's version, the thing is marked failed.

  5. Timeout. Things without progress for the update's timeout are marked failed with timed out. The service checks this every MF_OTA_TIMEOUT_CHECK_INTERVAL. A failed thing stays failed even if it reports later, e.g. succeeded after a timeout; retry the update to track it again.

  6. Retry. A user can move the failed things of an update back to pending (POST /updates/{id}/retry); they are notified again. Things with a newer update are skipped. Preventing a downgrade is the firmware's job. The service never retries on its own.

Authorization is delegated to the Things service: viewing updates requires viewer access on the group, while creating, retrying or removing updates requires editor access. Things authenticate with their thing key. Updates and progress are removed when their group or thing is removed, and a thing's progress is removed when it moves to another group. A retry is refused while any of its failed things is outside the update's group.

Configuration

The service is configured using the environment variables presented in the following table. Note that any unset variables will be replaced with their default values.

Variable Description Default
MF_OTA_LOG_LEVEL Log level for the OTA service (debug, info, warn, error) error
MF_BROKER_URL Message broker instance URL nats://localhost:4222
MF_OTA_HTTP_PORT OTA service HTTP port 9032
MF_JAEGER_URL Jaeger server URL for distributed tracing. Leave empty to disable tracing.
MF_OTA_DB_HOST Database host address localhost
MF_OTA_DB_PORT Database host port 5432
MF_OTA_DB_USER Database user mainflux
MF_OTA_DB_PASS Database password mainflux
MF_OTA_DB Name of the database used by the service ota
MF_OTA_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MF_OTA_DB_SSL_CERT Path to the PEM encoded certificate file
MF_OTA_DB_SSL_KEY Path to the PEM encoded key file
MF_OTA_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file
MF_OTA_CLIENT_TLS Flag that indicates if TLS should be turned on false
MF_OTA_CA_CERTS Path to trusted CAs in PEM format
MF_OTA_SERVER_CERT Path to server certificate in PEM format
MF_OTA_SERVER_KEY Path to server key in PEM format
MF_THINGS_AUTH_GRPC_URL Things service Auth gRPC URL localhost:8183
MF_THINGS_AUTH_GRPC_TIMEOUT Things service Auth gRPC request timeout in seconds 1s
MF_AUTH_GRPC_URL Auth service gRPC URL localhost:8181
MF_AUTH_GRPC_TIMEOUT Auth service gRPC request timeout in seconds 1s
MF_OTA_ES_URL Event store URL redis://localhost:6379/0
MF_OTA_FIRMWARE_URL Public base URL things download firmware group files from https://localhost/fs/groupfiles
MF_OTA_TIMEOUT_CHECK_INTERVAL How often things without progress are checked for timeout 10m

Deployment

The service itself is distributed as Docker container. Check the ota service section in docker-compose to see how service is deployed.

To start the service, execute the following shell script:

# Download the latest version of the service
git clone https://github.com/MainfluxLabs/mainflux

cd mainflux

# compile the ota service
make ota

# Copy binary to bin
make install

# Set the environment variables and run the service
MF_OTA_LOG_LEVEL=[OTA log level] \
MF_BROKER_URL=[Message broker instance URL] \
MF_OTA_HTTP_PORT=[OTA service HTTP port] \
MF_OTA_DB_HOST=[Database host address] \
MF_OTA_DB_PORT=[Database host port] \
MF_OTA_DB_USER=[Database user] \
MF_OTA_DB_PASS=[Database password] \
MF_OTA_DB=[OTA database name] \
MF_THINGS_AUTH_GRPC_URL=[Things service Auth gRPC URL] \
MF_THINGS_AUTH_GRPC_TIMEOUT=[Things service Auth gRPC request timeout] \
MF_AUTH_GRPC_URL=[Auth service gRPC URL] \
MF_AUTH_GRPC_TIMEOUT=[Auth service gRPC request timeout] \
MF_OTA_FIRMWARE_URL=[Public base URL of firmware group files] \
$GOBIN/mainfluxlabs-ota

Usage

For the full HTTP API reference, see the OpenAPI specification.

Documentation

Index

Constants

View Source
const (
	// StatusPending means the thing has not started the update yet.
	StatusPending = "pending"
	// StatusDownloading means the thing is downloading the firmware.
	StatusDownloading = "downloading"
	// StatusInstalling means the thing is installing the firmware.
	StatusInstalling = "installing"
	// StatusSucceeded means the thing reported the target version.
	StatusSucceeded = "succeeded"
	// StatusFailed means the update failed, timed out or was superseded.
	StatusFailed = "failed"
)
View Source
const (
	// ErrMsgTimedOut is stored for a thing update without progress for its update's timeout.
	ErrMsgTimedOut = "timed out"
	// ErrMsgVersionMismatch is stored when a thing reports success with a different version.
	ErrMsgVersionMismatch = "version mismatch: reported %s"
	// ErrMsgSuperseded is stored for an active thing update replaced by a newer update.
	ErrMsgSuperseded = "superseded by update %s"
)
View Source
const (
	// UpdateStatusInProgress means at least one thing is still active.
	UpdateStatusInProgress = "in_progress"
	// UpdateStatusCompleted means no thing is active or failed.
	UpdateStatusCompleted = "completed"
	// UpdateStatusCompletedWithFailures means no thing is active and at least one failed.
	UpdateStatusCompletedWithFailures = "completed_with_failures"
)

Variables

View Source
var (
	// ErrInvalidStatus indicates an unknown status.
	ErrInvalidStatus = errors.New("invalid OTA status")

	// ErrUpdateFinished indicates a status report for a thing update that already finished.
	ErrUpdateFinished = errors.New("OTA update already finished")

	// ErrMissingReportedVersion indicates a succeeded status report without the installed version.
	ErrMissingReportedVersion = errors.New("missing reported version")
)

ActiveStatuses are the statuses of a thing update that is still running.

View Source
var ThingUpdateOrderFields = map[string]string{
	"thing_id":   "thing_id",
	"updated_at": "updated_at",
	"status":     "status",
}

ThingUpdateOrderFields maps API order keys to SQL column expressions of the thing_updates table.

View Source
var UpdateOrderFields = map[string]string{
	"id":          "id",
	"created_at":  "created_at",
	"version":     "version",
	"status":      "status",
	"targets":     "targets",
	"pending":     "pending_count",
	"downloading": "downloading_count",
	"installing":  "installing_count",
	"succeeded":   "succeeded_count",
	"failed":      "failed_count",
}

UpdateOrderFields maps API-facing order keys to SQL column expressions for the updates table.

Functions

This section is empty.

Types

type Command

type Command struct {
	UpdateID string `json:"update_id"`
	Version  string `json:"version"`
	FileName string `json:"file_name"`
	URL      string `json:"url"`
	Size     int64  `json:"size"`
	Checksum string `json:"checksum"`
}

Command tells a thing which firmware to install and where to download it from.

type PageMetadata

type PageMetadata struct {
	Total  uint64 `json:"total,omitempty"`
	Offset uint64 `json:"offset,omitempty"`
	Limit  uint64 `json:"limit,omitempty"`
	Order  string `json:"order,omitempty"`
	Dir    string `json:"dir,omitempty"`
	Status string `json:"status,omitempty"`
}

PageMetadata contains page metadata that helps navigation.

type Service

type Service interface {
	// CreateUpdate creates an update of the given things in the group and notifies them.
	CreateUpdate(ctx context.Context, token, groupID string, u Update, thingIDs ...string) (Update, error)

	// ListUpdatesByGroup retrieves a page of updates of the given group.
	ListUpdatesByGroup(ctx context.Context, token, groupID string, pm PageMetadata) (UpdatesPage, error)

	// ViewUpdate retrieves the update identified by the given ID.
	ViewUpdate(ctx context.Context, token, id string) (Update, error)

	// ListThingUpdates retrieves a page of thing updates of the given update.
	ListThingUpdates(ctx context.Context, token, updateID string, pm PageMetadata) (ThingUpdatesPage, error)

	// RetryFailed moves the update's failed things back to pending and notifies them again.
	RetryFailed(ctx context.Context, token, updateID string) error

	// RemoveUpdate removes the update identified by the given ID.
	RemoveUpdate(ctx context.Context, token, id string) error

	// ViewPending retrieves the command of the update that the thing with the key should apply.
	ViewPending(ctx context.Context, key domain.ThingKey) (Command, error)

	// ReportStatus records the progress of an update reported by the thing identified by the key.
	ReportStatus(ctx context.Context, key domain.ThingKey, report StatusReport) error

	// FailTimedOut marks thing updates without progress for their update's timeout as failed.
	FailTimedOut(ctx context.Context) error

	// RemoveThingUpdatesByThing removes thing updates of the given thing.
	RemoveThingUpdatesByThing(ctx context.Context, thingID string) error

	// RemoveUpdatesByGroup removes updates of the given group.
	RemoveUpdatesByGroup(ctx context.Context, groupID string) error

	consumers.MessageConsumer
}

Service specifies an API that must be fullfiled by the domain service implementation, and all of its decorators (e.g. logging & metrics). All methods that accept a token parameter use it to identify and authorize the user performing the operation.

func New

func New(things domain.ThingsClient, updates UpdateRepository, publisher messaging.CommandPublisher, idp uuid.IDProvider, firmwareURL string, logger logger.Logger) Service

New instantiates the OTA service implementation. firmwareURL is the public base URL things download firmware files from.

type StatusReport

type StatusReport struct {
	UpdateID string `json:"update_id"`
	Status   string `json:"status"`
	Version  string `json:"version,omitempty"`
	Error    string `json:"error,omitempty"`
}

StatusReport is a thing's report on the progress of an update.

type ThingUpdate

type ThingUpdate struct {
	UpdateID        string
	ThingID         string
	Status          string
	Error           string
	ReportedVersion string
	UpdatedAt       time.Time
}

ThingUpdate is the progress of one thing within an update.

type ThingUpdatesPage

type ThingUpdatesPage struct {
	Total        uint64
	ThingUpdates []ThingUpdate
}

ThingUpdatesPage contains a page of thing updates.

type Update

type Update struct {
	ID          string
	GroupID     string
	FileName    string
	Version     string
	FileSize    int64
	Checksum    string
	Description string
	Timeout     time.Duration
	CreatedAt   time.Time
	Status      string
	Stats       UpdateStats
}

Update is a firmware rollout to a set of things in one group.

type UpdateRepository

type UpdateRepository interface {
	// Save persists the update with a pending thing update for each given thing. Older active
	// thing updates of the same things are marked failed as superseded in the same transaction.
	Save(ctx context.Context, u Update, thingIDs ...string) error

	// RetrieveByID retrieves the update with the given ID, including its status and stats.
	RetrieveByID(ctx context.Context, id string) (Update, error)

	// RetrieveByGroup retrieves a page of updates of the given group, including their status and
	// stats, optionally filtered by status.
	RetrieveByGroup(ctx context.Context, groupID string, pm PageMetadata) (UpdatesPage, error)

	// Remove removes the update with the given ID and its thing updates.
	Remove(ctx context.Context, id string) error

	// RemoveByGroup removes all updates of the given group.
	RemoveByGroup(ctx context.Context, groupID string) error

	// RetrieveThingUpdates retrieves a page of thing updates of the given update.
	RetrieveThingUpdates(ctx context.Context, updateID string, pm PageMetadata) (ThingUpdatesPage, error)

	// RetrieveThingUpdate retrieves the thing update of the given update and thing.
	RetrieveThingUpdate(ctx context.Context, updateID, thingID string) (ThingUpdate, error)

	// RetrieveActiveThingUpdate retrieves the newest active thing update of the given thing.
	RetrieveActiveThingUpdate(ctx context.Context, thingID string) (ThingUpdate, error)

	// UpdateThingUpdate updates the progress of an active thing update.
	UpdateThingUpdate(ctx context.Context, tu ThingUpdate) error

	// RetrieveFailedThingIDs retrieves the IDs of the failed things of the given update.
	RetrieveFailedThingIDs(ctx context.Context, updateID string) ([]string, error)

	// RetryFailed moves the failed thing updates of the given update and things back to pending
	// and returns the IDs of the affected things.
	RetryFailed(ctx context.Context, updateID string, thingIDs []string) ([]string, error)

	// FailTimedOut fails active thing updates without progress for their update's timeout.
	FailTimedOut(ctx context.Context, now time.Time) error

	// RemoveThingUpdatesByThing removes all thing updates of the given thing.
	RemoveThingUpdatesByThing(ctx context.Context, thingID string) error
}

UpdateRepository specifies the persistence API for updates and their thing updates.

type UpdateStats

type UpdateStats struct {
	Targets     uint64
	Pending     uint64
	Downloading uint64
	Installing  uint64
	Succeeded   uint64
	Failed      uint64
}

UpdateStats counts the things of an update by status.

func (*UpdateStats) Add

func (s *UpdateStats) Add(status string)

Add counts a thing with the given status.

func (*UpdateStats) Remove

func (s *UpdateStats) Remove(status string)

Remove stops counting a thing with the given status.

func (UpdateStats) Status

func (s UpdateStats) Status() string

Status returns the update status the stats add up to.

type UpdatesPage

type UpdatesPage struct {
	Total   uint64
	Updates []Update
}

UpdatesPage contains a page of updates.

Directories

Path Synopsis
api
Package api contains API-related concerns: endpoint definitions, middlewares and all resource representations.
Package api contains API-related concerns: endpoint definitions, middlewares and all resource representations.
http
Package http contains implementation of kit service HTTP API.
Package http contains implementation of kit service HTTP API.

Jump to

Keyboard shortcuts

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