mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-02 10:09:02 +01:00
The optional handler interface can contain a typed nil tenant manager. Keep its canonical config mutation synchronous even when there is no tenant snapshot to publish. Add a regression for that single-runtime boundary. Contract-Neutral: Preserve existing single-runtime settings application; no API, schema or visible surface contract delta. Change-source: pulse-maintainer
660 lines
22 KiB
Go
660 lines
22 KiB
Go
package monitoring
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
|
|
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// MultiTenantMonitor manages a dedicated Monitor instance for each organization.
|
|
type MultiTenantMonitor struct {
|
|
// Serialize constructors and dependency wiring without holding mu across
|
|
// persistence or callbacks. Live tenant reads only need mu, not initMu.
|
|
initMu sync.Mutex
|
|
// Share the actual settings writer's boundary with template reads and
|
|
// snapshot capture. Live lookups/visitors never acquire this lock, and
|
|
// dependency callbacks run only after it is released.
|
|
configMu sync.Mutex
|
|
mu sync.RWMutex
|
|
monitors map[string]*Monitor
|
|
tenantCancel map[string]context.CancelFunc
|
|
tenantDone map[string]chan struct{}
|
|
// A visitor racing construction invalidates its instance-settings snapshot.
|
|
// Protected by mu; settings I/O and callbacks never run while holding mu.
|
|
propagationGeneration uint64
|
|
instanceSettings tenantInstanceSettings
|
|
tenantDeleting map[string]struct{}
|
|
tenantStopping map[string]struct{}
|
|
persistence *config.MultiTenantPersistence
|
|
baseConfig *config.Config
|
|
wsHub *websocket.Hub
|
|
recoveryMgr *recoverymanager.Manager
|
|
initializer func(*Monitor)
|
|
globalCtx context.Context
|
|
globalCancel context.CancelFunc
|
|
stopped bool // Terminal admission fence, protected by mu.
|
|
}
|
|
|
|
// Immutable values captured with the actual config mutation, not by unrelated
|
|
// visitors. Constructors never retain request-local propagation callbacks.
|
|
type tenantInstanceSettings struct {
|
|
publicURL string
|
|
backupEnabled bool
|
|
backupInterval time.Duration
|
|
pbsInterval time.Duration
|
|
pmgInterval time.Duration
|
|
}
|
|
|
|
func captureTenantInstanceSettings(cfg *config.Config) tenantInstanceSettings {
|
|
if cfg == nil {
|
|
return tenantInstanceSettings{}
|
|
}
|
|
return tenantInstanceSettings{
|
|
publicURL: cfg.PublicURL, backupEnabled: cfg.EnableBackupPolling,
|
|
backupInterval: cfg.BackupPollingInterval,
|
|
pbsInterval: cfg.PBSPollingInterval, pmgInterval: cfg.PMGPollingInterval,
|
|
}
|
|
}
|
|
|
|
// UpdateInstanceSettings applies the settings handler's config mutation and
|
|
// captures the resulting runtime settings as one publication. The callback is
|
|
// synchronous and must only mutate config: no persistence, monitor lookup or
|
|
// side effect that can wait for initialization. In particular it never runs
|
|
// under initMu or the live-reader mutex, and is never retained for later use.
|
|
func (mtm *MultiTenantMonitor) UpdateInstanceSettings(update func()) {
|
|
if update == nil {
|
|
return
|
|
}
|
|
// The settings handler's optional interface can contain a typed nil
|
|
// manager on single-runtime installs. The config write still belongs to
|
|
// the handler even when there is no tenant snapshot to publish.
|
|
if mtm == nil {
|
|
update()
|
|
return
|
|
}
|
|
mtm.configMu.Lock()
|
|
defer mtm.configMu.Unlock()
|
|
update()
|
|
runtime := captureTenantInstanceSettings(mtm.baseConfig)
|
|
mtm.mu.Lock()
|
|
mtm.instanceSettings = runtime
|
|
mtm.propagationGeneration++
|
|
mtm.mu.Unlock()
|
|
}
|
|
|
|
// NewMultiTenantMonitor creates a new multi-tenant monitor manager.
|
|
func NewMultiTenantMonitor(baseCfg *config.Config, persistence *config.MultiTenantPersistence, wsHub *websocket.Hub) *MultiTenantMonitor {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
return &MultiTenantMonitor{
|
|
monitors: make(map[string]*Monitor),
|
|
tenantCancel: make(map[string]context.CancelFunc),
|
|
tenantDone: make(map[string]chan struct{}),
|
|
tenantDeleting: make(map[string]struct{}),
|
|
tenantStopping: make(map[string]struct{}),
|
|
persistence: persistence,
|
|
baseConfig: baseCfg, // Used as a template or for global settings
|
|
instanceSettings: captureTenantInstanceSettings(baseCfg),
|
|
wsHub: wsHub,
|
|
globalCtx: ctx,
|
|
globalCancel: cancel,
|
|
}
|
|
}
|
|
|
|
// Both shutdown budgets are variables so tests can shorten them.
|
|
var (
|
|
// tenantMonitorShutdownTimeout bounds how long process shutdown and
|
|
// RemoveTenant wait for a tenant's monitoring loop to exit.
|
|
tenantMonitorShutdownTimeout = 2 * time.Second
|
|
|
|
// tenantDeletionShutdownTimeout bounds how long organization deletion
|
|
// waits for the loop. Deletion refuses, and keeps the data, while the loop
|
|
// still runs, so this is a correctness gate rather than a best-effort
|
|
// wait: a loop that is still starting up or finishing a tick can take
|
|
// several seconds to see its cancelled context.
|
|
tenantDeletionShutdownTimeout = 30 * time.Second
|
|
)
|
|
|
|
// SetRecoveryManager wires a recovery store manager into all existing and future tenant monitors.
|
|
func (mtm *MultiTenantMonitor) SetRecoveryManager(manager *recoverymanager.Manager) {
|
|
mtm.initMu.Lock()
|
|
defer mtm.initMu.Unlock()
|
|
mtm.mu.Lock()
|
|
defer mtm.mu.Unlock()
|
|
mtm.recoveryMgr = manager
|
|
for _, monitor := range mtm.monitors {
|
|
if monitor == nil {
|
|
continue
|
|
}
|
|
monitor.SetRecoveryManager(manager)
|
|
}
|
|
}
|
|
|
|
// SetMonitorInitializer configures a callback that is applied to all existing
|
|
// and future tenant monitors after creation.
|
|
func (mtm *MultiTenantMonitor) SetMonitorInitializer(initializer func(*Monitor)) {
|
|
if mtm == nil {
|
|
return
|
|
}
|
|
|
|
mtm.initMu.Lock()
|
|
defer mtm.initMu.Unlock()
|
|
mtm.mu.Lock()
|
|
mtm.initializer = initializer
|
|
monitors := make([]*Monitor, 0, len(mtm.monitors))
|
|
for _, monitor := range mtm.monitors {
|
|
if monitor == nil {
|
|
continue
|
|
}
|
|
monitors = append(monitors, monitor)
|
|
}
|
|
mtm.mu.Unlock()
|
|
|
|
if initializer == nil {
|
|
return
|
|
}
|
|
for _, monitor := range monitors {
|
|
initializer(monitor)
|
|
}
|
|
}
|
|
|
|
// ForEachMonitor runs fn synchronously against every live tenant monitor.
|
|
// Policy reloads also invalidate an admitted constructor's settings snapshot,
|
|
// which it reconciles before publication. Runtime values are captured by the
|
|
// settings writer, never read from mutable config by this generic iterator.
|
|
// Do not wait for construction here: callers can hold router settings locks needed by live
|
|
// requests. Do not retain fn: callers can close over request-local mutable state.
|
|
func (mtm *MultiTenantMonitor) ForEachMonitor(fn func(*Monitor)) {
|
|
if mtm == nil || fn == nil {
|
|
return
|
|
}
|
|
mtm.mu.Lock()
|
|
mtm.propagationGeneration++
|
|
monitors := make([]*Monitor, 0, len(mtm.monitors))
|
|
for _, monitor := range mtm.monitors {
|
|
if monitor != nil {
|
|
monitors = append(monitors, monitor)
|
|
}
|
|
}
|
|
mtm.mu.Unlock()
|
|
for _, monitor := range monitors {
|
|
fn(monitor)
|
|
}
|
|
}
|
|
|
|
// ListOrganizationIDs returns the persisted organization IDs known to the
|
|
// tenant monitor without requiring every monitor to be initialized first.
|
|
func (mtm *MultiTenantMonitor) ListOrganizationIDs() ([]string, error) {
|
|
if mtm == nil || mtm.persistence == nil {
|
|
return []string{"default"}, nil
|
|
}
|
|
orgs, err := mtm.persistence.ListOrganizations()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ids := make([]string, 0, len(orgs))
|
|
for _, org := range orgs {
|
|
if org == nil || strings.TrimSpace(org.ID) == "" {
|
|
continue
|
|
}
|
|
ids = append(ids, strings.TrimSpace(org.ID))
|
|
}
|
|
if len(ids) == 0 {
|
|
ids = append(ids, "default")
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
// GetMonitor returns the monitor instance for a specific organization.
|
|
// It lazily initializes the monitor if it doesn't exist.
|
|
func (mtm *MultiTenantMonitor) GetMonitor(orgID string) (*Monitor, error) {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
return nil, fmt.Errorf("organization ID is required")
|
|
}
|
|
|
|
mtm.mu.RLock()
|
|
if mtm.stopped {
|
|
mtm.mu.RUnlock()
|
|
return nil, fmt.Errorf("tenant monitor manager is stopped")
|
|
}
|
|
monitor, exists := mtm.monitors[orgID]
|
|
_, deleting := mtm.tenantDeleting[orgID]
|
|
mtm.mu.RUnlock()
|
|
|
|
if deleting {
|
|
return nil, fmt.Errorf("organization %q is being deleted", orgID)
|
|
}
|
|
if exists {
|
|
return monitor, nil
|
|
}
|
|
|
|
mtm.initMu.Lock()
|
|
defer mtm.initMu.Unlock()
|
|
mtm.mu.Lock()
|
|
// Another constructor, deletion or retirement may have won while this
|
|
// caller waited. Never initialize over retained work or a closed owner.
|
|
if mtm.stopped {
|
|
mtm.mu.Unlock()
|
|
return nil, fmt.Errorf("tenant monitor manager is stopped")
|
|
}
|
|
if _, deleting = mtm.tenantDeleting[orgID]; deleting {
|
|
mtm.mu.Unlock()
|
|
return nil, fmt.Errorf("organization %q is being deleted", orgID)
|
|
}
|
|
if monitor, exists = mtm.monitors[orgID]; exists {
|
|
mtm.mu.Unlock()
|
|
return monitor, nil
|
|
}
|
|
if mtm.persistence == nil {
|
|
mtm.mu.Unlock()
|
|
return nil, fmt.Errorf("tenant persistence is not configured")
|
|
}
|
|
if mtm.monitors == nil {
|
|
mtm.monitors = make(map[string]*Monitor)
|
|
}
|
|
if mtm.tenantCancel == nil {
|
|
mtm.tenantCancel = make(map[string]context.CancelFunc)
|
|
}
|
|
if mtm.tenantDone == nil {
|
|
mtm.tenantDone = make(map[string]chan struct{})
|
|
}
|
|
|
|
// Own the entire initialization/loop lifetime before releasing admission.
|
|
// Stop and deletion must retain the data even when New or a callback is
|
|
// still running and there is no completed monitor in the cache yet.
|
|
tenantCtx, tenantCancel := context.WithCancel(mtm.globalCtx)
|
|
tenantDone := make(chan struct{})
|
|
mtm.tenantCancel[orgID] = tenantCancel
|
|
mtm.tenantDone[orgID] = tenantDone
|
|
generation := mtm.propagationGeneration
|
|
mtm.mu.Unlock()
|
|
|
|
monitor, err := mtm.initializeTenantMonitor(orgID)
|
|
mtm.mu.Lock()
|
|
for err == nil {
|
|
if _, deleting = mtm.tenantDeleting[orgID]; mtm.stopped || deleting || generation == mtm.propagationGeneration {
|
|
break
|
|
}
|
|
generation = mtm.propagationGeneration
|
|
instanceSettings := mtm.instanceSettings
|
|
mtm.mu.Unlock()
|
|
err = mtm.reconcileTenantInstanceSettings(monitor, instanceSettings)
|
|
mtm.mu.Lock()
|
|
// A save can race this read too. Publication shares mu with the
|
|
// visitor: repeat until it cannot miss a completed settings update.
|
|
}
|
|
if err != nil {
|
|
tenantCancel()
|
|
mtm.mu.Unlock()
|
|
var cleanupErr error
|
|
if monitor != nil {
|
|
cleanupErr = monitor.stop()
|
|
}
|
|
mtm.mu.Lock()
|
|
if cleanupErr == nil {
|
|
delete(mtm.tenantCancel, orgID)
|
|
delete(mtm.tenantDone, orgID)
|
|
} else {
|
|
// Failed settings admission cannot lose an incompletely stopped
|
|
// constructor or expose it as a live runtime on the next lookup.
|
|
mtm.monitors[orgID] = monitor
|
|
if mtm.tenantDeleting == nil {
|
|
mtm.tenantDeleting = make(map[string]struct{})
|
|
}
|
|
mtm.tenantDeleting[orgID] = struct{}{}
|
|
}
|
|
close(tenantDone)
|
|
mtm.mu.Unlock()
|
|
return nil, errors.Join(err, cleanupErr)
|
|
}
|
|
mtm.monitors[orgID] = monitor
|
|
if _, deleting = mtm.tenantDeleting[orgID]; mtm.stopped || deleting {
|
|
// A timed-out remover still owns this finished constructor. Do not
|
|
// expose or start it; publish ownership before signaling completion so
|
|
// the remover (or a later retry) can stop all of its writers safely.
|
|
tenantCancel()
|
|
close(tenantDone)
|
|
mtm.mu.Unlock()
|
|
return nil, fmt.Errorf("organization %q initialization was cancelled", orgID)
|
|
}
|
|
go func() {
|
|
defer close(tenantDone)
|
|
monitor.Start(tenantCtx, mtm.wsHub)
|
|
}()
|
|
mtm.mu.Unlock()
|
|
return monitor, nil
|
|
}
|
|
|
|
// Reconcile only the existing instance-wide settings propagated by the settings
|
|
// API and router. Use the committed security policy and captured runtime
|
|
// settings, not a caller's callback or the mutable base configuration. The caller
|
|
// owns initMu, not mu, and rechecks the generation and lifecycle fences before
|
|
// publication. Failed policy reads refuse admission instead of reviving grants.
|
|
func (mtm *MultiTenantMonitor) reconcileTenantInstanceSettings(monitor *Monitor, runtime tenantInstanceSettings) error {
|
|
persistence, err := mtm.persistence.GetPersistence("default")
|
|
if err != nil {
|
|
return fmt.Errorf("load instance settings persistence: %w", err)
|
|
}
|
|
settings, err := persistence.LoadSystemSettings()
|
|
if err != nil {
|
|
return fmt.Errorf("reconcile instance settings during tenant admission: %w", err)
|
|
}
|
|
if settings == nil {
|
|
// Match New's deny-private default when no settings file exists.
|
|
settings = &config.SystemSettings{}
|
|
}
|
|
nets, err := notifications.ParseAllowedPrivateCIDRs(settings.WebhookAllowedPrivateCIDRs)
|
|
if err != nil {
|
|
return fmt.Errorf("reconcile notification policy during tenant admission: %w", err)
|
|
}
|
|
if nm := monitor.GetNotificationManager(); nm != nil {
|
|
nm.ApplyAllowedPrivateCIDRs(settings.WebhookAllowedPrivateCIDRs, nets)
|
|
nm.SetPublicURL(runtime.publicURL)
|
|
}
|
|
monitor.SetBackupPollingEnabled(runtime.backupEnabled)
|
|
monitor.SetBackupPollingInterval(runtime.backupInterval)
|
|
monitor.SetPBSPollingInterval(runtime.pbsInterval)
|
|
monitor.SetPMGPollingInterval(runtime.pmgInterval)
|
|
return nil
|
|
}
|
|
|
|
// initializeTenantMonitor runs under initMu, never mu. Constructors remain
|
|
// serialized, and dependency setters cannot miss an admitted initialization.
|
|
func (mtm *MultiTenantMonitor) initializeTenantMonitor(orgID string) (*Monitor, error) {
|
|
if mtm.persistence == nil {
|
|
return nil, fmt.Errorf("tenant persistence is not configured")
|
|
}
|
|
if orgID != "default" && !mtm.persistence.OrgExists(orgID) {
|
|
return nil, fmt.Errorf("organization %q is not provisioned", orgID)
|
|
}
|
|
|
|
// Initialize new monitor for this tenant
|
|
log.Info().Str("org_id", orgID).Msg("initializing tenant monitor")
|
|
|
|
// Resolve persistence independently of the base-config lock.
|
|
tenantPersistence, err := mtm.persistence.GetPersistence(orgID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get persistence for org %s: %w", orgID, err)
|
|
}
|
|
var instancePersistence *config.ConfigPersistence
|
|
if orgID != "default" {
|
|
instancePersistence, err = mtm.persistence.GetPersistence("default")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get instance persistence for org %s: %w", orgID, err)
|
|
}
|
|
}
|
|
monitor, err := mtm.newTenantMonitor(orgID, tenantPersistence)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tenantPersistence.SetMetadataStores(
|
|
monitor.GuestMetadataStore(),
|
|
monitor.DockerMetadataStore(),
|
|
monitor.HostMetadataStore(),
|
|
)
|
|
|
|
// Set org ID for tenant isolation
|
|
// This enables tenant-scoped WebSocket broadcasts
|
|
monitor.SetOrgID(orgID)
|
|
if instancePersistence != nil {
|
|
monitor.SetInstanceAPITokenInventory(mtm.baseConfig, instancePersistence)
|
|
}
|
|
|
|
// Stamp this org's identity into webhook payloads so external receivers
|
|
// (PSA/ticketing bridges) can route by tenant. Resolved lazily so a
|
|
// display-name rename is picked up without restarting the monitor. The
|
|
// default org keeps the PULSE_TENANT_ID/PULSE_TENANT_NAME env defaults.
|
|
if nm := monitor.GetNotificationManager(); nm != nil && orgID != "default" {
|
|
persistence := mtm.persistence
|
|
nm.SetTenantIdentityResolver(func() (string, string) {
|
|
name := ""
|
|
if org, err := persistence.LoadOrganization(orgID); err == nil && org != nil {
|
|
name = org.DisplayName
|
|
}
|
|
return orgID, name
|
|
})
|
|
}
|
|
if mtm.recoveryMgr != nil {
|
|
monitor.SetRecoveryManager(mtm.recoveryMgr)
|
|
}
|
|
if mtm.initializer != nil {
|
|
mtm.initializer(monitor)
|
|
}
|
|
|
|
return monitor, nil
|
|
}
|
|
|
|
// newTenantMonitor protects the template copy (and default's canonical config)
|
|
// against actual settings writes. It releases configMu before any initializer
|
|
// or publication, so a held dependency callback cannot block a settings save.
|
|
func (mtm *MultiTenantMonitor) newTenantMonitor(orgID string, tenantPersistence *config.ConfigPersistence) (*Monitor, error) {
|
|
mtm.configMu.Lock()
|
|
defer mtm.configMu.Unlock()
|
|
// 1. Load Tenant Config
|
|
// The default org is the primary runtime and must retain the canonical
|
|
// configuration pointer owned by the server. Runtime auth mutations such as
|
|
// freshly minted agent tokens need to become visible to monitoring-backed
|
|
// diagnostics immediately. Non-default tenants remain isolated deep copies
|
|
// so their mutable state and credentials cannot alias the primary runtime.
|
|
tenantConfig := mtm.baseConfig
|
|
|
|
var err error
|
|
if orgID != "default" {
|
|
tenantConfig, err = loadTenantRuntimeConfig(mtm.baseConfig, tenantPersistence)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to load configuration for org %s: %w", orgID, err)
|
|
}
|
|
} else {
|
|
tenantConfig.PVEInstances = nil
|
|
tenantConfig.PBSInstances = nil
|
|
tenantConfig.PMGInstances = nil
|
|
tenantConfig.DataPath = tenantPersistence.GetConfigDir()
|
|
if nodes, loadErr := tenantPersistence.LoadNodesConfig(); loadErr != nil {
|
|
log.Warn().Err(loadErr).Str("org_id", orgID).Msg("failed to load tenant nodes config, starting with empty config")
|
|
} else if nodes != nil {
|
|
tenantConfig.PVEInstances = nodes.PVEInstances
|
|
tenantConfig.PBSInstances = nodes.PBSInstances
|
|
tenantConfig.PMGInstances = nodes.PMGInstances
|
|
}
|
|
}
|
|
|
|
monitor, err := New(tenantConfig)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create monitor for org %s: %w", orgID, err)
|
|
}
|
|
return monitor, nil
|
|
}
|
|
|
|
// PeekMonitor returns the tenant monitor instance if it is already initialized.
|
|
// It does not create a new monitor.
|
|
func (mtm *MultiTenantMonitor) PeekMonitor(orgID string) (*Monitor, bool) {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
return nil, false
|
|
}
|
|
|
|
mtm.mu.RLock()
|
|
defer mtm.mu.RUnlock()
|
|
if _, deleting := mtm.tenantDeleting[orgID]; mtm.stopped || deleting {
|
|
return nil, false
|
|
}
|
|
monitor, exists := mtm.monitors[orgID]
|
|
return monitor, exists
|
|
}
|
|
|
|
// Stop permanently closes admission and stops all tenant monitors. A new
|
|
// manager, rather than a lookup on this retired one, owns replacement runtimes.
|
|
func (mtm *MultiTenantMonitor) Stop() {
|
|
// Process shutdown remains best effort and logs each incomplete tenant.
|
|
// A reload must additionally check stop's result before replacing this
|
|
// manager: retained runtimes still own their saved state until drained.
|
|
_ = mtm.stop()
|
|
}
|
|
|
|
func (mtm *MultiTenantMonitor) stop() error {
|
|
log.Info().Msg("stopping MultiTenantMonitor and all tenant instances")
|
|
|
|
mtm.mu.Lock()
|
|
mtm.stopped = true
|
|
if mtm.globalCancel != nil {
|
|
mtm.globalCancel()
|
|
}
|
|
orgIDs := make([]string, 0, len(mtm.monitors)+len(mtm.tenantDone))
|
|
for orgID := range mtm.monitors {
|
|
orgIDs = append(orgIDs, orgID)
|
|
}
|
|
for orgID := range mtm.tenantDone {
|
|
if _, exists := mtm.monitors[orgID]; !exists {
|
|
orgIDs = append(orgIDs, orgID)
|
|
}
|
|
}
|
|
mtm.mu.Unlock()
|
|
var incomplete []error
|
|
for _, orgID := range orgIDs {
|
|
if err := mtm.removeTenant(orgID, false); err != nil {
|
|
log.Error().Err(err).Str("org_id", orgID).Msg("tenant shutdown incomplete; retaining runtime ownership and data")
|
|
incomplete = append(incomplete, err)
|
|
}
|
|
}
|
|
return errors.Join(incomplete...)
|
|
}
|
|
|
|
// RemoveTenant stops and removes a specific tenant's monitor.
|
|
// Useful for offboarding or manual reloading.
|
|
func (mtm *MultiTenantMonitor) RemoveTenant(orgID string) {
|
|
if err := mtm.removeTenant(orgID, false); err != nil {
|
|
log.Error().Err(err).Str("org_id", orgID).Msg("tenant removal incomplete; retaining runtime ownership and data")
|
|
}
|
|
}
|
|
|
|
// BeginTenantDeletion prevents lazy monitor initialization while a tenant's
|
|
// persistence is being removed. Call FinishTenantDeletion after the
|
|
// persistence operation completes. An incomplete shutdown retains its guard.
|
|
func (mtm *MultiTenantMonitor) BeginTenantDeletion(orgID string) error {
|
|
return mtm.removeTenant(orgID, true)
|
|
}
|
|
|
|
// FinishTenantDeletion releases the temporary lifecycle guard installed by
|
|
// BeginTenantDeletion. Once persistence has been removed, GetMonitor remains
|
|
// unable to recreate the tenant because the organization no longer exists.
|
|
func (mtm *MultiTenantMonitor) FinishTenantDeletion(orgID string) {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
return
|
|
}
|
|
|
|
mtm.mu.Lock()
|
|
// An incomplete removal still owns a runtime or writer. Do not release
|
|
// its guard merely because an offboarding caller ran deferred cleanup.
|
|
_, retained := mtm.monitors[orgID]
|
|
_, initializingOrRunning := mtm.tenantDone[orgID]
|
|
if !retained && !initializingOrRunning {
|
|
delete(mtm.tenantDeleting, orgID)
|
|
}
|
|
mtm.mu.Unlock()
|
|
}
|
|
|
|
func (mtm *MultiTenantMonitor) removeTenant(orgID string, deleting bool) error {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
return nil
|
|
}
|
|
|
|
mtm.mu.Lock()
|
|
if mtm.tenantDeleting == nil {
|
|
mtm.tenantDeleting = make(map[string]struct{})
|
|
}
|
|
if mtm.tenantStopping == nil {
|
|
mtm.tenantStopping = make(map[string]struct{})
|
|
}
|
|
if _, stopping := mtm.tenantStopping[orgID]; stopping {
|
|
mtm.mu.Unlock()
|
|
return fmt.Errorf("organization %q shutdown is already in progress", orgID)
|
|
}
|
|
mtm.tenantDeleting[orgID] = struct{}{}
|
|
mtm.tenantStopping[orgID] = struct{}{}
|
|
cancel := mtm.tenantCancel[orgID]
|
|
done := mtm.tenantDone[orgID]
|
|
mtm.mu.Unlock()
|
|
defer func() {
|
|
mtm.mu.Lock()
|
|
delete(mtm.tenantStopping, orgID)
|
|
mtm.mu.Unlock()
|
|
}()
|
|
|
|
log.Info().Str("org_id", orgID).Msg("stopping and removing tenant monitor")
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
shutdownTimeout := tenantMonitorShutdownTimeout
|
|
if deleting {
|
|
shutdownTimeout = tenantDeletionShutdownTimeout
|
|
}
|
|
if !waitForTenantMonitorShutdown(orgID, done, shutdownTimeout) {
|
|
return fmt.Errorf("organization %q monitoring loop has not stopped", orgID)
|
|
}
|
|
// A constructor can finish while the remover is waiting. Read the owned
|
|
// monitor only after its lifetime completes, not before the wait.
|
|
mtm.mu.RLock()
|
|
monitor := mtm.monitors[orgID]
|
|
mtm.mu.RUnlock()
|
|
if monitor != nil {
|
|
if err := monitor.stop(); err != nil {
|
|
return fmt.Errorf("organization %q guest metadata shutdown incomplete: %w", orgID, err)
|
|
}
|
|
}
|
|
|
|
mtm.mu.Lock()
|
|
delete(mtm.monitors, orgID)
|
|
delete(mtm.tenantCancel, orgID)
|
|
delete(mtm.tenantDone, orgID)
|
|
if !deleting {
|
|
delete(mtm.tenantDeleting, orgID)
|
|
}
|
|
mtm.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
func waitForTenantMonitorShutdown(orgID string, done <-chan struct{}, timeout time.Duration) bool {
|
|
if done == nil {
|
|
return true
|
|
}
|
|
|
|
timer := time.NewTimer(timeout)
|
|
defer timer.Stop()
|
|
|
|
select {
|
|
case <-done:
|
|
return true
|
|
case <-timer.C:
|
|
logger := log.Warn().Dur("timeout", timeout)
|
|
if orgID != "" {
|
|
logger = logger.Str("org_id", orgID)
|
|
}
|
|
logger.Msg("timed out waiting for tenant monitor loop to exit")
|
|
return false
|
|
}
|
|
}
|
|
|
|
// OrgExists checks if an organization exists (directory exists) without creating it.
|
|
func (mtm *MultiTenantMonitor) OrgExists(orgID string) bool {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
return false
|
|
}
|
|
|
|
if mtm.persistence == nil {
|
|
return false
|
|
}
|
|
return mtm.persistence.OrgExists(orgID)
|
|
}
|