Files
LocalAI/core/application/addon_gateway.go
T
mudler-agentandEttore Di Giacinto 7c74d26555 feat(addons): run the add-on owner as its own workload (#12867)
* feat(addons): generate and load a static carrier key set

A split deployment needs the owner and the frontends to share
certificates and a signing key that outlive a process. The loopback
carrier makes fresh keys at every start, so it cannot serve that.

GenerateCarrierKeys writes a CA certificate, an owner leaf and a
frontend leaf, and the frontend signing key pair. It drops the CA key,
so nobody can issue a third leaf, and it refuses to overwrite any file.
LoadCarrierConfig reads only the files of one role and refuses key
files that group or other users can access.

The owner never forwards, but NewCarrier still requires a signing key,
so the owner config gets a throwaway key in memory instead of the
frontends' private key.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): add util addons-carrier-keys

An operator who runs the add-on owner and its frontends as separate
workloads needs a way to make the shared key set. The command wraps
GenerateCarrierKeys: --out names the directory and --owner-host, which
can repeat, sets the names the owner certificate is valid for. It prints
which files belong on the owner and which on the frontends.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): add the owner and frontend roles to local-ai run

Every local-ai run process is its own add-on owner, so a distributed
deployment cannot scale its frontends: replicas that share a data
volume fight over the owner lock.

--addons-role selects combined (today's behaviour, the default), owner
or frontend. The owner and frontend roles also take --addons-owner-address
and --addons-carrier-dir, and the owner takes --addons-owner-listen. They
use the fixed carrier identities and the key set from the carrier key
directory. The frontend role has no add-on root, so it never creates the
add-ons folder. A bad role setup stops startup with a message that names
the flag.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): keep the frontend role away from owner state

A frontend holds no add-on state, but it still wrote the library
sources file of the data path, which is the owner's file. The frontend
role now skips the library option and reads only the galleries named by
the flags, and logs a warning when it has no account database, because
its pins are then kept per frontend.

The add-on manager rejects a relative root even for a forwarding
frontend, so the frontend config names the absolute path where an owner
would keep its state. Nothing creates or opens it, and a spec checks
that the data path stays empty.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* test(addons): run the owner and frontends as separate applications

The split roles are only useful if an owner and its frontends work as
separate processes that share nothing but the carrier keys and the owner
address. A spec now builds them as separate Application values with
their own data paths and keys from GenerateCarrierKeys.

It covers a frontend that lists apps and reads add-on status through the
owner, two frontends on one key set, a frontend that starts while the
owner is down and answers unavailable, a second owner refused on the
same root, and an owner that restarts on the same root and address and
still serves the installed add-on to the same frontend.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* docs(addons): describe running the owner as its own workload

An operator who runs several frontend replicas had no documented way to
stop each one from being its own add-on owner. The add-ons page now has
a section for the owner and frontend roles: one owner replica with its
own volume and a recreate-style rollout, a stable owner address, key
generation and per-role mounts, a Compose example, what a restart and an
owner outage look like, the models-path limit, and the frontend limits.
The singleton section names the roles and the distributed-state mode,
and the distributed mode page links to the new section.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): gate the addons feature in /api/features

One function, Application.AddonsFeature, decides whether the add-on
side is on. A combined or owner process answers true when add-ons are
enabled and the owner manager exists. A frontend answers true when the
owner answered the carrier's audience call within 2 s, and keeps that
answer for 10 s so /api/features does not dial the owner per request.

/api/features reports the result as "addons", and fine_tuning and
quantization take the same value, because both are add-ons. The
frontend cache is per-instance state.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): answer 503 on every add-on route when add-ons are off

With --addons-enabled=false the real add-on, fine-tuning and
quantization routes and services are not registered. One catch-all per
prefix answers the typed unavailable response of an absent owner, for
any path under it, so a client cannot tell which routes exist. The
response is the one the gateway already writes (gateway.WriteUnavailable
over typedError), not a second format.

With add-ons on, the same routes sit behind RequireAddonsFeature, which
reads Application.AddonsFeature, so a frontend that cannot reach the
owner gives the same answer. The per-user feature middleware still runs
after the gate. No endpoint is added, so the swagger, /api/instructions
and RouteFeatureRegistry surfaces do not change.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): build no carrier for a frontend with add-ons off

addonConfigFor already returned the zero config before it read a role
flag when add-ons are disabled. Say so on the way out: when a role,
owner address, listen address or carrier directory flag is set, log one
info line that the flags are ignored. A frontend with
--addons-enabled=false needs no owner address and no key directory,
loads no keys and builds no carrier.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(ui): hide add-on entries when the addons feature is off

The UI reads features.addons from /api/features. When it is false:
the sidebar shows no Add-ons entry and no pinned apps, the 404 page
lists no add-on destination, the shell does not call /api/addons/pins
or /api/addons/builtin, and /app/addons, /app/addons/*, /app/fine-tune
and /app/quantize lead back to /app. The Build hub tabs for add-ons,
fine-tuning and quantization were already keyed on features and now
follow the gate. An absent key (an older server) counts as on.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* docs(addons): describe the addons feature gate

The --addons-enabled row now says the UI hides the add-on entries and
every add-on, fine-tuning and quantization route answers 503. A new
subsection describes the addons key of /api/features, the 10 s frontend
cache as per-instance state, and that a frontend with add-ons off needs
no owner address or key directory. The fine-tuning and quantization
pages say they are off with --addons-enabled=false.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* fix(addons): give a frontend no add-on state root

OwnerConfig.validate required an absolute root for every role, so a
frontend named a path under the data directory that nothing was allowed
to open. Only the owner has a state root now: validate checks it when
the instance is the owner, and the frontend role leaves Root empty.
Nothing on a frontend reads or creates it.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* fix(addons): make the carrier signing key optional for the owner

NewCarrier required an Ed25519 signing key of every instance, so the
owner role loaded a throwaway key in memory that it never used. The
owner never signs an outbound request, so it now needs none:
NewCarrier accepts an empty key when the instance is the owner and
still requires a whole key from a frontend, and a malformed key is
refused for both. LoadCarrierConfig no longer generates one. The owner
still verifies frontend signatures with frontend-sign.pub.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* Keep the owner address out of the add-on identity file

The owner address is runtime configuration, so storing it and comparing
the whole file made a moved owner refuse its own root. The identity file
now holds the owner ID and storage ID only. An older file that still has
an address loads, and the address is ignored. A different owner ID or
storage ID is still refused.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* docs(addons): state that an existing root loads under the owner role

The owner identity no longer stores its address, so a root written by a
single node loads under the owner role when the owner and storage
identity match. Say so, and keep the caveat about absolute paths in the
journal.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* fix(addons): refuse library-source routes on a frontend

A frontend must keep no owner state, but the library-source routes, the
ApplyLibraries call and the startup official-libraries step still opened
and wrote addons/sources.json in its data path.

Mark the frontend role in the add-on config, also when add-ons are off.
On a frontend, LibrarySources returns the unavailable error,
ApplyLibraries does nothing and the startup step skips the store. The
six /api/library/sources routes answer 503 with the body that the add-on
feature gate writes, and an X-LocalAI-Reason header names the cause.
Reads are refused too: the carrier has no verb for them. Owner and
combined roles are unchanged.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* fix(addons): put the reason in the unavailable body

WriteUnavailable wrote the plain text "addon request failed", and the
library-source refusal put its reason in an X-LocalAI-Reason header.

Write the LocalAI error envelope instead, with a message, a type and the
code "unavailable", and keep the 503 status. The message names the
cause: add-ons are off on this instance, the add-on owner is not
reachable, or library sources are managed on the owner. Remove the
header.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): serve library calls on the add-on owner

Add the carrier verbs a frontend needs to work on the library through
the owner: library-list, library-add, library-update, library-enable,
library-disable, library-remove, library-backend-resolve and
library-backend-releases. A call carries the operation in one
LibraryCall field of the wire request, so an old owner rejects it as an
invalid binding. Every verb but the three reads is a mutation, and the
reply is an envelope of data or a typed error, so a frontend gives the
status the owner's own routes give.

The owner serves them through gateway.LibraryAdmin, implemented in the
application on the same LocalAdmin as the owner's HTTP routes. It runs
the owner's administrator check before any store call.

Add two peer-authenticated reads that take no actor and leave the
audience reply unchanged: GET /addons/capabilities (protocol, calls and
the owner's OS and architecture) and GET /addons/library/snapshot (the
gallery-relevant source list and its version).

Split the backend install: Installer.Resolve is the owner's half
(resolve, pick the meta backend for the asker's capability, pin by
digest) and returns a Plan; the node that installs runs the collision
check and the gallery install itself. Move the source administration
behind library.Admin and add library.ReconcileInfos for a source list
read from the owner.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): forward library routes from a frontend to the owner

A frontend refused the library-source routes and did not serve the
backend library routes. Forward them instead, and keep the owner the
only writer of the sources.

The library-source routes work on library.Admin: the local store on a
combined or owner process, the carrier on a frontend. The frontend
checks the calling account (a legacy API key is refused with 401), and
the owner checks the administrator right again before any store call.
With add-ons off, a frontend answers these routes with a 503.

A frontend asks the owner for its source list every 60 seconds through
the peer-authenticated snapshot call and rebuilds its model and backend
gallery lists, and the official-libraries switch, only when the version
changed. If the owner does not answer, it keeps the last lists and marks
them stale. Changing official_libraries on a frontend is refused with
409.

The backend library install is split. The owner resolves the entry and
pins the image; the frontend runs the gallery install on its own node,
with its own size limit and strict mode. A frontend refuses library
calls to an owner that does not serve them, or that runs on another OS
or architecture.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* docs(addons): document library operations on a frontend

Replace the frontend limits that said a frontend refuses the library
routes with what happens now: the library sources and the backend
library go through the owner, the gallery lists follow the owner every
60 seconds, official_libraries is set on the owner, and the owner and
the frontends must run on one OS and architecture.

Add specs for the split owner: a frontend lists sources through the
owner, a source added on a frontend reaches the owner and then the other
frontend after a refresh, a write with the owner down answers 503 with
the error envelope, official_libraries answers 409 on a frontend and a
change on the owner reaches the frontend's gallery lists, the lists are
kept and marked stale while the owner is down, a platform mismatch and a
legacy API key are refused, and a frontend installs a backend into its
own path from the owner's plan.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): check the shared models path with a probe

Exports write into the models path of the owner, and frontends load
models from their own path. A wrong mount fails silently: the export
succeeds and the model never appears.

The owner writes a probe file with a random nonce into its models path
at start. A frontend fetches the nonce over the carrier and checks at
start, then every 60 seconds, that the same file is visible at the same
absolute path. On a mismatch it logs an error, reports model_exports
false and blocks its export and import routes. The owner refuses an
export or import while its own probe is missing, and keeps running if
it cannot write the probe. An unreachable or older owner gives
"unknown" and leaves exports on.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* docs(api): describe the library refusal and forwarding

The library-source and backend-library routes forward to the add-on
owner on a frontend and answer 503 when the owner cannot serve them.
Add the 503 to their swagger annotations, regenerate the swagger files,
and say in /api/instructions that a frontend forwards these routes.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): let frontends run the backend update check through the owner

In named-user mode a frontend has no user to act as, so the background
backend update check failed there. Add one read-only system call for
the release lookup. The owner accepts it only on the peer-authenticated
route from a pinned frontend, only for backend-releases, and without an
actor. Calls through /addons/forward cannot carry the mark, and every
user-facing call still goes through the administrator check.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(mcp): expose the backend update check as a tool

Add list_backend_library_updates, a read-only tool for
GET /backends/library/updates. The in-process client reads the
library installer, and the HTTP client calls the route. The six
library source routes stay out of the catalog: the assistant has no
per-call actor and no approval card for library changes.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(api): add export status routes for fine-tuning and quantization

The add-on UIs could not know that model exports are blocked until a user
hit the refusal of the export route. Add GET /api/fine-tuning/status and
GET /api/quantization/status. Each returns {"model_exports": bool}, from
the same check that drives the model_exports key of /api/features.

The routes sit behind the add-ons gate, so they answer 503 when add-ons
are off. They are listed in the swagger spec, the instructions registry,
the route-feature registry and the feature docs.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

* feat(addons): disable exports when the models probe fails

The fine-tuning and quantization pages now read the new status route
and turn off the export form, the checkpoint export button and the
import button when model_exports is false. A short reason shows next
to the control. A failed or slow answer leaves the controls on, as the
server does for an unknown check.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>

---------

Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
2026-10-24 14:29:39 +02:00

458 lines
17 KiB
Go

// SPDX-License-Identifier: MIT
package application
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"path/filepath"
"time"
"github.com/mudler/LocalAI/core/http/auth"
mcpTools "github.com/mudler/LocalAI/core/http/endpoints/mcp"
"github.com/mudler/LocalAI/core/services/addons"
"github.com/mudler/LocalAI/core/services/addons/artifacts"
"github.com/mudler/LocalAI/core/services/addons/backendlib"
"github.com/mudler/LocalAI/core/services/addons/gateway"
"github.com/mudler/LocalAI/core/services/addons/hostops"
"github.com/mudler/LocalAI/core/services/addons/modelsprobe"
"github.com/mudler/LocalAI/core/services/addons/policy"
"github.com/mudler/LocalAI/core/services/addons/resources"
addonruntime "github.com/mudler/LocalAI/core/services/addons/runtime"
addontools "github.com/mudler/LocalAI/core/services/addons/tools"
"github.com/mudler/LocalAI/pkg/addons/contract"
"github.com/mudler/xlog"
"gorm.io/gorm"
)
func (a *Application) AddonGateway() *gateway.Gateway { return a.addonGateway }
// AddonToolProvider binds the tools of installed addons to the principal of a
// chat request. It is nil when the host has no addon gateway: the chat
// handler then rejects an opt-in with a typed error. The provider reads the
// ownership mode from configuration, never from a request.
func (a *Application) AddonToolProvider() *mcpTools.AddonToolProvider {
if a.addonGateway == nil {
return nil
}
return mcpTools.NewAddonToolProvider(addontools.NewToolAdapter(a.addonGateway), a.AddonOwnershipMode())
}
// AddonHostOps is the host operation channel of the add-on supervisor, or nil
// when this process offers none.
func (a *Application) AddonHostOps() *addonruntime.HostOps { return a.addonHostOps }
// newAddonHostOps builds the host operation broker for the supervisor of the
// owner. A frontend without the add-on manager, or a host whose setting names
// no add-on, builds nothing, so the channel fails closed. The setting is a
// host setting read at startup; no manifest or request can add to it.
func (a *Application) newAddonHostOps(m *addons.Manager, limits contract.Limits) *addonruntime.HostOps {
allowed := a.applicationConfig.AddonHostOps
if m == nil || len(allowed) == 0 {
return nil
}
in := hostops.NewInFlight()
broker := hostops.New(in, addonFeatureCheck(a.authDB), limits)
broker.SetAdminCheck(addonAdminCheck(a.authDB))
return &addonruntime.HostOps{Broker: broker, InFlight: in, Allowed: allowed}
}
// RegisterAddonEngineJobs registers the engine job operations with the services
// the routes use. The broker is built at startup and the services after it, so
// the HTTP setup calls this once they exist. A frontend without the broker has
// nothing to register, and the channel then fails closed.
func (a *Application) RegisterAddonEngineJobs(ft hostops.FineTuner, q hostops.Quantizer, backends hostops.BackendLister) error {
if a.addonHostOps == nil {
return nil
}
return hostops.RegisterEngineJobs(a.addonHostOps.Broker, ft, q, backends)
}
// RegisterAddonEngineProgress registers the progress and stop operations over
// the same services as RegisterAddonEngineJobs. The sources are wrapped in the
// bounded-wait reader here; a nil source registers nothing for its kind.
func (a *Application) RegisterAddonEngineProgress(ft, q hostops.ProgressSource) error {
if a.addonHostOps == nil {
return nil
}
var ftp, qp hostops.Progresser
if ft != nil {
ftp = hostops.NewProgresser(ft)
}
if q != nil {
qp = hostops.NewProgresser(q)
}
return hostops.RegisterEngineProgress(a.addonHostOps.Broker, ftp, qp)
}
// RegisterAddonEngineModels registers the model registration operations over
// the fine-tuning and quantization services. A nil source registers nothing
// for its kind.
func (a *Application) RegisterAddonEngineModels(ex hostops.Exporter, im hostops.Importer) error {
if a.addonHostOps == nil {
return nil
}
// The owner writes the exports, so it refuses them while its models path
// does not hold its probe.
ok := a.ownerProbeCurrent
if ex != nil {
ex = guardedExporter{Exporter: ex, ok: ok}
}
if im != nil {
im = guardedImporter{Importer: im, ok: ok}
}
return hostops.RegisterEngineModels(a.addonHostOps.Broker, ex, im)
}
// RegisterAddonEngineDatasets registers the inline dataset operation over the
// fine-tuning dataset store. A nil store registers nothing.
func (a *Application) RegisterAddonEngineDatasets(ds hostops.DatasetStore) error {
if a.addonHostOps == nil {
return nil
}
return hostops.RegisterEngineDatasets(a.addonHostOps.Broker, ds)
}
// addonFeatureCheck answers whether an active account holds a feature, with
// the same rule as the route middleware. Without an account database, or for
// an account that is not active, the answer is no.
func addonFeatureCheck(db *gorm.DB) func(userID, feature string) bool {
return func(userID, feature string) bool {
if db == nil || userID == "" {
return false
}
var u auth.User
if db.Where("id = ? AND status = ?", userID, auth.StatusActive).First(&u).Error != nil {
return false
}
return auth.HasFeatureAccess(db, &u, feature)
}
}
// addonAdminCheck answers whether an actor is an administrator. With an account
// database the role of the active account decides in every mode, with the rule
// of the admin routes (auth.RequireAdmin); a local-owner actor is not an
// administrator by mode alone. Without an account database there are no roles,
// so the local owner of the install is the administrator and no other actor is.
func addonAdminCheck(db *gorm.DB) func(actor contract.Actor) bool {
return func(actor contract.Actor) bool {
if db == nil {
return actor.Mode == "local-owner"
}
if actor.UserID == "" {
return false
}
var u auth.User
if db.Where("id = ? AND status = ?", actor.UserID, auth.StatusActive).First(&u).Error != nil {
return false
}
return u.Role == auth.RoleAdmin
}
}
// AddonPolicy is the owner-local resource policy. It is nil on frontends and on
// hosts without the addon transport, which then deny every resource.
func (a *Application) AddonPolicy() *policy.Policy { return a.addonPolicy }
// AddonOwnershipMode is the configured ownership mode. Named-user is the
// default; local-owner exists only when the deployment asked for it.
func (a *Application) AddonOwnershipMode() string {
if m := a.applicationConfig.Addons.OwnershipMode; m != "" {
return m
}
return auth.AddonModeNamedUser
}
// addonStatus is the manager view that creation authority consults.
type addonStatus interface {
Status(ctx context.Context, id string) (addons.Status, error)
}
// addonCreateAuthority lets an actor create a resource only for an addon that
// is installed and enabled on the owner, with no lifecycle change in flight.
// A manager that cannot answer is unavailable, never a grant.
func addonCreateAuthority(status addonStatus, revalidate func(context.Context, contract.Actor) error) func(context.Context, contract.Actor, string) error {
return func(ctx context.Context, actor contract.Actor, addonID string) error {
if status == nil || revalidate == nil {
return gateway.ErrForbidden
}
if err := revalidate(ctx, actor); err != nil {
return err
}
s, err := status.Status(ctx, addonID)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("addon status: %w: %w", gateway.ErrUnavailable, err)
}
if !s.Installed || !s.DesiredEnabled || !s.StartEligible {
return gateway.ErrForbidden
}
return nil
}
}
func (a *Application) startAddonGateway() error {
cfg := a.applicationConfig.Addons
if cfg.Transport == nil {
return nil
}
mode := a.AddonOwnershipMode()
if mode == auth.AddonModeNamedUser && a.authDB == nil {
return gateway.ErrForbidden
}
c := *cfg.Transport
if c.InstanceID != cfg.InstanceID || c.OwnerID != cfg.OwnerID || c.OwnerAddress != cfg.OwnerAddress {
return gateway.ErrForbidden
}
carrier, e := gateway.NewCarrier(c)
if e != nil {
return e
}
if mode == auth.AddonModeLocalOwner {
xlog.Warn(localOwnerWarning)
}
g := &gateway.Gateway{Limits: c.Limits, Manager: a.addonManager, Revalidate: auth.AddonRevalidate(a.authDB, mode)}
if cfg.InstanceID != cfg.OwnerID {
g.Forward = carrier
a.addonGateway = g
// The frontend installs backends on its own node and takes the
// resolved plan from the owner.
a.backendLibrary = &backendlib.Installer{
Remote: remoteBackends{a}, SystemState: a.applicationConfig.SystemState, ModelLoader: a.modelLoader,
MaxBytes: cfg.BackendMaxBytes, RequireIntegrity: a.applicationConfig.RequireBackendIntegrity,
}
go a.runLibraryRefresh(a.applicationConfig.Context)
go a.runModelsProbe(a.applicationConfig.Context)
return nil
}
// Only the owner holds the policy store. Other frontends reach it through the
// gateway, and without it the gateway keeps denying every resource.
if !filepath.IsAbs(cfg.Root) || cfg.ListenAddress == "" {
return gateway.ErrForbidden
}
store, e := policy.OpenStore(filepath.Join(cfg.Root, "policy"), policy.Mode(mode))
if e != nil {
return e
}
// Proposals are durable beside the policy store and held only here. The
// broker is the policy's proposal invalidator, so a revocation cancels the
// pending proposals of that user before it is acknowledged.
brokerOpts := policy.BrokerOptions{}
if a.addonManager != nil {
brokerOpts.Runtime = a.addonManager
}
// The same existence check settles the registrations a crash left and the
// reservations of create proposals the proposer stops waiting for.
exists := a.addonResourceExists
if exists == nil {
exists = a.addonBackingExists(contract.DefaultLimits())
}
brokerOpts.BackingExists = exists
// A deletion trusts only an explicit answer of the add-on.
confirmed := a.addonResourceExists
if confirmed == nil {
confirmed = a.addonBackingConfirmed(contract.DefaultLimits())
}
broker, e := policy.OpenBroker(filepath.Join(cfg.Root, "proposals"), brokerOpts)
if e != nil {
_ = store.Close()
return e
}
p := policy.New(store, policy.Options{
Revalidate: g.Revalidate,
CreateAuthority: addonCreateAuthority(a.addonManager, g.Revalidate),
Proposals: broker,
})
broker.Attach(p)
// Recovery gets the owner's access state. A restore or a purge that a
// crash stopped is finished now, before anything is served; an add-on
// that needs recovery stays unavailable until an administrator acts.
if a.addonManager != nil {
if rec := a.addonManager.DataRecovery(); rec != nil {
rec.SetPolicy(&policy.RecoveryPort{Policy: p, Broker: broker})
if e = rec.Reconcile(a.applicationConfig.Context); e != nil {
xlog.Warn("addons: a data recovery journal could not be finished yet", "error", e)
}
}
}
var files *artifacts.Artifacts
var selections *resources.SelectionStore
closeState := func() {
if files != nil {
_ = files.Close()
}
if selections != nil {
_ = selections.Close()
}
if a.addonReconcile != nil {
a.addonReconcile.Close()
}
_ = broker.Close()
_ = store.Close()
}
// Registrations left pending by a crash are settled before anything is
// served. A record whose backing cannot be confirmed now (its addon is
// disabled or failed to start) stays pending and hidden; it never stops
// the host from starting, and the loop below settles it later.
rep, e := p.ReconcileReport(a.applicationConfig.Context, exists)
if e != nil {
closeState()
return errors.Join(e, addons.ErrRecoveryRequired)
}
if rep.Kept > 0 {
xlog.Warn("addons: pending resource registrations could not be settled yet and stay pending", "settled", rep.Settled, "kept", rep.Kept)
}
// The conversation selections and the UI-only resource management sit
// beside the policy store and are held only here.
selections, e = resources.OpenSelections(filepath.Join(cfg.Root, "selections"), resources.SelectionOptions{})
if e != nil {
closeState()
return errors.Join(e, addons.ErrRecoveryRequired)
}
resourceOpts := resources.Options{Policy: p, Broker: broker, Users: auth.NewAddonUsers(a.authDB), Selections: selections, BackingConfirmed: confirmed, Limits: contract.DefaultLimits()}
if a.addonManager != nil {
resourceOpts.Runtime, resourceOpts.Capabilities, resourceOpts.Tools = a.addonManager, a.addonManager, a.addonManager
}
manage := resources.New(resourceOpts)
g.Resources = manage
// The owner serves the library calls of the frontends. A node with no
// source store (no catalog) has nothing to serve.
if a.addonSources != nil {
g.Libraries = a.newLibraryOwner()
g.OS, g.Arch = cfg.Host.OS, cfg.Host.Arch
}
g.ModelsProbe = func() (modelsprobe.Probe, bool) {
p := a.modelsProbe.own.Load()
if p == nil {
return modelsprobe.Probe{}, false
}
return *p, true
}
loop := policy.NewReconcileLoop(p, exists, a.addonReconcileTick)
loop.Resume = manage.Resume
loop.Report = func(r policy.ReconcileReport, err error) {
if err != nil || r.Kept > 0 {
xlog.Warn("addons: pending resource registrations remain", "settled", r.Settled, "kept", r.Kept, "error", err)
}
}
// A deletion a crash left is resumed before anything is served; one that
// cannot be finished now stays inaccessible and the loop retries it.
manage.Resume(a.applicationConfig.Context)
loop.Start(a.applicationConfig.Context)
a.addonReconcile = loop
// A proposal that was executing when the owner stopped is settled by
// receipt lookup, or recorded as outcome-unknown. Nothing is applied again.
if e = broker.Recover(a.applicationConfig.Context); e != nil {
closeState()
return errors.Join(e, addons.ErrRecoveryRequired)
}
// Unresolved outcomes are looked up again with backoff for a finite
// window, and expiry stays recorded. Run ends with the application
// context or when the broker is closed.
go broker.Run(a.applicationConfig.Context)
provider := p.Gateway()
g.Admission, g.Resolver = provider, provider
g.Proposals = broker.Gateway()
// Private file results are staged beside the other owner state. Without a
// manager there is no runtime to read them from, and the gateway then
// denies every file result and download.
if a.addonManager != nil {
files, e = artifacts.Open(artifacts.Options{
Dir: filepath.Join(cfg.Root, "artifacts"),
Policy: p,
Runtime: a.addonManager,
Addon: artifactAddonState(a.addonManager),
Limits: artifacts.DefaultLimits().WithExpiry(cfg.ArtifactExpiry),
})
if e != nil {
closeState()
return e
}
provider.Outputs = files
g.Artifacts = files.Gateway()
go files.Run(a.applicationConfig.Context)
}
handler, e := carrier.OwnerHandler(g)
if e != nil {
closeState()
return e
}
listener, e := net.Listen("tcp", cfg.ListenAddress)
if e != nil {
closeState()
return e
}
server := &http.Server{Handler: handler, TLSConfig: carrier.ServerTLS(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 65 * time.Second, IdleTimeout: 10 * time.Second, MaxHeaderBytes: 16 << 10}
a.addonServer = server
a.addonGateway = g
a.addonPolicy, a.addonStore = p, store
if pinStore, err := a.AddonPinStore(); err != nil {
xlog.Warn("addon pin sweep not started", "error", err)
} else {
a.startAddonPinSweep(a.applicationConfig.Context, pinStore)
}
go func() { _ = server.Serve(tls.NewListener(listener, server.TLSConfig)) }()
go func() { <-a.applicationConfig.Context.Done(); _ = server.Close(); closeState() }()
return nil
}
// addonBackingExists is the real existence check for resources whose backing
// lives in an addon (Tables databases). Without a manager there is no addon
// that could back a resource, so a pending record is dropped as before.
func (a *Application) addonBackingExists(limits contract.Limits) func(context.Context, policy.ResourceKey) (bool, error) {
m := a.addonManager
if m == nil {
return func(context.Context, policy.ResourceKey) (bool, error) { return false, nil }
}
return policy.BackingExists(policy.BackingOptions{
Runtime: m,
Tools: m,
Installed: func(ctx context.Context, id string) (bool, error) {
s, err := m.Status(ctx, id)
return s.Installed, err
},
Limits: limits,
})
}
// addonBackingConfirmed is the existence check of a deletion. Unlike
// addonBackingExists it never reads a missing manager, an add-on that is not
// installed or one that does not declare the existence tool as "gone".
func (a *Application) addonBackingConfirmed(limits contract.Limits) func(context.Context, policy.ResourceKey) (bool, error) {
m := a.addonManager
if m == nil {
return func(context.Context, policy.ResourceKey) (bool, error) { return false, policy.ErrBackingUnanswered }
}
return policy.BackingConfirmed(policy.BackingOptions{
Runtime: m,
Tools: m,
Installed: func(ctx context.Context, id string) (bool, error) {
s, err := m.Status(ctx, id)
return s.Installed, err
},
Limits: limits,
})
}
// artifactAddonState reports the lifecycle state the artifact store needs. A
// manager that cannot answer is an error, never an enabled addon.
func artifactAddonState(status addonStatus) func(context.Context, string) (artifacts.AddonState, error) {
return func(ctx context.Context, addonID string) (artifacts.AddonState, error) {
s, err := status.Status(ctx, addonID)
if err != nil {
return artifacts.AddonState{}, err
}
return artifacts.AddonState{Installed: s.Installed, Enabled: s.DesiredEnabled, Generation: s.Generation}, nil
}
}
// localOwnerWarning is logged at startup in local-owner mode. There is no
// session in that mode, so the confirmation boundary is the browser headers
// only and does not stop a script that sets them.
const localOwnerWarning = "addons: local-owner mode is enabled; unauthenticated callers share one authority over every addon resource and sharing is disabled; any caller that can reach this port can confirm addon proposals"