|
| 1 | +// Package updater provides functionality to check for and apply updates. |
| 2 | +package updater |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "log/slog" |
| 10 | + "net/http" |
| 11 | + "os" |
| 12 | + "os/exec" |
| 13 | + "strings" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/Masterminds/semver/v3" |
| 17 | +) |
| 18 | + |
| 19 | +// Service handles version checking and updates. |
| 20 | +type Service struct { |
| 21 | + currentVersion string |
| 22 | + githubRepo string |
| 23 | + logger *slog.Logger |
| 24 | + httpClient *http.Client |
| 25 | +} |
| 26 | + |
| 27 | +// NewService creates a new updater service. |
| 28 | +func NewService(currentVersion, githubRepo string, logger *slog.Logger) *Service { |
| 29 | + return &Service{ |
| 30 | + currentVersion: currentVersion, |
| 31 | + githubRepo: githubRepo, |
| 32 | + logger: logger, |
| 33 | + httpClient: &http.Client{ |
| 34 | + Timeout: 10 * time.Second, |
| 35 | + }, |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +// UpdateInfo contains information about available updates. |
| 40 | +type UpdateInfo struct { |
| 41 | + CurrentVersion string `json:"current_version"` |
| 42 | + LatestVersion string `json:"latest_version"` |
| 43 | + UpdateAvailable bool `json:"update_available"` |
| 44 | + ReleaseURL string `json:"release_url,omitempty"` |
| 45 | + ReleaseNotes string `json:"release_notes,omitempty"` |
| 46 | + PublishedAt string `json:"published_at,omitempty"` |
| 47 | +} |
| 48 | + |
| 49 | +// GitHubRelease represents a GitHub release from the API. |
| 50 | +type GitHubRelease struct { |
| 51 | + TagName string `json:"tag_name"` |
| 52 | + Name string `json:"name"` |
| 53 | + Body string `json:"body"` |
| 54 | + HTMLURL string `json:"html_url"` |
| 55 | + PublishedAt time.Time `json:"published_at"` |
| 56 | + Prerelease bool `json:"prerelease"` |
| 57 | + Draft bool `json:"draft"` |
| 58 | +} |
| 59 | + |
| 60 | +// CheckForUpdates queries GitHub for the latest release and compares with current version. |
| 61 | +func (s *Service) CheckForUpdates(ctx context.Context) (*UpdateInfo, error) { |
| 62 | + info := &UpdateInfo{ |
| 63 | + CurrentVersion: s.currentVersion, |
| 64 | + } |
| 65 | + |
| 66 | + // Skip check if version is "dev" or empty |
| 67 | + if s.currentVersion == "" || s.currentVersion == "dev" { |
| 68 | + s.logger.Debug("skipping update check for dev version") |
| 69 | + return info, nil |
| 70 | + } |
| 71 | + |
| 72 | + // Fetch latest release from GitHub |
| 73 | + url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", s.githubRepo) |
| 74 | + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 75 | + if err != nil { |
| 76 | + return info, fmt.Errorf("failed to create request: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + req.Header.Set("Accept", "application/vnd.github.v3+json") |
| 80 | + req.Header.Set("User-Agent", "Narvana-Control-Plane") |
| 81 | + |
| 82 | + resp, err := s.httpClient.Do(req) |
| 83 | + if err != nil { |
| 84 | + return info, fmt.Errorf("failed to fetch releases: %w", err) |
| 85 | + } |
| 86 | + defer resp.Body.Close() |
| 87 | + |
| 88 | + if resp.StatusCode != http.StatusOK { |
| 89 | + body, _ := io.ReadAll(resp.Body) |
| 90 | + return info, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, string(body)) |
| 91 | + } |
| 92 | + |
| 93 | + var release GitHubRelease |
| 94 | + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { |
| 95 | + return info, fmt.Errorf("failed to decode release: %w", err) |
| 96 | + } |
| 97 | + |
| 98 | + // Skip drafts and prereleases for stable version checks |
| 99 | + if release.Draft || release.Prerelease { |
| 100 | + s.logger.Debug("latest release is draft or prerelease, skipping", "tag", release.TagName) |
| 101 | + return info, nil |
| 102 | + } |
| 103 | + |
| 104 | + info.LatestVersion = release.TagName |
| 105 | + info.ReleaseURL = release.HTMLURL |
| 106 | + info.ReleaseNotes = release.Body |
| 107 | + info.PublishedAt = release.PublishedAt.Format(time.RFC3339) |
| 108 | + |
| 109 | + // Compare versions |
| 110 | + updateAvailable, err := s.isNewerVersion(release.TagName) |
| 111 | + if err != nil { |
| 112 | + s.logger.Warn("failed to compare versions", "error", err) |
| 113 | + return info, nil // Don't fail, just return what we have |
| 114 | + } |
| 115 | + |
| 116 | + info.UpdateAvailable = updateAvailable |
| 117 | + return info, nil |
| 118 | +} |
| 119 | + |
| 120 | +// isNewerVersion compares the latest version with current version. |
| 121 | +func (s *Service) isNewerVersion(latestVersion string) (bool, error) { |
| 122 | + // Normalize version strings (remove 'v' prefix if present) |
| 123 | + current := strings.TrimPrefix(s.currentVersion, "v") |
| 124 | + latest := strings.TrimPrefix(latestVersion, "v") |
| 125 | + |
| 126 | + currentVer, err := semver.NewVersion(current) |
| 127 | + if err != nil { |
| 128 | + return false, fmt.Errorf("invalid current version %q: %w", current, err) |
| 129 | + } |
| 130 | + |
| 131 | + latestVer, err := semver.NewVersion(latest) |
| 132 | + if err != nil { |
| 133 | + return false, fmt.Errorf("invalid latest version %q: %w", latest, err) |
| 134 | + } |
| 135 | + |
| 136 | + return latestVer.GreaterThan(currentVer), nil |
| 137 | +} |
| 138 | + |
| 139 | +// ApplyUpdate performs the update by pulling new container images and restarting services. |
| 140 | +// This is designed to work in containerized deployments using Podman/Docker Compose. |
| 141 | +func (s *Service) ApplyUpdate(ctx context.Context, version string) error { |
| 142 | + s.logger.Info("applying update", "version", version) |
| 143 | + |
| 144 | + // Determine deployment method |
| 145 | + deployMethod := s.detectDeploymentMethod() |
| 146 | + s.logger.Info("detected deployment method", "method", deployMethod) |
| 147 | + |
| 148 | + switch deployMethod { |
| 149 | + case "compose": |
| 150 | + return s.updateCompose(ctx, version) |
| 151 | + case "systemd": |
| 152 | + return s.updateSystemd(ctx, version) |
| 153 | + default: |
| 154 | + return fmt.Errorf("unsupported deployment method: %s", deployMethod) |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +// detectDeploymentMethod checks how Narvana is deployed. |
| 159 | +func (s *Service) detectDeploymentMethod() string { |
| 160 | + // Check if running in a container (presence of /.dockerenv or /run/.containerenv) |
| 161 | + if _, err := os.Stat("/.dockerenv"); err == nil { |
| 162 | + return "compose" |
| 163 | + } |
| 164 | + if _, err := os.Stat("/run/.containerenv"); err == nil { |
| 165 | + return "compose" |
| 166 | + } |
| 167 | + |
| 168 | + // Check for systemd service |
| 169 | + if _, err := exec.LookPath("systemctl"); err == nil { |
| 170 | + cmd := exec.Command("systemctl", "is-active", "narvana-api") |
| 171 | + if err := cmd.Run(); err == nil { |
| 172 | + return "systemd" |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + return "unknown" |
| 177 | +} |
| 178 | + |
| 179 | +// updateCompose updates a Docker/Podman Compose deployment. |
| 180 | +func (s *Service) updateCompose(ctx context.Context, version string) error { |
| 181 | + // In a containerized environment, we need to trigger an external update script |
| 182 | + // or communicate with the host system to restart the compose stack. |
| 183 | + |
| 184 | + // Set the desired version in the environment |
| 185 | + composeFile := os.Getenv("COMPOSE_FILE") |
| 186 | + if composeFile == "" { |
| 187 | + composeFile = "/app/compose.yaml" // Default location in container |
| 188 | + } |
| 189 | + |
| 190 | + // Write a flag file that the host can monitor to trigger updates |
| 191 | + updateFlagFile := "/var/lib/narvana/.update-requested" |
| 192 | + content := fmt.Sprintf("version=%s\ntimestamp=%s\n", version, time.Now().Format(time.RFC3339)) |
| 193 | + |
| 194 | + if err := os.WriteFile(updateFlagFile, []byte(content), 0644); err != nil { |
| 195 | + return fmt.Errorf("failed to write update flag: %w", err) |
| 196 | + } |
| 197 | + |
| 198 | + s.logger.Info("update flag written, waiting for external updater", "file", updateFlagFile, "version", version) |
| 199 | + |
| 200 | + // Note: The actual container restart must be done externally (by systemd, cron, or a watcher) |
| 201 | + // because the API can't restart its own container from inside. |
| 202 | + return nil |
| 203 | +} |
| 204 | + |
| 205 | +// updateSystemd updates a systemd-based deployment. |
| 206 | +func (s *Service) updateSystemd(ctx context.Context, version string) error { |
| 207 | + // For systemd deployments, we would: |
| 208 | + // 1. Download new binaries |
| 209 | + // 2. Restart services |
| 210 | + // This is more complex and depends on the installation method |
| 211 | + |
| 212 | + return fmt.Errorf("systemd-based updates not yet implemented") |
| 213 | +} |
| 214 | + |
0 commit comments