ubusio

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT 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

ubusio

A pure-Go client and server library for ubus, the OpenWrt micro bus.

ubusio speaks the ubus wire protocol directly over the ubusd unix socket. It uses only the Go standard library: no cgo, no libubus, no spawning of the ubus command line tool. Binaries are static and cross-compile to any router architecture Go supports (arm, arm64, mips, mipsle, 386, amd64, ...).

Status

Pre-release. The API may still change until v0.1.0. All features below are implemented, covered by unit tests against an in-process stand-in for ubusd, and verified against the real ubusd, ubus CLI and libubus of OpenWrt 21.02 and 25.12 on arm64, arm/v7 and amd64 (see compat/).

Area State
blobmsg encoding/decoding implemented, unit + fuzz tested
Connection, lookup, object listing (incl. prefix* wildcards), calls implemented
Exporting objects and method handlers implemented
Events: listen (patterns), send implemented
Subscriptions and notifications (both sides) implemented
Reconnect with restoration of objects, listeners and subscriptions implemented
Compatibility test bench against real ubusd/libubus compat/, passing for 21.02 and 25.12

Usage

go get github.com/ddffcczz/ubusio
conn, err := ubusio.Dial(ctx)                    // /var/run/ubus/ubus.sock
info, err := conn.Call(ctx, "system", "board", nil)
model, _ := info.String("model")

var sysinfo struct {
	Uptime int64 `blobmsg:"uptime"`
	Memory struct {
		Free int64 `blobmsg:"free"`
	} `blobmsg:"memory"`
}
err = conn.CallInto(ctx, "system", "info", nil, &sysinfo)

objs, err := conn.Objects(ctx, "network.interface.*")

obj, err := conn.AddObject(ctx, "demo", []ubusio.Method{{
	Name: "hello",
	Args: []ubusio.ArgSignature{{Name: "name", Type: blobmsg.TypeString}},
	Handler: func(ctx context.Context, req *ubusio.Request) error {
		name, _ := req.Args.String("name")
		return req.Reply(map[string]any{"message": "hello " + name})
	},
}})

l, err := conn.Listen(ctx, func(ev ubusio.Event) { /* ... */ }, "network.*")
err = conn.Send(ctx, "demo.started", map[string]any{"pid": 1})

sub, err := conn.NewSubscriber(ctx, func(ctx context.Context, n *ubusio.Request) error {
	return nil
})
err = sub.Watch(ctx, "hostapd.wlan0")
err = obj.Notify(ctx, "changed", map[string]any{"value": 42})

More in example_test.go and the package documentation.

Behaviour worth knowing
  • Values. Decoding is lossless: a blobmsg.Table keeps field order, the exact wire type of each value (int8/int16/int32/int64, float64, string, nested Table/Array) and duplicate names. Higher-level views are strict: Table.Map() and blobmsg.Decode (into structs with blobmsg:"name" tags) reject duplicate names unless last-wins is requested, never use Go int, and fail on integer overflow. On encoding, Go int is sent as INT32 when it fits, else INT64; bool as INT8.
  • Calls. Call returns the single data reply and fails with ErrMultipleReplies if a method sends more than one; CallMany returns all, CallEach streams them, CallInto decodes into a struct. A path ending in * must match exactly one object (ErrMultipleObjects otherwise); Objects lists matches. Requests without a context deadline get a default timeout (30 s), and every socket write is bounded by a write timeout (10 s) so a stuck ubusd cannot block goroutines.
  • Errors are *ubusio.Error wrapping a Status or one of the Err* values; use errors.Is(err, ubusio.StatusNotFound). They never contain call data.
  • Size limit. Messages over 1 MiB are refused before sending (ErrMessageTooLarge): ubusd would drop the whole connection.
  • Memory. Everything a connection has received but not yet consumed (replies, queued events, notifications and method calls) shares one budget, 4 MiB by default (WithMemoryBudget). Beyond it requests fail with ErrMemoryBudget, events and notifications are dropped and method calls get the overload status, all counted in Conn.Stats. CallMany and NotifyWait accumulate at most 1024 replies / 4 MiB (WithReplyLimits, ErrTooManyReplies); CallEach streams without accumulating. A cancelled context ends a request at once, even with replies buffered.
  • Handlers run on a bounded worker pool (default 4 workers, queue 64). When it is full, calls are answered with StatusNoMemory (configurable). Event listeners and subscribers receive their messages one at a time, in order; when they fall behind, excess messages are dropped and counted (Listener.Dropped, Subscriber.Dropped, Conn.Stats).
  • Events and notifications are best-effort. ubusd silently drops messages for a client whose output queue exceeds 1 MiB, and the protocol has no sequence numbers, so such loss cannot be detected. Consumers that track state should resynchronise by querying periodically. Events are not delivered back to the connection that sent them.
  • Registrations (AddObject, Listen, NewSubscriber/Subscribe) return handles with an idempotent Close and CloseOnDone(ctx). The ctx passed to these calls bounds only the registration request (the convention of net.Dialer.DialContext), not the lifetime of the registration; use CloseOnDone to tie a registration to a context. With WithReconnect or WithLazyConnect, active registrations are restored from their descriptors on the new connection; closed ones are not. Registrations that fail to restore are retried with backoff (WithRestoreRetry, default 8 tries; permission errors are final) and listed by Conn.RestoreStatus; operations on them return ErrNotRegistered meanwhile. Requests in flight when the connection breaks fail with ErrConnectionLost and are never retried.
  • Object ids change on reconnect. ubusd assigns new ids and drops remote subscriptions to the old objects; remote subscribers must subscribe again (libubus auto-subscribe and this library's path subscriptions do so when ubus.object.add announces the object). Path subscriptions made here re-resolve the path and resubscribe when the remote service restarts.
  • Not supported: file descriptor passing, the monitor interface, libubus channels.

Goals

  • Complete coverage of the ubus client protocol: lookup, call, objects, events, subscribe/notify.
  • Safe by default: strict decoding with size and depth limits, bounded queues and in-flight limits, context-aware calls, errors that never echo request payloads.
  • Predictable concurrency: one reader goroutine per connection, handlers run on a bounded worker pool, ordered delivery per listener.
  • Optional automatic reconnect that re-registers objects, event listeners and subscriptions.

Compatibility

Verified with the compatibility bench (Go test binaries for arm64, arm/v7 and amd64 against ubusd, the ubus CLI and libubus built from the upstream commits each release packages):

OpenWrt release Default socket path State
25.12 /var/run/ubus/ubus.sock verified
21.02 /var/run/ubus/ubus.sock verified
19.07 and older /var/run/ubus.sock (fallback) not targeted

Details per feature: docs/compatibility.md.

Go: the module declares go 1.23. Binaries are meant to be cross-compiled on a build host with CGO_ENABLED=0; the Go version shipped in a router SDK does not matter.

Development

make ci      # gofmt check, go vet, race tests, cross-compilation
make fuzz    # run every fuzz target for FUZZTIME (default 30s)

License

MIT, see LICENSE.

This is an independent implementation of the ubus wire protocol written from its public description; it contains no code from the ubus or libubox projects.

Documentation

Overview

Package ubusio is a pure-Go client and server library for ubus, the OpenWrt micro bus.

It talks the ubus wire protocol directly over the unix socket of ubusd and has no cgo or external process dependencies. The blobmsg subpackage implements the blob/blobmsg message encoding used on the wire.

The package is under active development; the API is not yet stable.

Example (Call)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/ddffcczz/ubusio"
	"github.com/ddffcczz/ubusio/blobmsg"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	info, err := conn.Call(ctx, "system", "board", nil)
	if err != nil {
		log.Fatal(err)
	}
	model, _ := info.String("model")
	fmt.Println("model:", model)

	// Decoding into a struct: strict (duplicate keys are errors) and with
	// explicit integer widths.
	var board struct {
		Model   string `blobmsg:"model"`
		Release struct {
			Version string `blobmsg:"version"`
		} `blobmsg:"release"`
	}
	if err := blobmsg.Decode(info, &board, blobmsg.MapOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(board.Release.Version)
}
Example (Events)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	l, err := conn.Listen(ctx, func(ev ubusio.Event) {
		m, err := ev.Data.Map()
		fmt.Println(ev.Type, m, err)
	}, "network.interface", "demo.*")
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	if err := conn.Send(ctx, "demo.started", map[string]any{"pid": 1}); err != nil {
		log.Fatal(err)
	}
}
Example (Notify)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	obj, err := conn.AddObject(ctx, "demo.notifier", nil, ubusio.OnSubscribers(func(active bool) {
		fmt.Println("subscribers present:", active)
	}))
	if err != nil {
		log.Fatal(err)
	}
	if obj.HasSubscribers() {
		obj.Notify(ctx, "changed", map[string]any{"value": 42})
	}
}
Example (Objects)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	objs, err := conn.Objects(ctx, "network.interface.*")
	if err != nil {
		log.Fatal(err)
	}
	for _, o := range objs {
		fmt.Printf("%s @%08x\n", o.Path, o.ID)
		for _, m := range o.Signature {
			fmt.Println("  ", m.Name, m.Args)
		}
	}
}
Example (Server)
package main

import (
	"context"
	"log"
	"time"

	"github.com/ddffcczz/ubusio"
	"github.com/ddffcczz/ubusio/blobmsg"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx, ubusio.WithReconnect(nil))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	_, err = conn.AddObject(ctx, "demo", []ubusio.Method{
		{
			Name: "hello",
			Args: []ubusio.ArgSignature{{Name: "name", Type: blobmsg.TypeString}},
			Handler: func(ctx context.Context, req *ubusio.Request) error {
				name, ok := req.Args.String("name")
				if !ok {
					return ubusio.StatusInvalidArgument
				}
				return req.Reply(map[string]any{"message": "hello " + name})
			},
		},
		{
			// A deferred reply, completed from another goroutine.
			Name: "slow",
			Handler: func(ctx context.Context, req *ubusio.Request) error {
				req.Defer()
				go func() {
					time.Sleep(time.Second)
					req.Reply(map[string]any{"done": true})
					req.Complete(nil)
				}()
				return nil
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	select {} // serve until killed; try: ubus call demo hello '{"name":"x"}'
}
Example (Subscribe)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ddffcczz/ubusio"
)

func main() {
	ctx := context.Background()
	conn, err := ubusio.Dial(ctx, ubusio.WithReconnect(nil))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	sub, err := conn.NewSubscriber(ctx, func(ctx context.Context, n *ubusio.Request) error {
		fmt.Println("notification", n.Method, n.Args.MapLastWins())
		return nil
	}, ubusio.OnTargetRemoved(func(id uint32, path string) {
		fmt.Println("gone:", path)
	}))
	if err != nil {
		log.Fatal(err)
	}
	// Watch does not require the object to exist yet and follows it
	// across restarts of its owner and reconnects.
	if err := sub.Watch(ctx, "hostapd.wlan0"); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

View Source
const (
	DefaultSocketPath = "/var/run/ubus/ubus.sock"
	LegacySocketPath  = "/var/run/ubus.sock"
)

Default socket paths. DefaultSocketPath is used by OpenWrt 21.02 and later; LegacySocketPath by older releases and is tried when the default does not exist and no explicit path was configured.

View Source
const (
	DefaultMaxInflight    = 64
	DefaultRequestTimeout = 30 * time.Second
	DefaultWriteTimeout   = 10 * time.Second
	// DefaultMemoryBudget bounds the received data a connection buffers
	// at any time: unconsumed replies, queued events, notifications and
	// method calls. Sized for routers.
	DefaultMemoryBudget = 4 << 20
	// DefaultMaxReplies and DefaultMaxReplyBytes bound the replies that
	// CallMany and NotifyWait accumulate.
	DefaultMaxReplies     = 1024
	DefaultMaxReplyBytes  = 4 << 20
	DefaultHandlerWorkers = 4
	DefaultHandlerQueue   = 64
)

Defaults for the corresponding options.

View Source
const DefaultMaxMessageSize = 1 << 20

DefaultMaxMessageSize is the largest message ubusd accepts by default (UBUS_MAX_MSGLEN). ubusd closes the connection of a client that sends a bigger one.

View Source
const (
	DefaultRestoreAttempts = 8
)

Defaults for WithRestoreRetry.

Variables

View Source
var (
	// ErrClosed is returned after Close.
	ErrClosed = errors.New("ubusio: connection closed")
	// ErrConnectionLost is returned for requests that were in flight
	// (or could not be sent) when the connection to ubusd broke. Such
	// requests are never retried automatically: they may or may not
	// have been executed.
	ErrConnectionLost = errors.New("ubusio: connection lost")
	// ErrMessageTooLarge is returned when an outgoing message exceeds
	// the configured maximum message size. Nothing was sent.
	ErrMessageTooLarge = errors.New("ubusio: message too large")
	// ErrWriteTimeout is returned when ubusd did not accept a message
	// within the write timeout (see WithWriteTimeout). Nothing was sent.
	ErrWriteTimeout = errors.New("ubusio: write timeout")
	// ErrInvalidName is returned for empty names or names containing
	// NUL bytes (object paths, methods, event types and patterns).
	ErrInvalidName = errors.New("ubusio: invalid name")
	// ErrProtocol reports a malformed message received from ubusd. The
	// connection is closed when the framing itself is broken.
	ErrProtocol = errProtocol
)

Errors returned by the library. Library errors never include message payloads.

View Source
var ErrAlreadyCompleted = errors.New("ubusio: request already completed")

ErrAlreadyCompleted is returned by Reply and Complete after the request's final status was sent.

View Source
var ErrMemoryBudget = errors.New("ubusio: connection memory budget exhausted")

ErrMemoryBudget is returned when the connection's memory budget for buffered data is exhausted (see WithMemoryBudget).

View Source
var ErrMultipleObjects = errors.New("ubusio: path matches more than one object")

ErrMultipleObjects is returned by Lookup (and Call) when a wildcard path matches more than one object; use Objects to list them.

View Source
var ErrMultipleReplies = errors.New("ubusio: method sent more than one reply")

ErrMultipleReplies is returned by Call and CallID when the method sent more than one data reply; use CallMany or CallEach for such methods. The call itself was executed.

View Source
var ErrNotRegistered = errors.New("ubusio: not registered on the current connection")

ErrNotRegistered is returned for operations on an object, listener or subscriber that is not (yet) registered on the current connection, for example because restoring it after a reconnect failed and is being retried (see Conn.RestoreStatus).

View Source
var ErrTooManyReplies = errors.New("ubusio: too many replies")

ErrTooManyReplies is returned by CallMany, CallIDMany and NotifyWait when the replies exceed WithReplyLimits.

Functions

This section is empty.

Types

type ArgSignature

type ArgSignature struct {
	Name string
	Type blobmsg.Type
}

ArgSignature is a declared method argument.

type Backoff

type Backoff func(attempt int) time.Duration

Backoff returns the delay before reconnect attempt n (starting at 1).

func ExponentialBackoff

func ExponentialBackoff(min, max time.Duration) Backoff

ExponentialBackoff returns a Backoff doubling from min up to max, with up to 20% random jitter.

type Conn

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

Conn is a connection to ubusd. It is safe for concurrent use.

A single goroutine reads from the socket and routes replies to the requests waiting for them; method, event and notification handlers run on a separate bounded worker pool and never block the reader.

func Dial

func Dial(ctx context.Context, opts ...Option) (*Conn, error)

Dial connects to ubusd and waits for its greeting. The context bounds the connection attempt only.

func (*Conn) AddObject

func (c *Conn) AddObject(ctx context.Context, path string, methods []Method, opts ...ObjectOption) (*Object, error)

AddObject publishes an object at path with the given methods.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Call

func (c *Conn) Call(ctx context.Context, path, method string, args any) (blobmsg.Table, error)

Call invokes method on the object at path and returns its data reply, or nil if the method replied with a status only. A method that sends several data replies makes Call fail with ErrMultipleReplies as soon as the second one arrives (never silently picking one, and without buffering the rest). args is encoded with blobmsg.Marshal: nil, a blobmsg.Table, a map with string keys or a struct.

path may end in '*' if it matches exactly one object (see Lookup). Object ids are cached per exact path (see WithLookupCache). When ubusd reports a cached id as unknown, the path is looked up again and the call is sent once more; this is safe because the first attempt never reached a handler.

func (*Conn) CallEach

func (c *Conn) CallEach(ctx context.Context, path, method string, args any, fn func(blobmsg.Table) error) error

CallEach invokes method on the object at path and calls fn for every data reply as it arrives, in order. Methods may send any number of data replies before their final status. If fn returns an error, the remaining replies are discarded and that error is returned.

func (*Conn) CallID

func (c *Conn) CallID(ctx context.Context, id uint32, method string, args any) (blobmsg.Table, error)

CallID invokes method on the object with the given id and returns its single data reply, like Call.

func (*Conn) CallIDEach

func (c *Conn) CallIDEach(ctx context.Context, id uint32, method string, args any, fn func(blobmsg.Table) error) error

CallIDEach invokes method on the object with the given id and calls fn for every data reply, like CallEach.

func (*Conn) CallIDMany

func (c *Conn) CallIDMany(ctx context.Context, id uint32, method string, args any) ([]blobmsg.Table, error)

CallIDMany invokes method on the object with the given id and returns all its data replies, like CallMany.

func (*Conn) CallInto

func (c *Conn) CallInto(ctx context.Context, path, method string, args, out any) error

CallInto invokes method like Call and decodes the single data reply into out with blobmsg.Decode and strict options. A status-only reply leaves out unchanged.

func (*Conn) CallMany

func (c *Conn) CallMany(ctx context.Context, path, method string, args any) ([]blobmsg.Table, error)

CallMany invokes method on the object at path and returns all its data replies in order. The number and total size of replies are limited (see WithReplyLimits); beyond that the call fails with ErrTooManyReplies. On error, the replies received so far are returned with it.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection. Pending requests fail with ErrClosed, the context passed to handlers is cancelled and queued handler work is discarded. Close does not wait for handlers that are still running (so it may be called from a handler); their replies fail.

func (*Conn) ID

func (c *Conn) ID() uint32

ID returns the client id assigned by ubusd to the current connection, or 0 when not connected.

func (*Conn) Listen

func (c *Conn) Listen(ctx context.Context, handler func(Event), patterns ...string) (*Listener, error)

Listen registers handler for events whose type matches one of the patterns. A pattern is an exact event type or a prefix followed by '*'; "*" matches every event. ubusd does not deliver events to the connection that sent them.

When the handler falls behind by more than the handler queue size (see WithHandlerWorkers), further events are dropped and counted (see Dropped).

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Lookup

func (c *Conn) Lookup(ctx context.Context, path string) (uint32, error)

Lookup returns the id of the object published at path. A path ending in '*' is a prefix pattern that must match exactly one object: several matches give ErrMultipleObjects, none StatusNotFound.

func (*Conn) NewSubscriber

func (c *Conn) NewSubscriber(ctx context.Context, h Handler, opts ...SubscriberOption) (*Subscriber, error)

NewSubscriber creates a subscriber whose notifications are handled by h.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

func (*Conn) Objects

func (c *Conn) Objects(ctx context.Context, pattern string) ([]ObjectInfo, error)

Objects lists published objects. An empty pattern lists all objects, a pattern ending in '*' lists the objects whose path starts with the part before it, and any other pattern matches one exact path. No match yields an empty list and no error.

On ubus releases without lookup queuing (e.g. OpenWrt 21.02) ubusd may silently drop parts of very large listings; prefer prefix patterns and always use a context deadline there.

func (*Conn) RestoreStatus added in v0.1.1

func (c *Conn) RestoreStatus() []RestoreFailure

RestoreStatus returns the registrations that are currently not restored on the connection. It is empty when everything is active.

func (*Conn) Send

func (c *Conn) Send(ctx context.Context, typ string, data any) error

Send emits an event. data is encoded like call arguments; nil sends an empty table. Event types starting with "ubus." are reserved by ubusd.

func (*Conn) Stats

func (c *Conn) Stats() Stats

Stats returns the connection's drop counters.

func (*Conn) Subscribe

func (c *Conn) Subscribe(ctx context.Context, path string, h Handler, opts ...SubscriberOption) (*Subscriber, error)

Subscribe is a shortcut that creates a Subscriber with handler h and subscribes it to the object at path (which must exist). Close the returned subscriber to end the subscription.

ctx bounds only the registration request, like the context of net.Dialer.DialContext: it does not govern the registration once it is established. The registration lasts until Close (or the connection is closed); use CloseOnDone to tie it to a context.

type Error

type Error struct {
	Op     string
	Path   string
	Method string
	Err    error
}

Error describes a failed operation. It wraps the underlying cause, typically a Status or one of the Err* values. It names the operation, object and method but never contains message data.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Event

type Event struct {
	Type string
	Data blobmsg.Table
}

Event is a ubus event.

type Handler

type Handler func(ctx context.Context, req *Request) error

Handler handles an incoming method call or subscription notification. It may send any number of data replies with req.Reply. Its return value becomes the reply status: nil is success, a Status is sent as is and any other error is reported as StatusUnknownError. To answer later, call req.Defer and finish with req.Complete.

Handlers run on the connection's worker pool; ctx is cancelled when the connection is closed.

type Listener

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

Listener receives events matching its patterns. Events are delivered to its handler one at a time, in arrival order.

func (*Listener) Close

func (l *Listener) Close() error

Close stops event delivery. It is idempotent; a closed listener is not restored after a reconnect. Events queued but not yet passed to the handler are discarded; a handler call in progress is not interrupted.

func (*Listener) CloseOnDone

func (l *Listener) CloseOnDone(ctx context.Context)

CloseOnDone closes the listener when ctx is done.

func (*Listener) Dropped

func (l *Listener) Dropped() uint64

Dropped returns the number of events dropped because the handler could not keep up.

type Method

type Method struct {
	Name    string
	Args    []ArgSignature
	Handler Handler
}

Method describes an exported method. Args is published as the method signature (as shown by "ubus -v list"); ubus does not enforce it.

type MethodSignature

type MethodSignature struct {
	Name string
	Args []ArgSignature
}

MethodSignature describes a method and its declared arguments.

type NotifyResult

type NotifyResult struct {
	Subscriber uint32
	Status     Status
	Data       []blobmsg.Table
	// Done is false if the subscriber did not answer before the
	// context ended.
	Done bool
}

NotifyResult is the answer of one subscriber to NotifyWait.

type Object

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

Object is an object published on the bus.

func (*Object) Close

func (o *Object) Close() error

Close withdraws the object from the bus, like Remove with the default request timeout. It is idempotent.

func (*Object) CloseOnDone

func (o *Object) CloseOnDone(ctx context.Context)

CloseOnDone closes the object when ctx is done.

func (*Object) HasSubscribers

func (o *Object) HasSubscribers() bool

HasSubscribers reports whether the object currently has subscribers.

func (*Object) ID

func (o *Object) ID() uint32

ID returns the object id assigned by ubusd. It changes after a reconnect.

func (*Object) Notify

func (o *Object) Notify(ctx context.Context, method string, data any) error

Notify sends a notification to all subscribers without waiting for replies.

func (*Object) NotifyWait

func (o *Object) NotifyWait(ctx context.Context, method string, data any) ([]NotifyResult, error)

NotifyWait sends a notification and waits until every subscriber has answered or ctx ends. The number of subscribers and the data replies collected are bounded by WithReplyLimits (ErrTooManyReplies). It returns one result per subscriber present when the notification was sent; on timeout the results collected so far are returned together with the context error.

func (*Object) Path

func (o *Object) Path() string

Path returns the object path.

func (*Object) Remove

func (o *Object) Remove(ctx context.Context) error

Remove withdraws the object from the bus. It is idempotent; a removed object is not restored after a reconnect.

Note for remote subscribers: after a reconnect the object is published again under a new id and ubusd has dropped existing subscriptions to it. Subscribers must subscribe again (this library does so automatically for path subscriptions, as does libubus auto-subscribe).

type ObjectInfo

type ObjectInfo struct {
	Path   string
	ID     uint32
	TypeID uint32
	// Signature lists the methods visible to this client (ubusd hides
	// methods denied by ACLs) in the order reported by ubusd.
	Signature []MethodSignature
}

ObjectInfo describes a published object as reported by ubusd.

type ObjectOption

type ObjectOption func(*Object)

ObjectOption configures an Object.

func OnSubscribers

func OnSubscribers(fn func(active bool)) ObjectOption

OnSubscribers sets a callback invoked whenever the object gains its first subscriber (true) or loses its last one (false). Calls are delivered in order.

type Option

type Option func(*options)

Option configures a Conn.

func OnDisconnect

func OnDisconnect(fn func(c *Conn, err error)) Option

OnDisconnect sets a hook called when an established connection is lost.

func OnReconnect

func OnReconnect(fn func(c *Conn, err error)) Option

OnReconnect sets a hook called after the connection was re-established. err joins the errors of registrations that could not be restored (they are retried on the next reconnect).

func WithHandlerWorkers

func WithHandlerWorkers(workers, queue int) Option

WithHandlerWorkers sets the number of goroutines running method, event and notification handlers, and the size of the queue in front of them. When the queue is full, method calls are answered with the overload status (see WithOverloadStatus) and events are dropped.

func WithLazyConnect

func WithLazyConnect() Option

WithLazyConnect makes Dial return without connecting: the connection is established by the first request and, after a loss, re-established by the next request (restoring registrations like WithReconnect).

func WithLookupCache

func WithLookupCache(enabled bool) Option

WithLookupCache enables or disables caching of path to object id lookups made by Call (enabled by default). Cached ids are dropped when ubusd reports the object as gone and after reconnects.

func WithMaxDepth

func WithMaxDepth(n int) Option

WithMaxDepth sets the nesting limit for decoding message data.

func WithMaxInflight

func WithMaxInflight(n int) Option

WithMaxInflight limits the number of concurrent outgoing requests. Further requests wait for a free slot or for their context.

func WithMaxMessageSize

func WithMaxMessageSize(n int) Option

WithMaxMessageSize sets the largest message, in bytes, that is sent or accepted. It must not exceed the ubusd limit (1 MiB by default), since ubusd drops clients that send bigger messages.

func WithMemoryBudget added in v0.1.1

func WithMemoryBudget(bytes int) Option

WithMemoryBudget sets the connection-wide budget, in bytes of message data, for everything received but not yet consumed: replies waiting for their caller, queued events, notifications and method calls. When it is exhausted, requests fail with ErrMemoryBudget, events and notifications are dropped (and counted) and method calls are answered with the overload status. It is raised to at least one maximum-size message.

func WithOverloadStatus

func WithOverloadStatus(s Status) Option

WithOverloadStatus sets the status returned to callers when the handler queue is full. The default is StatusNoMemory; use StatusUnknownError for callers on ubus releases that predate it.

func WithReconnect

func WithReconnect(backoff Backoff) Option

WithReconnect makes the connection re-establish itself in the background after it is lost, waiting backoff(n) before attempt n. After reconnecting, published objects are registered again (with new ids), event listeners and path subscriptions are restored and the lookup cache is cleared. Requests that were in flight when the connection broke fail with ErrConnectionLost and are not retried; requests made while disconnected wait for the new connection, bounded by their context.

func WithReplyLimits added in v0.1.1

func WithReplyLimits(maxReplies, maxBytes int) Option

WithReplyLimits bounds the number and total size (in bytes of message data) of the replies accumulated by CallMany, CallIDMany and NotifyWait; beyond them these fail with ErrTooManyReplies. CallEach is not limited by them since it does not accumulate.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) Option

WithRequestTimeout sets the timeout applied to requests whose context has no deadline. Zero disables the implicit timeout.

func WithRestoreRetry added in v0.1.1

func WithRestoreRetry(attempts int, backoff Backoff) Option

WithRestoreRetry sets how registrations that could not be restored after a reconnect are retried: up to attempts further tries, waiting backoff(n) before try n (default 8 tries, exponential from 200ms to 10s). Only registrations are retried (objects, event listeners, subscribers and path subscriptions), never calls. Permission errors and invalid names are not retried.

func WithSocketPath

func WithSocketPath(path string) Option

WithSocketPath sets the ubusd socket path. Without it the default path is used, falling back to LegacySocketPath when the default is missing.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout bounds every socket write, whatever the context, so that a stuck ubusd cannot block callers or handler workers forever. Zero disables the bound (contexts still apply).

type Request

type Request struct {
	// Method is the method name (for notifications: the notification
	// type chosen by the notifying object).
	Method string
	// Args is the call data.
	Args blobmsg.Table
	// User and Group identify the caller when ubusd provides them.
	User, Group string
	// CallerID is the ubus client id of the caller.
	CallerID uint32
	// NoReply is set for notifications sent without waiting for
	// replies; Reply and Complete are no-ops then.
	NoReply bool
	// contains filtered or unexported fields
}

Request is an incoming method call or notification.

func (*Request) Complete

func (r *Request) Complete(err error) error

Complete sends the final status of the request (see Handler for the mapping of err).

func (*Request) Defer

func (r *Request) Defer()

Defer marks the request as answered later: the handler's return value is ignored and the request stays open until Complete.

func (*Request) Reply

func (r *Request) Reply(data any) error

Reply sends a data reply. It can be called several times before the request completes.

type RestoreFailure added in v0.1.1

type RestoreFailure struct {
	// Kind is "object", "listener", "subscriber" or "subscription".
	Kind string
	// Name is the object path, the listener's patterns or the
	// subscribed path (empty for a subscriber object).
	Name string
	// Err is the last error.
	Err error
	// Attempts counts the tries so far, the first restore included.
	Attempts int
	// GaveUp is set once the failure is no longer retried (permanent
	// error or retries exhausted); the registration stays inactive until
	// the next reconnect or until it is closed and created again.
	GaveUp bool
}

RestoreFailure describes a registration that is not active on the current connection because restoring it after a reconnect failed.

type Stats

type Stats struct {
	// DroppedEvents counts events not delivered because a listener's
	// queue was full.
	DroppedEvents uint64
	// DroppedNotifications counts notifications not delivered because a
	// subscriber's queue was full.
	DroppedNotifications uint64
	// OverloadedCalls counts incoming method calls answered with the
	// overload status because the handler queue was full.
	OverloadedCalls uint64
	// BudgetExceeded counts messages refused because the memory budget
	// was exhausted (see WithMemoryBudget); they are also counted in the
	// fields above where applicable.
	BudgetExceeded uint64
	// BufferedBytes is the message data currently buffered.
	BufferedBytes int64
}

Stats are counters of messages this connection had to drop.

ubusd itself drops messages silently when a client's output queue exceeds its limit (1 MiB by default) and the protocol has no sequence numbers to detect that, so these counters only cover local drops. Treat events and notifications as best-effort and resynchronise state by querying periodically.

type Status

type Status int32

Status is a ubus status code. Non-zero values are errors and can be compared with errors.Is, e.g. errors.Is(err, ubusio.StatusNotFound).

const (
	StatusOK               Status = 0
	StatusInvalidCommand   Status = 1
	StatusInvalidArgument  Status = 2
	StatusMethodNotFound   Status = 3
	StatusNotFound         Status = 4
	StatusNoData           Status = 5
	StatusPermissionDenied Status = 6
	StatusTimeout          Status = 7
	StatusNotSupported     Status = 8
	StatusUnknownError     Status = 9
	StatusConnectionFailed Status = 10
	StatusNoMemory         Status = 11
	StatusParseError       Status = 12
	StatusSystemError      Status = 13
)

Status codes. Codes 11 to 13 are not known to ubus releases before 2022 (e.g. OpenWrt 21.02); such peers report them as unknown errors.

func (Status) Error

func (s Status) Error() string

Error implements error.

func (Status) String

func (s Status) String() string

type Subscriber

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

Subscriber receives notifications from the objects it subscribes to. Notifications are handled one at a time, in arrival order, by the subscriber's Handler; for notifications sent with NotifyWait the handler's result is returned to the notifying object.

Subscriptions made by path are kept until Unsubscribe or Close: when the target object disappears the subscription becomes pending and is re-established as soon as an object with that path is published again, including after a reconnect.

func (*Subscriber) Close

func (s *Subscriber) Close() error

Close removes the subscriber and all its subscriptions. It is idempotent; a closed subscriber is not restored after a reconnect.

func (*Subscriber) CloseOnDone

func (s *Subscriber) CloseOnDone(ctx context.Context)

CloseOnDone closes the subscriber when ctx is done.

func (*Subscriber) Dropped

func (s *Subscriber) Dropped() uint64

Dropped returns the number of notifications dropped because the handler could not keep up.

func (*Subscriber) ID

func (s *Subscriber) ID() uint32

ID returns the subscriber's object id (it changes after a reconnect).

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(ctx context.Context, path string) error

Subscribe subscribes to the object at path, which must exist. ctx bounds only this request; the subscription lasts until Unsubscribe or Close.

func (*Subscriber) SubscribeID

func (s *Subscriber) SubscribeID(ctx context.Context, id uint32) error

SubscribeID subscribes to the object with the given id. Such subscriptions end when the target goes away or the connection is re-established.

func (*Subscriber) Unsubscribe

func (s *Subscriber) Unsubscribe(ctx context.Context, path string) error

Unsubscribe ends a subscription made by path.

func (*Subscriber) UnsubscribeID

func (s *Subscriber) UnsubscribeID(ctx context.Context, id uint32) error

UnsubscribeID ends a subscription made by id.

func (*Subscriber) Watch

func (s *Subscriber) Watch(ctx context.Context, path string) error

Watch subscribes to the object at path as soon as it exists; it does not fail when the object is missing.

type SubscriberOption

type SubscriberOption func(*Subscriber)

SubscriberOption configures a Subscriber.

func OnTargetRemoved

func OnTargetRemoved(fn func(target uint32, path string)) SubscriberOption

OnTargetRemoved sets a callback invoked when a subscribed object goes away (path is empty for subscriptions made by id). It runs in order with the notifications.

Directories

Path Synopsis
Package blobmsg encodes and decodes the blobmsg format, the typed, self-describing message encoding used by ubus.
Package blobmsg encodes and decodes the blobmsg format, the typed, self-describing message encoding used by ubus.
internal
blob
Package blob implements the raw blob attribute framing shared by the ubus message layer and the blobmsg encoding.
Package blob implements the raw blob attribute framing shared by the ubus message layer and the blobmsg encoding.
fakeubusd
Package fakeubusd is an in-process stand-in for ubusd used by unit tests on hosts where the real daemon is not available.
Package fakeubusd is an in-process stand-in for ubusd used by unit tests on hosts where the real daemon is not available.

Jump to

Keyboard shortcuts

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