Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

17.7 KB
Raw Blame
package updates

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/mockmode"
)

// Pre-compiled regexes for performance (avoid recompilation on each call)
var (
	semverRe           = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+(.+))?$`)
	rcNumRe            = regexp.MustCompile(`rc\.?(\d+)`)
	publishedPreviewRe = regexp.MustCompile(`^(alpha|beta|rc)\.([1-9][0-9]*)$`)
	gitHashRe          = regexp.MustCompile(`^([0-9a-fA-F]{7,})(-dirty)?$`)
)

// BuildVersion is the version string injected at build time via ldflags.
// Set this from main before starting the server so GetCurrentVersion()
// doesn't have to fall back to disk reads or the hardcoded default.
var BuildVersion string

// Version represents a semantic version
type Version struct {
	Major      int
	Minor      int
	Patch      int
	Prerelease string
	Build      string
}

func (v *Version) IsRCPrerelease() bool {
	if v == nil {
		return false
	}
	return rcNumRe.MatchString(strings.ToLower(strings.TrimSpace(v.Prerelease)))
}

// PreviewStage returns the governed published prerelease stage. The update
// channel retains the historical "rc" wire value for compatibility, but it
// carries alpha, beta, and release-candidate builds.
func (v *Version) PreviewStage() string {
	if v == nil {
		return ""
	}
	matches := publishedPreviewRe.FindStringSubmatch(strings.ToLower(strings.TrimSpace(v.Prerelease)))
	if len(matches) == 0 {
		return ""
	}
	return matches[1]
}

func (v *Version) IsPreviewPrerelease() bool {
	return v.PreviewStage() != ""
}

func (v *Version) IsPublishedReleaseAssetVersion() bool {
	if v == nil {
		return false
	}
	if v.Build != "" {
		return false
	}
	return v.Prerelease == "" || v.IsPreviewPrerelease()
}

// VersionInfo contains detailed version information
type VersionInfo struct {
	Version        string `json:"version"`
	Build          string `json:"build"`
	Runtime        string `json:"runtime"`
	Channel        string `json:"channel,omitempty"`
	IsDocker       bool   `json:"isDocker"`
	IsSourceBuild  bool   `json:"isSourceBuild"`
	IsDevelopment  bool   `json:"isDevelopment"`
	DeploymentType string `json:"deploymentType"`
}

// UsageDataVersionIdentity is the canonical release/build identity that usage-data
// surfaces should use when distinguishing published releases from development or
// manual branch builds.
type UsageDataVersionIdentity struct {
	Version            string `json:"version"`
	RawVersion         string `json:"version_raw,omitempty"`
	Channel            string `json:"version_channel"`
	Build              string `json:"version_build,omitempty"`
	IsDevelopment      bool   `json:"version_is_development"`
	IsPublishedRelease bool   `json:"version_is_published_release"`
}

// ParseVersion parses a version string into a Version struct
func ParseVersion(versionStr string) (*Version, error) {
	// Remove 'v' prefix if present
	versionStr = strings.TrimPrefix(versionStr, "v")

	matches := semverRe.FindStringSubmatch(versionStr)

	if len(matches) == 0 {
		return nil, fmt.Errorf("invalid version format: %s", versionStr)
	}

	major, _ := strconv.Atoi(matches[1])
	minor, _ := strconv.Atoi(matches[2])
	patch, _ := strconv.Atoi(matches[3])

	return &Version{
		Major:      major,
		Minor:      minor,
		Patch:      patch,
		Prerelease: matches[4],
		Build:      matches[5],
	}, nil
}

// String returns the string representation of the version
func (v *Version) String() string {
	version := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
	if v.Prerelease != "" {
		version += "-" + v.Prerelease
	}
	if v.Build != "" {
		version += "+" + v.Build
	}
	return version
}

// Compare compares two versions
// Returns:
//
//	-1 if v < other
//	 0 if v == other
//	 1 if v > other
func (v *Version) Compare(other *Version) int {
	if v.Major != other.Major {
		return compareInts(v.Major, other.Major)
	}
	if v.Minor != other.Minor {
		return compareInts(v.Minor, other.Minor)
	}
	if v.Patch != other.Patch {
		return compareInts(v.Patch, other.Patch)
	}

	// Handle prerelease versions
	if v.Prerelease == "" && other.Prerelease != "" {
		return 1 // v is release, other is prerelease
	}
	if v.Prerelease != "" && other.Prerelease == "" {
		return -1 // v is prerelease, other is release
	}
	if v.Prerelease != other.Prerelease {
		return comparePrerelease(v.Prerelease, other.Prerelease)
	}

	return 0
}

func comparePrerelease(left string, right string) int {
	leftIdentifiers := strings.Split(left, ".")
	rightIdentifiers := strings.Split(right, ".")
	limit := min(len(leftIdentifiers), len(rightIdentifiers))

	for index := 0; index < limit; index++ {
		leftIdentifier := leftIdentifiers[index]
		rightIdentifier := rightIdentifiers[index]
		leftNumber, leftNumeric := numericPrereleaseIdentifier(leftIdentifier)
		rightNumber, rightNumeric := numericPrereleaseIdentifier(rightIdentifier)

		switch {
		case leftNumeric && rightNumeric:
			if comparison := compareNumericPrereleaseIdentifiers(leftNumber, rightNumber); comparison != 0 {
				return comparison
			}
		case leftNumeric:
			return -1
		case rightNumeric:
			return 1
		default:
			if comparison := strings.Compare(leftIdentifier, rightIdentifier); comparison != 0 {
				return comparison
			}
		}
	}

	return compareInts(len(leftIdentifiers), len(rightIdentifiers))
}

func numericPrereleaseIdentifier(identifier string) (string, bool) {
	if identifier == "" {
		return "", false
	}
	for _, character := range identifier {
		if character < '0' || character > '9' {
			return "", false
		}
	}
	normalized := strings.TrimLeft(identifier, "0")
	if normalized == "" {
		normalized = "0"
	}
	return normalized, true
}

func compareNumericPrereleaseIdentifiers(left string, right string) int {
	if len(left) != len(right) {
		return compareInts(len(left), len(right))
	}
	return strings.Compare(left, right)
}

// IsNewerThan returns true if v is newer than other
func (v *Version) IsNewerThan(other *Version) bool {
	return v.Compare(other) > 0
}

// IsPrerelease returns true if this is a prerelease version
func (v *Version) IsPrerelease() bool {
	return v.Prerelease != ""
}

// GetCurrentVersion gets the current running version
func GetCurrentVersion() (*VersionInfo, error) {
	allowDockerUpdates := dockerUpdatesAllowed()
	versionFileRaw, hasVersionFile := readCurrentVersionFile()

	buildInfo := func(raw string, build string, isDev bool) *VersionInfo {
		normalized := normalizeVersionString(raw)
		identity := DescribeUsageDataVersion(normalized)
		isDev = isDev || identity.IsDevelopment
		sourceBuild := isSourceBuildEnvironment() || isDev
		channel := detectChannelFromVersion(normalized)
		if sourceBuild {
			// Source builds have no published release channel. Keep their
			// exact version while excluding them from release update flows.
			channel = ""
			build = "source"
			if isDev {
				build = "development"
			}
		}
		info := &VersionInfo{
			Version:        normalized,
			Build:          build,
			Runtime:        "go",
			Channel:        channel,
			IsDevelopment:  isDev,
			IsDocker:       isDockerEnvironment(),
			IsSourceBuild:  sourceBuild,
			DeploymentType: GetDeploymentType(),
		}

		if allowDockerUpdates && info.IsDocker {
			info.IsDocker = false
		}

		return info
	}

	// Build-time version injected via ldflags takes highest priority.
	// This covers all release binary deployments regardless of working directory.
	if BuildVersion != "" && BuildVersion != "dev" {
		return buildInfo(BuildVersion, "release", false), nil
	}

	if gitVersion, err := getGitVersion(); err == nil && gitVersion != "" {
		return buildInfo(normalizeDevelopmentVersion(gitVersion, versionFileRaw), "development", true), nil
	}

	// Try to read from VERSION file first (release builds)
	if hasVersionFile {
		return buildInfo(versionFileRaw, "release", false), nil
	}

	// Fall back to git (development builds)
	gitVersion, err := getGitVersion()
	if err == nil && gitVersion != "" {
		return buildInfo(gitVersion, "development", true), nil
	}

	// Final fallback
	return buildInfo("4.26.0", "release", false), nil
}

// DescribeUsageDataVersion normalizes a reported version string into a stable
// release/build identity for telemetry and operator-facing usage-data reports.
func DescribeUsageDataVersion(raw string) UsageDataVersionIdentity {
	trimmed := strings.TrimSpace(raw)
	normalized := normalizeVersionString(trimmed)
	identity := UsageDataVersionIdentity{
		Version: normalized,
		Channel: "unknown",
	}
	if trimmed != "" && trimmed != normalized {
		identity.RawVersion = trimmed
	}

	parsed, err := ParseVersion(normalized)
	if err != nil {
		return identity
	}

	identity.Build = parsed.Build
	identity.Channel = usageDataVersionChannel(parsed)
	identity.IsDevelopment = identity.Channel == "dev"
	// A development build is never a published release. Without this the 0.0.0
	// sentinel "0.0.0-rc.1" would satisfy IsPublishedReleaseAssetVersion and
	// report both flags at once, which no real install can be.
	identity.IsPublishedRelease = !identity.IsDevelopment && parsed.IsPublishedReleaseAssetVersion()
	return identity
}

// normalizeVersionString ensures any version string can be parsed as semantic version.
// Release builds are returned unchanged, while git describe strings and branch names are
// converted to a safe 0.0.0-based prerelease format.
func normalizeVersionString(version string) string {
	version = strings.TrimSpace(version)
	version = strings.TrimPrefix(version, "v")

	if version == "" {
		return "0.0.0-dev"
	}

	if normalized, ok := normalizeGitDescribeVersion(version); ok {
		return normalized
	}

	if _, err := ParseVersion(version); err == nil {
		return version
	}

	return fmt.Sprintf("0.0.0-%s", sanitizePrereleaseIdentifier(version))
}

func normalizeDevelopmentVersion(gitVersion string, versionBase string) string {
	normalizedGit := normalizeVersionString(gitVersion)
	normalizedBase := normalizeVersionString(versionBase)
	if versionBase == "" {
		return normalizedGit
	}
	if _, err := ParseVersion(normalizedBase); err != nil {
		return normalizedGit
	}

	if buildMetadata, ok := gitBuildMetadata(gitVersion); ok {
		if strings.Contains(normalizedBase, "+") {
			return normalizedBase + "." + buildMetadata
		}
		return normalizedBase + "+" + buildMetadata
	}

	return normalizedBase
}

func gitBuildMetadata(version string) (string, bool) {
	if normalized, ok := normalizeGitDescribeVersion(version); ok {
		if plus := strings.Index(normalized, "+"); plus >= 0 && plus < len(normalized)-1 {
			return normalized[plus+1:], true
		}
	}

	matches := gitHashRe.FindStringSubmatch(strings.TrimSpace(version))
	if matches == nil {
		return "", false
	}

	build := "git.0.g" + strings.ToLower(matches[1])
	if matches[2] != "" {
		build += ".dirty"
	}
	return build, true
}

var gitDescribeRegex = regexp.MustCompile(`^(\d+\.\d+\.\d+(?:-[0-9A-Za-z\.-]+)?)-(\d+)-g([0-9a-fA-F]+)(-dirty)?$`)

func normalizeGitDescribeVersion(version string) (string, bool) {
	version = strings.TrimSpace(strings.TrimPrefix(version, "v"))
	matches := gitDescribeRegex.FindStringSubmatch(version)
	if matches == nil {
		return "", false
	}

	base := matches[1]
	if _, err := ParseVersion(base); err != nil {
		return "", false
	}

	build := fmt.Sprintf("git.%s.g%s", matches[2], strings.ToLower(matches[3]))
	if matches[4] != "" {
		build += ".dirty"
	}

	return fmt.Sprintf("%s+%s", base, build), true
}

func sanitizePrereleaseIdentifier(raw string) string {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return "dev"
	}

	var b strings.Builder
	lastSep := false

	for _, r := range raw {
		switch {
		case r >= '0' && r <= '9',
			r >= 'A' && r <= 'Z',
			r >= 'a' && r <= 'z':
			b.WriteRune(r)
			lastSep = false
		case r == '-' || r == '.':
			if lastSep {
				continue
			}
			b.WriteRune(r)
			lastSep = true
		default:
			if !lastSep {
				b.WriteRune('-')
				lastSep = true
			}
		}
	}

	clean := strings.Trim(b.String(), "-.")
	if clean == "" {
		return "dev"
	}
	return strings.ToLower(clean)
}

func detectChannelFromVersion(version string) string {
	trimmed := strings.TrimSpace(version)
	if parsed, err := ParseVersion(trimmed); err == nil {
		if parsed.IsPreviewPrerelease() {
			return "rc"
		}
		return "stable"
	}
	return "stable"
}

// developmentSentinelVersion reports whether a version carries the 0.0.0
// sentinel normalizeVersionString assigns to any build string it cannot parse
// as a release version: a branch name, an ad-hoc test or qualification label,
// or an empty VERSION file. Pulse never publishes a 0.0.0 release, so such a
// build is a development build whatever its prerelease text happens to spell,
// and the check has to precede the prerelease classification rather than fall
// through to it.
func developmentSentinelVersion(version *Version) bool {
	return version != nil && version.Major == 0 && version.Minor == 0 && version.Patch == 0
}

func usageDataVersionChannel(version *Version) string {
	if version == nil {
		return "unknown"
	}
	switch {
	case version.Build != "":
		return "dev"
	case developmentSentinelVersion(version):
		return "dev"
	case version.IsPreviewPrerelease():
		return version.PreviewStage()
	case version.Prerelease == "":
		return "stable"
	case strings.EqualFold(version.Prerelease, "dev"), strings.HasPrefix(strings.ToLower(version.Prerelease), "dev."):
		return "dev"
	default:
		return "prerelease"
	}
}

func readCurrentVersionFile() (string, bool) {
	versionPaths := []string{
		"VERSION",
		"/opt/pulse/VERSION",
		filepath.Join(filepath.Dir(os.Args[0]), "VERSION"),
	}

	for _, path := range versionPaths {
		versionBytes, err := os.ReadFile(path)
		if err == nil {
			if raw := strings.TrimSpace(string(versionBytes)); raw != "" {
				return raw, true
			}
		}
	}

	return "", false
}

// getGitVersion gets version information from git
func getGitVersion() (string, error) {
	// Get the latest tag
	cmd := exec.Command("git", "describe", "--tags", "--always", "--dirty")
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}

	version := strings.TrimSpace(string(output))
	if version == "" {
		return "", fmt.Errorf("no version found")
	}

	return version, nil
}

// isDockerEnvironment checks if running in Docker
func isDockerEnvironment() bool {
	if dockerUpdatesAllowed() {
		return false
	}

	// Check for Docker-specific files
	if fileExists("/.dockerenv") {
		return true
	}

	// Check cgroup for Docker - with timeout to prevent hanging
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	cmd := exec.CommandContext(ctx, "cat", "/proc/1/cgroup")
	data, err := cmd.Output()
	if err == nil && strings.Contains(string(data), "docker") {
		return true
	}

	return false
}

// isSourceBuildEnvironment checks if running from a source build
func isSourceBuildEnvironment() bool {
	markerPaths := []string{
		"BUILD_FROM_SOURCE",
		"/opt/pulse/BUILD_FROM_SOURCE",
		filepath.Join(filepath.Dir(os.Args[0]), "BUILD_FROM_SOURCE"),
	}

	for _, path := range markerPaths {
		if fileExists(path) {
			return true
		}
	}

	return false
}

// fileExists checks if a file exists
func fileExists(path string) bool {
	// Use os.Stat instead of exec.Command for better performance and reliability
	_, err := os.Stat(path)
	return err == nil
}

// GetDeploymentType determines how Pulse was deployed
func GetDeploymentType() string {
	if mockmode.IsEnabled() {
		return "mock"
	}

	// Check if running in Docker
	if isDockerEnvironment() {
		return "docker"
	}

	if isSourceBuildEnvironment() {
		return "source"
	}

	// Check for ProxmoxVE LXC installation (has update command)
	if data, err := os.ReadFile("/bin/update"); err == nil && isProxmoxVEUpdateHelper(string(data)) {
		return "proxmoxve"
	}

	// Check for systemd service to determine installation type
	if fileExists("/etc/systemd/system/pulse-backend.service") {
		// Read file directly instead of using exec.Command
		data, err := os.ReadFile("/etc/systemd/system/pulse-backend.service")
		if err == nil {
			content := string(data)
			if strings.Contains(content, "User=pulse") && strings.Contains(content, "/opt/pulse/bin/pulse") {
				return "proxmoxve"
			}
		}
		return "systemd"
	}

	if fileExists("/etc/systemd/system/pulse.service") {
		return "systemd"
	}

	// Development or manual run
	if strings.Contains(os.Args[0], "go-build") || fileExists(".git") {
		return "development"
	}

	return "manual"
}

// communityScriptsPulseEntrypoint matches the community-scripts update
// bootstrap generated for the Pulse LXC. Since September 2026 that bootstrap
// names the app only through this export; it no longer contains ct/pulse.sh.
var communityScriptsPulseEntrypoint = regexp.MustCompile(`(?m)^export UPDATE_SCRIPT_NAME="pulse"\s*$`)

// isProxmoxVEUpdateHelper reports whether /bin/update classifies this install
// as proxmoxve: the Pulse installer's helper (which native hosts also carry),
// or the community-scripts updater in its old direct-pull or bootstrap form.
func isProxmoxVEUpdateHelper(content string) bool {
	return strings.Contains(content, "pulse.sh") ||
		strings.Contains(content, "install.sh") ||
		communityScriptsPulseEntrypoint.MatchString(content)
}

// dockerUpdatesAllowed returns true when Docker environments should expose update functionality.
func dockerUpdatesAllowed() bool {
	if envBool("PULSE_ALLOW_DOCKER_UPDATES") {
		return true
	}
	return mockmode.IsEnabled()
}

func envBool(key string) bool {
	value := strings.TrimSpace(strings.ToLower(os.Getenv(key)))
	switch value {
	case "1", "true", "yes", "on":
		return true
	default:
		return false
	}
}

// compareInts compares two integers
func compareInts(a, b int) int {
	if a < b {
		return -1
	}
	if a > b {
		return 1
	}
	return 0
}

// extractRCNumber extracts the RC number from a prerelease string like "rc.9" or "rc9"
func extractRCNumber(prerelease string) int {
	matches := rcNumRe.FindStringSubmatch(strings.ToLower(prerelease))
	if len(matches) > 1 {
		num, err := strconv.Atoi(matches[1])
		if err == nil {
			return num
		}
	}
	return -1
}