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)
}
Output:
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)
}
}
Output:
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})
}
}
Output:
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)
}
}
}
Output:
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"}'
}
Output:
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)
}
}
Output:
Index ¶
- Constants
- Variables
- type ArgSignature
- type Backoff
- type Conn
- func (c *Conn) AddObject(ctx context.Context, path string, methods []Method, opts ...ObjectOption) (*Object, error)
- func (c *Conn) Call(ctx context.Context, path, method string, args any) (blobmsg.Table, error)
- func (c *Conn) CallEach(ctx context.Context, path, method string, args any, ...) error
- func (c *Conn) CallFD(ctx context.Context, path, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)
- func (c *Conn) CallID(ctx context.Context, id uint32, method string, args any) (blobmsg.Table, error)
- func (c *Conn) CallIDEach(ctx context.Context, id uint32, method string, args any, ...) error
- func (c *Conn) CallIDFD(ctx context.Context, id uint32, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)
- func (c *Conn) CallIDMany(ctx context.Context, id uint32, method string, args any) ([]blobmsg.Table, error)
- func (c *Conn) CallInto(ctx context.Context, path, method string, args, out any) error
- func (c *Conn) CallMany(ctx context.Context, path, method string, args any) ([]blobmsg.Table, error)
- func (c *Conn) Close() error
- func (c *Conn) ID() uint32
- func (c *Conn) Listen(ctx context.Context, handler func(Event), patterns ...string) (*Listener, error)
- func (c *Conn) Lookup(ctx context.Context, path string) (uint32, error)
- func (c *Conn) Monitor(ctx context.Context, handler func(MonitorEvent), opts ...MonitorOption) (*Monitor, error)
- func (c *Conn) NewSubscriber(ctx context.Context, h Handler, opts ...SubscriberOption) (*Subscriber, error)
- func (c *Conn) Objects(ctx context.Context, pattern string) ([]ObjectInfo, error)
- func (c *Conn) RestoreStatus() []RestoreFailure
- func (c *Conn) Send(ctx context.Context, typ string, data any) error
- func (c *Conn) Shutdown(ctx context.Context) error
- func (c *Conn) Stats() Stats
- func (c *Conn) Subscribe(ctx context.Context, path string, h Handler, opts ...SubscriberOption) (*Subscriber, error)
- type Error
- type Event
- type Handler
- type Listener
- type MessageType
- type Method
- type MethodSignature
- type Monitor
- type MonitorDirection
- type MonitorEvent
- type MonitorOption
- type NotifyResult
- type Object
- func (o *Object) Close() error
- func (o *Object) CloseOnDone(ctx context.Context)
- func (o *Object) HasSubscribers() bool
- func (o *Object) ID() uint32
- func (o *Object) Notify(ctx context.Context, method string, data any) error
- func (o *Object) NotifyWait(ctx context.Context, method string, data any) ([]NotifyResult, error)
- func (o *Object) Path() string
- func (o *Object) Remove(ctx context.Context) error
- type ObjectInfo
- type ObjectOption
- type Option
- func OnDisconnect(fn func(c *Conn, err error)) Option
- func OnReconnect(fn func(c *Conn, err error)) Option
- func WithHandlerWorkers(workers, queue int) Option
- func WithLazyConnect() Option
- func WithLookupCache(enabled bool) Option
- func WithMaxDepth(n int) Option
- func WithMaxInflight(n int) Option
- func WithMaxMessageSize(n int) Option
- func WithMemoryBudget(bytes int) Option
- func WithOverloadStatus(s Status) Option
- func WithReconnect(backoff Backoff) Option
- func WithReplyLimits(maxReplies, maxBytes int) Option
- func WithRequestTimeout(d time.Duration) Option
- func WithRestoreRetry(attempts int, backoff Backoff) Option
- func WithSocketPath(path string) Option
- func WithWriteTimeout(d time.Duration) Option
- type Request
- type RestoreFailure
- type Stats
- type Status
- type Subscriber
- func (s *Subscriber) Close() error
- func (s *Subscriber) CloseOnDone(ctx context.Context)
- func (s *Subscriber) Dropped() uint64
- func (s *Subscriber) ID() uint32
- func (s *Subscriber) Subscribe(ctx context.Context, path string) error
- func (s *Subscriber) SubscribeID(ctx context.Context, id uint32) error
- func (s *Subscriber) Unsubscribe(ctx context.Context, path string) error
- func (s *Subscriber) UnsubscribeID(ctx context.Context, id uint32) error
- func (s *Subscriber) Watch(ctx context.Context, path string) error
- type SubscriberOption
Examples ¶
Constants ¶
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.
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.
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.
const (
DefaultRestoreAttempts = 8
)
Defaults for WithRestoreRetry.
Variables ¶
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.
var ( // ErrInvalidFD is returned for a nil-equivalent or closed *os.File // passed as a descriptor to send. Nothing was sent. ErrInvalidFD = errors.New("ubusio: invalid file descriptor") // ErrFDLost is returned by CallFD and CallIDFD, together with the // reply and without a file, when the final status arrived with ancillary data that could // not be received: the method may have sent a descriptor that is // lost. The call itself succeeded. ErrFDLost = errors.New("ubusio: a file descriptor sent with the reply was lost") // ErrFDUnsupported is returned on platforms without SCM_RIGHTS. ErrFDUnsupported = errors.New("ubusio: file descriptor passing is not supported on this platform") )
Errors of file descriptor passing.
var ( // ErrShuttingDown is returned while Shutdown is in progress, for new // registrations, for calls that are not made with the context of a // running handler of the connection, and for requests that would need // a new connection. ErrShuttingDown = errors.New("ubusio: connection is shutting down") // ErrShutdownInHandler is returned by Shutdown when it is called with // the context of a handler of the same connection: waiting would wait // for the caller itself. Shutdown has been started and completes on // its own; use Close to force it. ErrShutdownInHandler = errors.New("ubusio: Shutdown called from a handler") // ErrShutdownAborted is returned by a Shutdown that was waiting when // the connection was closed by force: by Close, or by another // Shutdown whose context ended. ErrShutdownAborted = errors.New("ubusio: shutdown aborted: connection closed by force") )
Errors of the connection lifecycle.
var ErrAlreadyCompleted = errors.New("ubusio: request already completed")
ErrAlreadyCompleted is returned by Reply and Complete after the request's final status was sent.
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).
var ErrMonitorActive = errors.New("ubusio: a monitor is already active on this connection")
ErrMonitorActive is returned by Monitor when the connection already has an active monitor: ubusd keeps one monitor registration per client.
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.
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.
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).
var ErrTooManyReplies = errors.New("ubusio: too many replies")
ErrTooManyReplies is returned by CallMany, CallIDMany, NotifyWait, Objects and wildcard Lookup when the replies exceed WithReplyLimits.
Functions ¶
This section is empty.
Types ¶
type ArgSignature ¶
ArgSignature is a declared method argument.
type Backoff ¶
Backoff returns the delay before reconnect attempt n (starting at 1).
func ExponentialBackoff ¶
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 ¶
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 ¶
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) CallFD ¶ added in v0.2.0
func (c *Conn) CallFD(ctx context.Context, path, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)
CallFD is Call with file descriptors: it sends fd (if not nil) with the request and returns the descriptor that the method attached to its final status (nil if it sent none). The returned file belongs to the caller, who must close it. The library does not take ownership of fd: the kernel duplicates it, and the caller may close it once CallFD returns. A descriptor is returned only for a successful call.
ubus passes one descriptor per message, and only with the request and the final status; data replies cannot carry one. Descriptors need a platform with SCM_RIGHTS (ErrFDUnsupported otherwise). Descriptors are not counted in the memory budget.
The received file is untrusted input from another process: it may be a FIFO or socket that blocks on read or write, a directory, a device or an O_PATH descriptor. Check it with Stat, use deadlines (SetDeadline works on pipes and sockets) and never use it as the directory of an *at call. If the final status came with ancillary data that could not be received, the reply is returned with ErrFDLost and no file (one that did arrive is closed).
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) CallIDFD ¶ added in v0.2.0
func (c *Conn) CallIDFD(ctx context.Context, id uint32, method string, args any, fd *os.File) (blobmsg.Table, *os.File, error)
CallIDFD is CallFD for an object id, like CallID.
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 ¶
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 ¶
Close closes the connection at once. Pending requests fail with ErrClosed, the context passed to handlers is cancelled, queued handler work is discarded (its memory budget and descriptors released), replies not yet written are dropped, automatic reconnection stops and a connection attempt in progress is aborted. Blocked socket reads and writes are interrupted. It is idempotent and safe for concurrent use. See Shutdown for the graceful variant.
Close never waits for user handlers, so it may be called from inside any handler. It stops waiting for them, it does not stop them: a running handler, and any goroutine it started, goes on after Close returned, cancelling its context only asks it to end, and what it does outside this connection is neither prevented nor undone. Its replies and calls on this connection fail. No further handler is begun, except one whose start was decided just before. To know that handlers have finished, track them in the application.
func (*Conn) ID ¶
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 ¶
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) Monitor ¶ added in v0.2.0
func (c *Conn) Monitor(ctx context.Context, handler func(MonitorEvent), opts ...MonitorOption) (*Monitor, error)
Monitor asks ubusd to report all messages it receives and sends, to handler, one at a time in arrival order. ubusd allows this only to clients running as root (uid and gid 0); others get StatusPermissionDenied. The reports contain all call arguments and replies on the bus: treat them as sensitive.
ubusd keeps one monitor per client, so a connection can have one active Monitor; further calls return ErrMonitorActive until it is closed. The monitor is restored after a reconnect like listeners are.
When the handler falls behind by more than the handler queue size (see WithHandlerWorkers) or the memory budget is exhausted, reports are dropped and counted (see Dropped). Reports that ubusd itself dropped are detected by gaps in the sequence (see Missed). A report of a message the handler generates may follow immediately: use MonitorExcludeSelf to avoid feedback.
Reports waiting for the handler use at most a quarter of the memory budget (see WithMemoryBudget), the rest are dropped, so that a flood of monitored traffic leaves room for calls. Handler panics are recovered and dropped. A monitor shares the worker pool and reader with the connection's other work: use a dedicated Conn for it.
ctx bounds only the registration request; the registration lasts until Close (or the connection is closed).
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 ¶
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.
The number of objects and their total size are limited like call results (WithReplyLimits, default 1024 objects and 4 MiB); beyond that Objects returns the objects received so far together with ErrTooManyReplies. Raise the limits for systems with more objects.
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. A registration that its owner closed is no longer listed.
func (*Conn) Send ¶
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) Shutdown ¶ added in v0.2.0
Shutdown closes the connection gracefully. When it starts:
- new registrations fail with ErrShuttingDown;
- new calls, sends and notifications fail with ErrShuttingDown unless they are made with the context of a running handler of this connection (or one derived from it), until it returns or, for a deferred request, completes. Event listener, subscriber OnTargetRemoved, OnSubscribers and monitor callbacks receive no context, so their calls count as external;
- no new handler invocation is accepted: requests that still arrive are answered with StatusNotFound, events and notifications are dropped;
- reconnection stops: if the connection is or gets lost, operations that need it fail with ErrShuttingDown;
- event listeners and the monitor are removed at ubusd and subscriptions ended (best effort). Published objects stay until the connection closes, because ubusd drops the replies of a removed object.
The connection keeps working otherwise: running and queued handlers finish and send their replies, requests in flight and the calls handlers make receive theirs. Every method call or notification admitted before Shutdown started is run and answered as far as the link allows. When all handlers, deferred requests and requests in flight are done, the replies the library owes at that point are written, ubusd is given up to five seconds to confirm that it has processed them, and the transport is closed. That confirmation is best effort: if it does not come, the connection is closed all the same, and replies ubusd had not read may be lost. Refusals of requests that keep arriving after that point are best effort and do not delay it.
The result belongs to the caller:
- nil: all admitted work finished and the connection was closed by the drain, whether or not ubusd confirmed the last replies; or it was closed before this call, in whatever way;
- an error wrapping ctx.Err(): the context of this call ended first; this call closed the connection by force, as Close does;
- ErrShutdownAborted: while this call was waiting, the connection was closed by force, by Close or by another Shutdown whose context ended.
Called with the context of a handler of this connection, Shutdown starts draining and returns ErrShutdownInHandler without waiting. Other contexts cannot be told apart: a handler that calls Shutdown with an unrelated context waits for itself until that context ends.
When the context of a call ends first, Shutdown guarantees that the connection is closed when it returns. It does not guarantee that user code has stopped executing, nor that its side effects stop: as after Close, running handlers, and goroutines they started, go on, cancelling their context only asks them to end, and what they do outside this connection is neither prevented nor undone.
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 ¶
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.
type Handler ¶
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 ¶
Close stops event delivery. It is idempotent; a closed listener is not restored after a reconnect. It does not wait for the handler and may be called from it: no new handler call starts after Close returns, one in progress may finish, and queued events are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.
func (*Listener) CloseOnDone ¶
CloseOnDone closes the listener when ctx is done.
type MessageType ¶ added in v0.2.0
type MessageType uint8
MessageType is the type of a ubus protocol message.
const ( MessageHello MessageType = msgHello MessageStatus MessageType = msgStatus MessageData MessageType = msgData MessagePing MessageType = msgPing MessageLookup MessageType = msgLookup MessageInvoke MessageType = msgInvoke MessageAddObject MessageType = msgAddObject MessageRemoveObject MessageType = msgRemoveObject MessageSubscribe MessageType = msgSubscribe MessageUnsubscribe MessageType = msgUnsubscribe MessageNotify MessageType = msgNotify )
Message types, as reported by the monitor.
func (MessageType) String ¶ added in v0.2.0
func (t MessageType) String() string
String returns the name used by `ubus monitor`, or the number for unknown types.
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 Monitor ¶ added in v0.2.0
type Monitor struct {
// contains filtered or unexported fields
}
Monitor is a registration for ubusd's traffic monitor, the interface behind `ubus monitor`. See Conn.Monitor.
func (*Monitor) Close ¶ added in v0.2.0
Close stops monitoring. It is idempotent; a closed monitor is not restored after a reconnect. It does not wait for the handler and may be called from it: no new handler call starts after Close returns, one in progress may finish, and queued reports are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.
func (*Monitor) CloseOnDone ¶ added in v0.2.0
CloseOnDone closes the monitor when ctx is done.
type MonitorDirection ¶ added in v0.2.0
type MonitorDirection uint8
MonitorDirection selects the messages a monitor reports.
const ( MonitorBoth MonitorDirection = iota MonitorToClient // only messages sent by ubusd MonitorFromClient // only messages received by ubusd )
Monitor directions.
type MonitorEvent ¶ added in v0.2.0
type MonitorEvent struct {
// Seq is ubusd's per-monitor sequence number of this report. Gaps
// mean that ubusd dropped reports for this client (see Missed).
Seq uint16
// Client is the id of the client whose connection carried the
// message.
Client uint32
// ToClient is true for messages ubusd sent to Client and false for
// messages it received from Client (UBUS_MONITOR_SEND).
ToClient bool
// Type is the message type.
Type MessageType
// MsgSeq and Peer are the sequence number and peer fields of the
// message header.
MsgSeq uint16
Peer uint32
// Decoded message attributes.
Path string
ObjectID uint32
Method string
ObjectType uint32
Target uint32
User string
Group string
Active bool
NoReply bool
// Status is valid when HasStatus is set.
Status Status
HasStatus bool
// Data is the decoded UBUS_ATTR_DATA table (call arguments, reply
// or event data) and Signature the decoded object signature.
Data blobmsg.Table
Signature blobmsg.Table
// Raw is the undecoded attribute block of the message. It belongs to
// the handler.
Raw []byte
// Err is set when the message attributes could not be decoded (the
// content of a message is not validated by ubusd before it is
// reported); only the header fields and Raw are valid then.
Err error
}
MonitorEvent is one message ubusd received from or sent to a client, as reported to a monitor. It carries the message header and the decoded attributes; fields of attributes the message did not have are zero.
type MonitorOption ¶ added in v0.2.0
type MonitorOption func(*Monitor)
MonitorOption configures Monitor. Filters are applied locally: ubusd reports everything to a monitor.
func MonitorExcludeSelf ¶ added in v0.2.0
func MonitorExcludeSelf() MonitorOption
MonitorExcludeSelf skips messages carried by this connection itself, which avoids a feedback loop when the handler makes calls.
func MonitorOnly ¶ added in v0.2.0
func MonitorOnly(d MonitorDirection) MonitorOption
MonitorOnly reports only one direction.
func MonitorTypes ¶ added in v0.2.0
func MonitorTypes(types ...MessageType) MonitorOption
MonitorTypes reports only messages of the given types. Repeated use adds types; without arguments it does nothing.
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 ¶
Close withdraws the object from the bus, like Remove with the default request timeout. It is idempotent.
func (*Object) CloseOnDone ¶
CloseOnDone closes the object when ctx is done.
func (*Object) HasSubscribers ¶
HasSubscribers reports whether the object currently has subscribers.
func (*Object) NotifyWait ¶
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. A subscriber that ubusd lists several times, having subscribed several times, is sent the notification as often: its result is Done when all are answered, holds the data of all and the first status other than StatusOK.
func (*Object) Remove ¶
Remove withdraws the object from the bus. It is idempotent; a removed object is not restored after a reconnect. Remove does not wait for running handlers and may be called from one; calls not started yet are discarded and answered with StatusNotFound, and no handler of the object starts after Remove returns.
ctx bounds only the wait. The removal at ubusd goes on after it ends, and a further Remove waits for it and returns its result.
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 ¶
OnDisconnect sets a hook called when an established connection is lost.
func OnReconnect ¶
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 ¶
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 ¶
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 ¶
WithMaxDepth sets the nesting limit for decoding message data.
func WithMaxInflight ¶
WithMaxInflight limits the number of concurrent outgoing requests. Further requests wait for a free slot or for their context.
func WithMaxMessageSize ¶
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
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 ¶
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 ¶
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
WithReplyLimits bounds the number and total size (in bytes of message data) of the replies accumulated by CallMany, CallIDMany and NotifyWait and of the objects listed by Objects and wildcard Lookup; beyond them these fail with ErrTooManyReplies. CallEach is not limited by them since it does not accumulate.
func WithRequestTimeout ¶
WithRequestTimeout sets the timeout applied to operations whose context has no deadline. It bounds the operation as a whole, from the wait for a connection to the last reply. Zero disables the implicit timeout; a registration or removal that ubusd never answers then lasts, also after its caller gave up, until the connection is lost or closed, and Shutdown waits for a registration as long as its own context allows.
func WithRestoreRetry ¶ added in v0.1.1
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, the monitor, subscribers and path subscriptions), never calls. Permission errors and invalid names are not retried.
func WithSocketPath ¶
WithSocketPath sets the ubusd socket path. Without it the default path is used, falling back to LegacySocketPath when the default is missing.
func WithWriteTimeout ¶
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 ¶
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 ¶
Reply sends a data reply. It can be called several times before the request completes.
func (*Request) SetReplyFD ¶ added in v0.2.0
SetReplyFD attaches f to the final status of the request (Complete or the implicit completion after the handler returns); a later call replaces it, nil removes it. The library sends a duplicate and closes it after sending, so the caller keeps ownership of f and may close it right away. Data replies cannot carry descriptors. It is a no-op for notifications (NoReply) and fails with ErrAlreadyCompleted after completion.
func (*Request) TakeFD ¶ added in v0.2.0
TakeFD returns the file descriptor the caller sent with the request, or nil if there was none or it was already taken. The caller of TakeFD owns the file and must close it. The file comes from an untrusted process: it may be a FIFO or socket that blocks, a directory, a device or an O_PATH descriptor. Stat it before use, use deadlines and never treat it as a directory for *at calls. A descriptor that the handler does not take is closed when the handler returns, also when it deferred the request: take it before returning.
type RestoreFailure ¶ added in v0.1.1
type RestoreFailure struct {
// Kind is "object", "listener", "monitor", "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, or, for those that expect no reply,
// because their session ended before they were handled.
DroppedNotifications uint64
// DroppedMonitorMessages counts monitor messages not delivered
// because the monitor's queue was full.
DroppedMonitorMessages uint64
// FDsLost counts messages that came with ancillary data that could
// not be received (truncated or malformed): a file descriptor may have
// been sent with them that was lost. See ErrFDLost.
FDsLost 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
// DroppedReplies counts status replies that the library itself owed
// to a caller (request refused because the object, the connection or
// the session it arrived on is going away, unknown method, invalid
// arguments, overload) and did not write: the reply queue of the
// session (256 replies) was full, the session or the connection ended
// first, or the write failed. It also counts a failure to send the
// status when a handler returns. Each lost reply counts once. Errors
// of Reply and Complete calls are returned to their caller and not
// counted. OverloadedCalls counts
// calls refused for overload whether or not that reply got out, so a
// lost overload reply appears in both.
DroppedReplies 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.
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 ends the subscriptions and removes the subscriber. It is idempotent; a closed subscriber is not restored after a reconnect. It does not wait for handlers and may be called from one: no new handler call starts after Close returns, one in progress may finish, and queued notifications are discarded. If the daemon does not answer within the request timeout, Close returns the error while the removal goes on; a further Close waits for it.
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, or because their session ended before they were handled (those expecting no reply).
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 (also if the path is already watched). 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. ctx bounds only the wait: the removal at ubusd goes on after it ends.
func (*Subscriber) UnsubscribeID ¶
func (s *Subscriber) UnsubscribeID(ctx context.Context, id uint32) error
UnsubscribeID ends a subscription made by id. ctx bounds only the wait: the removal at ubusd goes on after it ends.
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.
Source Files
¶
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. |
|
compat
|
|
|
benchgo
command
Command benchgo is the Go half of the ubusio vs libubus benchmark (compat/bench.sh).
|
Command benchgo is the Go half of the ubusio vs libubus benchmark (compat/bench.sh). |
|
size/base
command
Command base stands for an existing Go daemon: net, encoding/json, fmt and context without ubusio.
|
Command base stands for an existing Go daemon: net, encoding/json, fmt and context without ubusio. |
|
size/full
command
Command full is base plus a ubusio connection and one call.
|
Command full is base plus a ubusio connection and one call. |
|
size/hello
command
Command hello is the floor: the Go runtime and os only.
|
Command hello is the floor: the Go runtime and os only. |
|
size/httpbase
command
Command httpbase is base plus net/http (a daemon with an HTTP server).
|
Command httpbase is base plus net/http (a daemon with an HTTP server). |
|
size/httpfull
command
Command httpfull is httpbase plus a ubusio connection and one call.
|
Command httpfull is httpbase plus a ubusio connection and one call. |
|
size/minicall
command
Command minicall is the smallest useful ubusio client: connect, call one method, print the reply.
|
Command minicall is the smallest useful ubusio client: connect, call one method, print the reply. |
|
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. |
|
scripts
|
|
|
apidiff
command
Command apidiff prints the exported API of the package in the current directory, one item per line, so that two versions can be compared (see scripts/apidiff.sh).
|
Command apidiff prints the exported API of the package in the current directory, one item per line, so that two versions can be compared (see scripts/apidiff.sh). |