Help us shape the future of Go! Take the 2026 Go Developer Survey

sleepwake

package
v0.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package sleepwake provides automatic instance hibernation when the system sleeps

This package monitors system power events (sleep/wake) and automatically hibernates running Prism instances to prevent cost waste when users forget to stop instances before closing their laptop or shutting down.

Key Features: - Automatic hibernation on system sleep - Optional resume on wake - Configurable grace period and exclusions - Cross-platform support (macOS primary, Linux/Windows stubs)

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPlatformNotSupported indicates the current platform doesn't support sleep/wake monitoring
	ErrPlatformNotSupported = errors.New("sleep/wake monitoring not supported on this platform")
)

Errors

Functions

This section is empty.

Types

type Config

type Config struct {
	// Enabled controls whether sleep/wake monitoring is active
	Enabled bool `json:"enabled" yaml:"enabled"`

	// HibernateOnSleep controls whether instances are hibernated when system sleeps
	HibernateOnSleep bool `json:"hibernate_on_sleep" yaml:"hibernate_on_sleep"`

	// HibernationMode determines which instances get hibernated
	// - "idle_only": Only hibernate idle instances (default, safest)
	// - "all": Hibernate all except excluded (manual exclusion list)
	// - "manual_only": No automatic hibernation
	HibernationMode HibernationMode `json:"hibernation_mode" yaml:"hibernation_mode"`

	// IdleCheckTimeout is how long to wait when checking if an instance is idle
	// Default: 10 seconds
	IdleCheckTimeout time.Duration `json:"idle_check_timeout" yaml:"idle_check_timeout"`

	// ResumeOnWake controls whether instances are resumed when system wakes
	// Default: false (user must manually resume for control)
	ResumeOnWake bool `json:"resume_on_wake" yaml:"resume_on_wake"`

	// GracePeriod is the time to wait after sleep event before hibernating
	// This allows cancellation if system wakes quickly (e.g., lid closed briefly)
	// Default: 30 seconds
	GracePeriod time.Duration `json:"grace_period" yaml:"grace_period"`

	// ExcludedInstances is a list of instance names that should not be auto-hibernated
	// Useful for critical instances that should never auto-hibernate regardless of idle status
	ExcludedInstances []string `json:"excluded_instances" yaml:"excluded_instances"`

	// StateFilePath is where the sleep/wake state is persisted
	// Default: ~/.prism/sleep_wake_state.json
	StateFilePath string `json:"state_file_path" yaml:"state_file_path"`
}

Config represents sleep/wake monitor configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default sleep/wake configuration

type Event

type Event struct {
	Type      EventType `json:"type"`
	Timestamp time.Time `json:"timestamp"`
	Source    string    `json:"source"` // "iokit", "systemd", "win32", etc.
}

Event represents a power management event

type EventType

type EventType int

EventType represents the type of power event

const (
	// EventSleep indicates the system is about to sleep
	EventSleep EventType = iota
	// EventWake indicates the system has woken up
	EventWake
	// EventShutdown indicates the system is shutting down (future)
	EventShutdown
)

func (EventType) String

func (e EventType) String() string

type HibernationMode

type HibernationMode string

HibernationMode determines which instances are hibernated on sleep

const (
	// HibernationModeIdleOnly only hibernates instances detected as idle (RECOMMENDED DEFAULT)
	// Integrates with idle detection system to check CPU/memory/network/disk/GPU usage
	// Safe for long-running jobs - they won't be interrupted
	HibernationModeIdleOnly HibernationMode = "idle_only"

	// HibernationModeAll hibernates all instances except those in exclusion list
	// User must manually maintain exclusion list for active workloads
	// Higher risk of interrupting work
	HibernationModeAll HibernationMode = "all"

	// HibernationModeManualOnly disables automatic hibernation on sleep
	// User must manually hibernate instances via CLI
	// Most conservative option
	HibernationModeManualOnly HibernationMode = "manual_only"
)

type InstanceManager

type InstanceManager interface {
	// ListInstances returns the names of all running instances
	ListInstances(ctx context.Context) ([]string, error)

	// IsInstanceIdle checks if an instance is currently idle (low resource usage)
	// This integrates with the existing idle detection system
	IsInstanceIdle(ctx context.Context, instanceName string) (bool, error)

	// HibernateInstance hibernates a single instance
	HibernateInstance(ctx context.Context, instanceName string) error

	// ResumeInstance resumes a hibernated instance
	ResumeInstance(ctx context.Context, instanceName string) error
}

InstanceManager defines the interface for hibernating/resuming instances This will be implemented by the daemon's API client or daemon directly

type Monitor

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor monitors system power events and manages instance hibernation

func NewMonitor

func NewMonitor(config Config, mgr InstanceManager) (*Monitor, error)

NewMonitor creates a new sleep/wake monitor

func (*Monitor) GetStatus

func (m *Monitor) GetStatus() Status

GetStatus returns the current monitor status

func (*Monitor) Start

func (m *Monitor) Start() error

Start begins monitoring for sleep/wake events

func (*Monitor) Stop

func (m *Monitor) Stop() error

Stop stops the monitor

func (*Monitor) UpdateConfig

func (m *Monitor) UpdateConfig(config Config) error

UpdateConfig updates the monitor configuration

type State

type State struct {

	// LastSleepTime is when the system last went to sleep
	LastSleepTime time.Time `json:"last_sleep_time"`

	// LastWakeTime is when the system last woke up
	LastWakeTime time.Time `json:"last_wake_time"`

	// HibernatedInstances tracks which instances were auto-hibernated during sleep
	// Map of instance name -> hibernation time
	HibernatedInstances map[string]time.Time `json:"hibernated_instances"`

	// TotalSleepEvents is the count of sleep events processed
	TotalSleepEvents int64 `json:"total_sleep_events"`

	// TotalWakeEvents is the count of wake events processed
	TotalWakeEvents int64 `json:"total_wake_events"`

	// TotalHibernated is the count of instances hibernated due to sleep
	TotalHibernated int64 `json:"total_hibernated"`

	// TotalResumed is the count of instances resumed due to wake
	TotalResumed int64 `json:"total_resumed"`

	// StateFilePath is where this state is persisted
	StateFilePath string `json:"-"`
	// contains filtered or unexported fields
}

State represents the persisted sleep/wake state

func NewState

func NewState(filePath string) *State

NewState creates a new State with the given file path

func (*State) AddHibernatedInstance

func (s *State) AddHibernatedInstance(instanceName string)

AddHibernatedInstance records that an instance was hibernated

func (*State) ClearHibernatedInstances

func (s *State) ClearHibernatedInstances()

ClearHibernatedInstances removes all hibernated instances from tracking

func (*State) GetHibernatedInstances

func (s *State) GetHibernatedInstances() map[string]time.Time

GetHibernatedInstances returns a copy of the hibernated instances map

func (*State) GetStats

func (s *State) GetStats() Stats

GetStats returns a snapshot of the statistics

func (*State) Load

func (s *State) Load() error

Load loads the state from disk

func (*State) RecordResumed

func (s *State) RecordResumed()

RecordResumed increments the resumed counter

func (*State) RecordSleepEvent

func (s *State) RecordSleepEvent()

RecordSleepEvent records a sleep event

func (*State) RecordWakeEvent

func (s *State) RecordWakeEvent()

RecordWakeEvent records a wake event

func (*State) RemoveHibernatedInstance

func (s *State) RemoveHibernatedInstance(instanceName string)

RemoveHibernatedInstance removes an instance from the hibernated list

func (*State) Save

func (s *State) Save() error

Save persists the state to disk

type Stats

type Stats struct {
	LastSleepTime    time.Time `json:"last_sleep_time"`
	LastWakeTime     time.Time `json:"last_wake_time"`
	TotalSleepEvents int64     `json:"total_sleep_events"`
	TotalWakeEvents  int64     `json:"total_wake_events"`
	TotalHibernated  int64     `json:"total_hibernated"`
	TotalResumed     int64     `json:"total_resumed"`
	ActivelyTracked  int       `json:"actively_tracked"` // Currently hibernated instances
}

Stats represents sleep/wake monitoring statistics

type Status

type Status struct {
	Enabled             bool              `json:"enabled"`
	Running             bool              `json:"running"`
	Platform            string            `json:"platform"` // "darwin", "linux", "windows"
	HibernateOnSleep    bool              `json:"hibernate_on_sleep"`
	HibernationMode     HibernationMode   `json:"hibernation_mode"`   // "idle_only", "all", "manual_only"
	IdleCheckTimeout    string            `json:"idle_check_timeout"` // e.g., "10s"
	ResumeOnWake        bool              `json:"resume_on_wake"`
	GracePeriod         string            `json:"grace_period"`
	ExcludedInstances   []string          `json:"excluded_instances"`
	Stats               Stats             `json:"stats"`
	HibernatedInstances map[string]string `json:"hibernated_instances"` // name -> time string
}

Status represents the current status of the sleep/wake monitor

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL