package plugins
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/Masterminds/squirrel"
extism "github.com/extism/go-sdk"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/core/sonic"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/utils/singleton"
"github.com/rjeczalik/notify"
"github.com/tetratelabs/wazero"
)
const (
defaultTimeout = 30 * time.Second
maxPluginLoadConcurrency = 3
)
type SubsonicRouter = http.Handler
type PluginMetricsRecorder interface {
RecordPluginRequest(ctx context.Context, plugin, method string, ok bool, elapsed int64)
}
type Manager struct {
mu sync.RWMutex
plugins map[string]*plugin
ctx context.Context
cancel context.CancelFunc
cache wazero.CompilationCache
stopped atomic.Bool
loadWg sync.WaitGroup
watcherEvents chan notify.EventInfo
watcherDone chan struct{}
debounceTimers map[string]*time.Timer
debounceMu sync.Mutex
subsonicRouter SubsonicRouter
ds model.DataStore
broker events.Broker
metrics PluginMetricsRecorder
}
func GetManager(ds model.DataStore, broker events.Broker, m PluginMetricsRecorder) *Manager {
return singleton.GetInstance(func() *Manager {
return &Manager{
ds: ds,
broker: broker,
metrics: m,
plugins: make(map[string]*plugin),
}
})
}
func (m *Manager) sendPluginRefreshEvent(ctx context.Context, pluginIDs ...string) {
if m.broker == nil {
return
}
event := (&events.RefreshResource{}).With("plugin", pluginIDs...)
m.broker.SendBroadcastMessage(ctx, event)
}
func (m *Manager) SetSubsonicRouter(router SubsonicRouter) {
m.subsonicRouter = router
}
func (m *Manager) Start(ctx context.Context) error {
if !conf.Server.Plugins.Enabled {
log.Debug(ctx, "Plugin system is disabled")
return nil
}
if m.subsonicRouter == nil {
log.Fatal(ctx, "Plugin manager requires DataStore to be configured")
}
pluginLogLevel := conf.Server.Plugins.LogLevel
if pluginLogLevel == "" {
pluginLogLevel = conf.Server.LogLevel
}
extism.SetLogLevel(toExtismLogLevel(log.ParseLogLevel(pluginLogLevel)))
m.ctx, m.cancel = context.WithCancel(ctx)
cacheDir := filepath.Join(conf.Server.CacheFolder.MustPath(), "plugins")
purgeCacheBySize(ctx, cacheDir, conf.Server.Plugins.CacheSize)
var err error
m.cache, err = wazero.NewCompilationCacheWithDir(cacheDir)
if err != nil {
log.Error(ctx, "Failed to create wazero compilation cache", err)
return fmt.Errorf("creating wazero compilation cache: %w", err)
}
if conf.Server.Plugins.Folder.String() == "" {
log.Debug(ctx, "No plugins folder configured")
return nil
}
folder := conf.Server.Plugins.Folder.MustPath()
log.Info(ctx, "Starting plugin manager", "folder", folder)
adminCtx := adminContext(ctx)
if err := m.ds.Plugin(adminCtx).ClearErrors(); err != nil {
log.Error(ctx, "Error clearing plugin errors", err)
}
if err := m.syncPlugins(ctx, folder); err != nil {
log.Error(ctx, "Error syncing plugins with DB", err)
}
if err := m.loadEnabledPlugins(ctx); err != nil {
log.Error(ctx, "Error loading enabled plugins", err)
return fmt.Errorf("loading enabled plugins: %w", err)
}
if conf.Server.Plugins.AutoReload {
if err := m.startWatcher(); err != nil {
log.Error(ctx, "Failed to start plugin file watcher", err)
}
}
return nil
}
func (m *Manager) Stop() error {
m.stopped.Store(true)
if m.cancel != nil {
m.cancel()
}
m.stopWatcher()
m.loadWg.Wait()
m.mu.Lock()
defer m.mu.Unlock()
for name, plugin := range m.plugins {
err := plugin.Close()
if err != nil {
log.Error("Error during plugin cleanup", "plugin", name, err)
}
if plugin.compiled != nil {
if err := plugin.compiled.Close(context.Background()); err != nil {
log.Error("Error closing plugin", "plugin", name, err)
}
}
}
m.plugins = make(map[string]*plugin)
if m.cache != nil {
if err := m.cache.Close(context.Background()); err != nil {
log.Error("Error closing wazero cache", err)
}
m.cache = nil
}
return nil
}
func (m *Manager) PluginNames(capability string) []string {
m.mu.RLock()
defer m.mu.RUnlock()
var names []string
cap := Capability(capability)
for name, plugin := range m.plugins {
if hasCapability(plugin.capabilities, cap) {
names = append(names, name)
}
}
return names
}
func (m *Manager) LoadMediaAgent(name string) (agents.Interface, bool) {
return loadPlugin(m, name, CapabilityMetadataAgent, newMetadataAgent)
}
func (m *Manager) LoadScrobbler(name string) (scrobbler.Scrobbler, bool) {
return loadPlugin(m, name, CapabilityScrobbler, newScrobblerPlugin)
}
func (m *Manager) LoadLyricsProvider(name string) (lyrics.Lyrics, bool) {
return loadPlugin(m, name, CapabilityLyrics, newLyricsPlugin)
}
func (m *Manager) LoadSonicSimilarity(name string) (sonic.Provider, bool) {
return loadPlugin(m, name, CapabilitySonicSimilarity, newSonicSimilarityPlugin)
}
func loadPlugin[T any](m *Manager, name string, cap Capability, newAdapter func(*plugin) T) (T, bool) {
m.mu.RLock()
p, ok := m.plugins[name]
m.mu.RUnlock()
var zero T
if !ok || !hasCapability(p.capabilities, cap) {
return zero, false
}
return newAdapter(p), true
}
type PluginInfo struct {
Name string
Version string
}
func (m *Manager) GetPluginInfo() map[string]PluginInfo {
m.mu.RLock()
defer m.mu.RUnlock()
info := make(map[string]PluginInfo, len(m.plugins))
for name, plugin := range m.plugins {
info[name] = PluginInfo{
Name: plugin.manifest.Name,
Version: plugin.manifest.Version,
}
}
return info
}
func (m *Manager) EnablePlugin(ctx context.Context, id string) error {
if m.ds == nil {
return fmt.Errorf("datastore not configured")
}
adminCtx := adminContext(ctx)
repo := m.ds.Plugin(adminCtx)
plugin, err := repo.Get(id)
if err != nil {
return fmt.Errorf("getting plugin from DB: %w", err)
}
if plugin.Enabled {
return nil
}
if err := m.checkPermissionGates(plugin); err != nil {
return err
}
if err := m.loadPluginWithConfig(plugin); err != nil {
plugin.LastError = err.Error()
plugin.UpdatedAt = time.Now()
_ = repo.Put(plugin)
return fmt.Errorf("loading plugin: %w", err)
}
plugin.Enabled = true
plugin.LastError = ""
plugin.UpdatedAt = time.Now()
if err := repo.Put(plugin); err != nil {
_ = m.unloadPlugin(id)
return fmt.Errorf("updating plugin in DB: %w", err)
}
log.Info(ctx, "Enabled plugin", "plugin", id)
m.sendPluginRefreshEvent(ctx, id)
return nil
}
func (m *Manager) DisablePlugin(ctx context.Context, id string) error {
if m.ds == nil {
return fmt.Errorf("datastore not configured")
}
adminCtx := adminContext(ctx)
repo := m.ds.Plugin(adminCtx)
plugin, err := repo.Get(id)
if err != nil {
return fmt.Errorf("getting plugin from DB: %w", err)
}
if !plugin.Enabled {
return nil
}
if err := m.unloadPlugin(id); err != nil {
log.Debug(ctx, "Plugin was not loaded", "plugin", id)
}
plugin.Enabled = false
plugin.UpdatedAt = time.Now()
if err := repo.Put(plugin); err != nil {
return fmt.Errorf("updating plugin in DB: %w", err)
}
log.Info(ctx, "Disabled plugin", "plugin", id)
m.sendPluginRefreshEvent(ctx, id)
return nil
}
func (m *Manager) ValidatePluginConfig(ctx context.Context, id, configJSON string) error {
if m.ds == nil {
return fmt.Errorf("datastore not configured")
}
adminCtx := adminContext(ctx)
repo := m.ds.Plugin(adminCtx)
plugin, err := repo.Get(id)
if err != nil {
return fmt.Errorf("getting plugin from DB: %w", err)
}
manifest, err := readManifest(plugin.Path)
if err != nil {
return fmt.Errorf("reading manifest: %w", err)
}
return ValidateConfig(manifest, configJSON)
}
func (m *Manager) UpdatePluginConfig(ctx context.Context, id, configJSON string) error {
return m.updatePluginSettings(ctx, id, func(p *model.Plugin) {
p.Config = configJSON
})
}
func (m *Manager) UpdatePluginUsers(ctx context.Context, id, usersJSON string, allUsers bool) error {
return m.updatePluginSettings(ctx, id, func(p *model.Plugin) {
p.Users = usersJSON
p.AllUsers = allUsers
})
}
func (m *Manager) UpdatePluginLibraries(ctx context.Context, id, librariesJSON string, allLibraries, allowWriteAccess bool) error {
return m.updatePluginSettings(ctx, id, func(p *model.Plugin) {
p.Libraries = librariesJSON
p.AllLibraries = allLibraries
p.AllowWriteAccess = allowWriteAccess
})
}
func (m *Manager) RescanPlugins(ctx context.Context) error {
folder := conf.Server.Plugins.Folder.String()
if folder == "" {
return fmt.Errorf("plugins folder not configured")
}
log.Info(ctx, "Manual plugin rescan requested", "folder", folder)
return m.syncPlugins(ctx, folder)
}
func (m *Manager) updatePluginSettings(ctx context.Context, id string, updateFn func(*model.Plugin)) error {
if m.ds == nil {
return fmt.Errorf("datastore not configured")
}
adminCtx := adminContext(ctx)
repo := m.ds.Plugin(adminCtx)
plugin, err := repo.Get(id)
if err != nil {
return fmt.Errorf("getting plugin from DB: %w", err)
}
wasEnabled := plugin.Enabled
updateFn(plugin)
plugin.UpdatedAt = time.Now()
shouldDisable := false
disableReason := ""
if wasEnabled {
manifest, err := readManifest(plugin.Path)
if err == nil && manifest.Permissions != nil {
if manifest.Permissions.Users != nil && !hasValidUsersConfig(plugin.Users, plugin.AllUsers) {
shouldDisable = true
disableReason = "users permission removal"
}
if manifest.Permissions.Library != nil && !hasValidLibrariesConfig(plugin.Libraries, plugin.AllLibraries) {
shouldDisable = true
disableReason = "library permission removal"
}
}
}
if shouldDisable {
if err := m.unloadPlugin(id); err != nil {
log.Debug(ctx, "Plugin was not loaded", "plugin", id)
}
plugin.Enabled = false
if err := repo.Put(plugin); err != nil {
return fmt.Errorf("updating plugin in DB: %w", err)
}
log.Info(ctx, "Disabled plugin due to "+disableReason, "plugin", id)
m.sendPluginRefreshEvent(ctx, id)
return nil
}
if err := repo.Put(plugin); err != nil {
return fmt.Errorf("updating plugin in DB: %w", err)
}
if wasEnabled {
if err := m.unloadPlugin(id); err != nil {
log.Debug(ctx, "Plugin was not loaded", "plugin", id)
}
if err := m.loadPluginWithConfig(plugin); err != nil {
plugin.LastError = err.Error()
plugin.Enabled = false
_ = repo.Put(plugin)
return fmt.Errorf("reloading plugin: %w", err)
}
}
log.Info(ctx, "Updated plugin settings", "plugin", id)
m.sendPluginRefreshEvent(ctx, id)
return nil
}
func (m *Manager) unloadPlugin(name string) error {
m.mu.Lock()
plugin, ok := m.plugins[name]
if !ok {
m.mu.Unlock()
return fmt.Errorf("plugin %q not found", name)
}
delete(m.plugins, name)
m.mu.Unlock()
err := plugin.Close()
if err != nil {
log.Error("Error during plugin cleanup", "plugin", name, err)
}
if plugin.compiled != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := plugin.compiled.Close(ctx); err != nil {
log.Error("Error closing plugin during unload", "plugin", name, err)
}
}
runtime.GC()
log.Info(m.ctx, "Unloaded plugin", "plugin", name)
return nil
}
func (m *Manager) UnloadDisabledPlugins(ctx context.Context) {
if m.ds == nil {
return
}
adminCtx := adminContext(ctx)
repo := m.ds.Plugin(adminCtx)
plugins, err := repo.GetAll(model.QueryOptions{
Filters: squirrel.Eq{"enabled": false},
})
if err != nil {
log.Error(ctx, "Failed to get disabled plugins", err)
return
}
var unloaded []string
for _, p := range plugins {
m.mu.RLock()
_, loaded := m.plugins[p.ID]
m.mu.RUnlock()
if loaded {
if err := m.unloadPlugin(p.ID); err != nil {
log.Warn(ctx, "Failed to unload disabled plugin", "plugin", p.ID, err)
} else {
unloaded = append(unloaded, p.ID)
log.Info(ctx, "Unloaded disabled plugin", "plugin", p.ID)
}
}
}
if len(unloaded) > 0 {
m.sendPluginRefreshEvent(ctx, unloaded...)
}
}
func (m *Manager) checkPermissionGates(p *model.Plugin) error {
manifest, err := readManifest(p.Path)
if err != nil {
return fmt.Errorf("reading manifest: %w", err)
}
if manifest.Permissions != nil && manifest.Permissions.Users != nil {
if !hasValidUsersConfig(p.Users, p.AllUsers) {
return fmt.Errorf("users permission requires configuration: select users or enable 'all users' access")
}
}
if manifest.Permissions != nil && manifest.Permissions.Library != nil {
if !hasValidLibrariesConfig(p.Libraries, p.AllLibraries) {
return fmt.Errorf("library permission requires configuration: select libraries or enable 'all libraries' access")
}
}
return nil
}
func hasValidUsersConfig(usersJSON string, allUsers bool) bool {
if allUsers {
return true
}
if usersJSON == "" {
return false
}
var users []string
if err := json.Unmarshal([]byte(usersJSON), &users); err != nil {
return false
}
return len(users) > 0
}
func hasValidLibrariesConfig(librariesJSON string, allLibraries bool) bool {
if allLibraries {
return true
}
if librariesJSON == "" {
return false
}
var libraries []int
if err := json.Unmarshal([]byte(librariesJSON), &libraries); err != nil {
return false
}
return len(libraries) > 0
}