Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 42 additions & 35 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/jetkvm/kvm/internal/logging"
"github.com/jetkvm/kvm/internal/native"
"github.com/jetkvm/kvm/internal/network/types"
"github.com/jetkvm/kvm/internal/powersched"
"github.com/jetkvm/kvm/internal/sync"
"github.com/jetkvm/kvm/internal/usbgadget"

Expand Down Expand Up @@ -88,41 +89,42 @@ func (m *KeyboardMacro) Validate() error {
}

type Config struct {
CloudURL string `json:"cloud_url"`
UpdateAPIURL string `json:"update_api_url"`
CloudAppURL string `json:"cloud_app_url"`
CloudToken string `json:"cloud_token"`
TailscaleControlURL string `json:"tailscale_control_url,omitempty"`
GoogleIdentity string `json:"google_identity"`
JigglerEnabled bool `json:"jiggler_enabled"`
JigglerConfig *JigglerConfig `json:"jiggler_config"`
AutoUpdateEnabled bool `json:"auto_update_enabled"`
IncludePreRelease bool `json:"include_pre_release"`
HashedPassword string `json:"hashed_password"`
LocalAuthToken string `json:"local_auth_token"`
LocalAuthMode string `json:"localAuthMode"` //TODO: fix it with migration
LocalLoopbackOnly bool `json:"local_loopback_only"`
WakeOnLanDevices []WakeOnLanDevice `json:"wake_on_lan_devices"`
KeyboardMacros []KeyboardMacro `json:"keyboard_macros"`
KeyboardLayout string `json:"keyboard_layout"`
EdidString string `json:"hdmi_edid_string"`
ActiveExtension string `json:"active_extension"`
DisplayRotation string `json:"display_rotation"`
DisplayMaxBrightness int `json:"display_max_brightness"`
DisplayDimAfterSec int `json:"display_dim_after_sec"`
DisplayOffAfterSec int `json:"display_off_after_sec"`
TLSMode string `json:"tls_mode"` // options: "self-signed", "user-defined", ""
UsbConfig *usbgadget.Config `json:"usb_config"`
UsbDevices *usbgadget.Devices `json:"usb_devices"`
NetworkConfig *types.NetworkConfig `json:"network_config"`
DefaultLogLevel string `json:"default_log_level"`
VideoSleepAfterSec int `json:"video_sleep_after_sec"`
VideoQualityFactor float64 `json:"video_quality_factor"`
VideoCodecPreference string `json:"video_codec_preference"`
HideDisplayWhenIdle bool `json:"host_display_disable_when_idle"`
NativeMaxRestart uint `json:"native_max_restart_attempts"`
MqttConfig *MQTTConfig `json:"mqtt_config"`
AudioEnabled bool `json:"audio_enabled"`
CloudURL string `json:"cloud_url"`
UpdateAPIURL string `json:"update_api_url"`
CloudAppURL string `json:"cloud_app_url"`
CloudToken string `json:"cloud_token"`
TailscaleControlURL string `json:"tailscale_control_url,omitempty"`
GoogleIdentity string `json:"google_identity"`
JigglerEnabled bool `json:"jiggler_enabled"`
JigglerConfig *JigglerConfig `json:"jiggler_config"`
AutoUpdateEnabled bool `json:"auto_update_enabled"`
IncludePreRelease bool `json:"include_pre_release"`
HashedPassword string `json:"hashed_password"`
LocalAuthToken string `json:"local_auth_token"`
LocalAuthMode string `json:"localAuthMode"` //TODO: fix it with migration
LocalLoopbackOnly bool `json:"local_loopback_only"`
WakeOnLanDevices []WakeOnLanDevice `json:"wake_on_lan_devices"`
PowerSchedules []powersched.Schedule `json:"power_schedules"`

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose here it would make sense to use a shorter reference so that the diff becomes smaller.

KeyboardMacros []KeyboardMacro `json:"keyboard_macros"`
KeyboardLayout string `json:"keyboard_layout"`
EdidString string `json:"hdmi_edid_string"`
ActiveExtension string `json:"active_extension"`
DisplayRotation string `json:"display_rotation"`
DisplayMaxBrightness int `json:"display_max_brightness"`
DisplayDimAfterSec int `json:"display_dim_after_sec"`
DisplayOffAfterSec int `json:"display_off_after_sec"`
TLSMode string `json:"tls_mode"` // options: "self-signed", "user-defined", ""
UsbConfig *usbgadget.Config `json:"usb_config"`
UsbDevices *usbgadget.Devices `json:"usb_devices"`
NetworkConfig *types.NetworkConfig `json:"network_config"`
DefaultLogLevel string `json:"default_log_level"`
VideoSleepAfterSec int `json:"video_sleep_after_sec"`
VideoQualityFactor float64 `json:"video_quality_factor"`
VideoCodecPreference string `json:"video_codec_preference"`
HideDisplayWhenIdle bool `json:"host_display_disable_when_idle"`
NativeMaxRestart uint `json:"native_max_restart_attempts"`
MqttConfig *MQTTConfig `json:"mqtt_config"`
AudioEnabled bool `json:"audio_enabled"`
}

// GetUpdateAPIURL returns the update API URL
Expand Down Expand Up @@ -189,6 +191,7 @@ func getDefaultConfig() Config {
AutoUpdateEnabled: true, // Set a default value
ActiveExtension: "",
KeyboardMacros: []KeyboardMacro{},
PowerSchedules: []powersched.Schedule{},
DisplayRotation: "270",
KeyboardLayout: "en-US",
DisplayMaxBrightness: 64,
Expand Down Expand Up @@ -303,6 +306,10 @@ func LoadConfig() {
loadedConfig.MqttConfig = getDefaultConfig().MqttConfig
}

if loadedConfig.PowerSchedules == nil {
loadedConfig.PowerSchedules = []powersched.Schedule{}
}

// fixup old keyboard layout value
if loadedConfig.KeyboardLayout == "en_US" {
loadedConfig.KeyboardLayout = "en-US"
Expand Down
151 changes: 151 additions & 0 deletions internal/powersched/schedule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Package powersched describes recurring power actions for the attached host.
//
// It holds only the schedule model and its translation to a crontab, with no
// dependency on the device runtime, so the rules can be unit tested on any
// platform. Executing a schedule lives in the main kvm package.
package powersched

import (
"fmt"
"net"
"sort"
"strings"
"time"
_ "time/tzdata"
)

// Schedule methods.
const (
MethodWOL = "wol"
MethodATX = "atx"
)

// Schedule actions.
const (
ActionOn = "on"
ActionOff = "off"
ActionOffForce = "off-force"
)

// MaxSchedules limits how many schedules a device may store, mirroring the
// keyboard macro limits so a misbehaving client can't grow the config forever.
const MaxSchedules = 25

// Schedule describes a recurring power action on the attached host.
//
// The schedule is stored as a weekday set plus a wall-clock time in an IANA
// timezone rather than a raw crontab: the UI exposes a weekday/time picker, and
// keeping the structured form lets both ends render the schedule consistently.
type Schedule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Method string `json:"method"` // "wol" | "atx"
Action string `json:"action"` // "on" | "off" | "off-force"
Weekdays []int `json:"weekdays"` // 0=Sunday .. 6=Saturday
Hour int `json:"hour"` // 0-23
Minute int `json:"minute"` // 0-59
Timezone string `json:"timezone"` // IANA name, e.g. "Europe/Berlin"

// Wake-on-LAN only. The MAC is copied onto the schedule rather than
// referencing an entry in WakeOnLanDevices, so removing a saved device
// can't leave a schedule pointing at nothing.
MacAddress string `json:"macAddress,omitempty"`
BroadcastIP string `json:"broadcastIP,omitempty"`
}

// AllowedActions returns the actions that are valid for a given method.
func AllowedActions(method string) []string {
switch method {
case MethodWOL:
// A magic packet can only ever turn a host on.
return []string{ActionOn}
case MethodATX:
return []string{ActionOn, ActionOff, ActionOffForce}
default:
return nil
}
}

// Validate checks the schedule and normalises its weekday list. It returns an
// error describing the first problem found.
func (s *Schedule) Validate() error {
if strings.TrimSpace(s.Name) == "" {
return fmt.Errorf("schedule name cannot be empty")
}

actions := AllowedActions(s.Method)
if actions == nil {
return fmt.Errorf("invalid method: %s", s.Method)
}

valid := false
for _, a := range actions {
if s.Action == a {
valid = true
break
}
}
if !valid {
return fmt.Errorf("action %q is not valid for method %q", s.Action, s.Method)
}

if s.Method == MethodWOL {
if _, err := net.ParseMAC(s.MacAddress); err != nil {
return fmt.Errorf("invalid MAC address %q: %w", s.MacAddress, err)
}
if s.BroadcastIP != "" {
if ip := net.ParseIP(s.BroadcastIP); ip == nil || ip.To4() == nil {
return fmt.Errorf("invalid broadcast IP address: %s", s.BroadcastIP)
}
}
}

if s.Hour < 0 || s.Hour > 23 {
return fmt.Errorf("hour must be between 0 and 23, got %d", s.Hour)
}
if s.Minute < 0 || s.Minute > 59 {
return fmt.Errorf("minute must be between 0 and 59, got %d", s.Minute)
}

if len(s.Weekdays) == 0 {
return fmt.Errorf("at least one weekday must be selected")
}
seen := make(map[int]bool, len(s.Weekdays))
days := make([]int, 0, len(s.Weekdays))
for _, d := range s.Weekdays {
if d < 0 || d > 6 {
return fmt.Errorf("weekday must be between 0 and 6, got %d", d)
}
if seen[d] {
continue
}
seen[d] = true
days = append(days, d)
}
sort.Ints(days)
s.Weekdays = days

if s.Timezone != "" {
if _, err := time.LoadLocation(s.Timezone); err != nil {
return fmt.Errorf("invalid timezone %q: %w", s.Timezone, err)
}
}

return nil
}

// CronTab renders the schedule as a 6-field crontab, matching the
// with-seconds format the jiggler already uses.
func (s *Schedule) CronTab() string {
days := make([]string, 0, len(s.Weekdays))
for _, d := range s.Weekdays {
days = append(days, fmt.Sprintf("%d", d))
}

tab := fmt.Sprintf("0 %d %d * * %s", s.Minute, s.Hour, strings.Join(days, ","))
if s.Timezone != "" && s.Timezone != "UTC" {
tab = fmt.Sprintf("TZ=%s %s", s.Timezone, tab)
}
return tab
}
Loading
Loading