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) 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) 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) 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) 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 Method
- type MethodSignature
- 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 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 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 and NotifyWait 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) 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 ¶
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. 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 ¶
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) 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.
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 ¶
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) 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. Events queued but not yet passed to the handler are discarded; a handler call in progress is not interrupted.
func (*Listener) CloseOnDone ¶
CloseOnDone closes the listener when ctx is done.
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 ¶
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.
func (*Object) Remove ¶
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 ¶
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; 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 requests whose context has no deadline. Zero disables the implicit timeout.
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, 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).
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.
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.
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. |
|
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. |