-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathupdates.go
More file actions
258 lines (229 loc) · 7.12 KB
/
updates.go
File metadata and controls
258 lines (229 loc) · 7.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/fiatjaf/pyramid/global"
"github.com/fiatjaf/pyramid/groups"
"github.com/fiatjaf/pyramid/search"
)
// this is set at build time to something else based on git
var currentVersion string = "dev"
// this is set by the user and reset on restart
var customUpdateSource string
type releaseVersion struct {
name string
binaryURL string
}
var latestVersion releaseVersion
func fetchLatestVersion() {
var (
version releaseVersion
err error
)
if customUpdateSource == "" {
version, err = fetchLatestFromGitHub("fiatjaf/pyramid")
} else {
version, err = resolveCustomUpdateSource(customUpdateSource)
}
if err != nil {
log.Error().Err(err).Str("source", customUpdateSource).Msg("failed to fetch latest release")
return
}
latestVersion = version
log.Info().Str("version", latestVersion.name).Str("source", customUpdateSource).Msg("fetched latest version")
}
type githubRelease struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
Assets []struct {
Name string `json:"name"`
URL string `json:"browser_download_url"`
} `json:"assets"`
}
func fetchLatestFromGitHub(repo string) (releaseVersion, error) {
apiURL := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo)
release, err := fetchGitHubRelease(apiURL)
if err != nil {
return releaseVersion{}, err
}
return releaseToVersion(release)
}
func fetchReleaseByTag(repo, tag string) (releaseVersion, error) {
apiURL := fmt.Sprintf("https://api.github.com/repos/%s/releases/tags/%s", repo, tag)
release, err := fetchGitHubRelease(apiURL)
if err != nil {
return releaseVersion{}, err
}
return releaseToVersion(release)
}
func fetchGitHubRelease(apiURL string) (githubRelease, error) {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(apiURL)
if err != nil {
return githubRelease{}, fmt.Errorf("failed to fetch github release: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return githubRelease{}, fmt.Errorf("github api returned status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return githubRelease{}, fmt.Errorf("failed to read github api response: %w", err)
}
var release githubRelease
if err := json.Unmarshal(body, &release); err != nil {
return githubRelease{}, fmt.Errorf("failed to parse github api response: %w", err)
}
return release, nil
}
func releaseToVersion(release githubRelease) (releaseVersion, error) {
// determine architecture and find the corresponding binary asset
var binaryURL string
var expectedBinaryName string
switch runtime.GOARCH {
case "amd64":
expectedBinaryName = "pyramid-amd64"
case "arm64":
expectedBinaryName = "pyramid-arm64"
default:
return releaseVersion{}, fmt.Errorf("unsupported architecture %s", runtime.GOARCH)
}
for _, asset := range release.Assets {
if asset.Name == expectedBinaryName {
binaryURL = asset.URL
break
}
}
if binaryURL == "" {
return releaseVersion{}, fmt.Errorf("binary asset not found for %s", expectedBinaryName)
}
return releaseVersion{
name: release.TagName,
binaryURL: binaryURL,
}, nil
}
func resolveCustomUpdateSource(source string) (releaseVersion, error) {
u, err := url.Parse(source)
if err != nil {
return releaseVersion{}, fmt.Errorf("invalid update source url: %w", err)
}
host := strings.ToLower(u.Host)
switch host {
case "github.com", "www.github.com":
return resolveGitHubWebURL(u, source)
case "api.github.com":
release, err := fetchGitHubRelease(u.String())
if err != nil {
return releaseVersion{}, err
}
return releaseToVersion(release)
default:
name := path.Base(u.Path)
if name == "." || name == "/" || name == "" {
name = "custom"
}
return releaseVersion{name: name, binaryURL: source}, nil
}
}
func resolveGitHubWebURL(u *url.URL, raw string) (releaseVersion, error) {
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 2 {
return releaseVersion{}, fmt.Errorf("invalid github repository url")
}
repo := parts[0] + "/" + parts[1]
if len(parts) == 2 {
return fetchLatestFromGitHub(repo)
}
if len(parts) >= 3 && parts[2] == "releases" {
if len(parts) == 3 || parts[3] == "" || parts[3] == "latest" {
return fetchLatestFromGitHub(repo)
}
switch parts[3] {
case "tag":
if len(parts) >= 5 {
return fetchReleaseByTag(repo, parts[4])
}
case "download":
if len(parts) >= 5 {
return releaseVersion{name: parts[4], binaryURL: raw}, nil
}
}
}
return fetchLatestFromGitHub(repo)
}
func performUpdateInPlace() error {
log.Info().Str("version", latestVersion.name).Msg("performing in-place update")
if latestVersion.binaryURL == "" {
return fmt.Errorf("no update available")
}
currentBinary, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
// download the new binary
log.Info().Str("url", latestVersion.binaryURL).Msg("downloading version for update")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(latestVersion.binaryURL)
if err != nil {
return fmt.Errorf("failed to download binary: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
b, _ := io.ReadAll(resp.Body)
body := string(b)
if len(body) > 200 {
body = body[0:199] + "…"
}
log.Warn().Str("body", body).Int("status", resp.StatusCode).Msg("github failed to serve us the binary again")
return fmt.Errorf("downloading the new binary from github failed with status %d", resp.StatusCode)
}
// save the new binary to a stable path (overwrite it if it exists)
tempPath := fmt.Sprintf("pyramid-update-%s", latestVersion.name)
tempFile, err := os.Create(tempPath)
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
defer os.Remove(tempPath)
if _, err := io.Copy(tempFile, resp.Body); err != nil {
tempFile.Close()
return fmt.Errorf("failed to write binary: %w", err)
}
tempFile.Close()
// use rename for atomic replacement
log.Info().Msg("replacing binary with new version")
if err := os.Rename(currentBinary, "pyramid-old-binary"); err != nil {
return fmt.Errorf("replace failed: %w", err)
}
if err := os.Rename(tempPath, currentBinary); err != nil {
return fmt.Errorf("replace failed: %w", err)
}
// ensure executable permissions on the final binary
if err := os.Chmod(currentBinary, 0755); err != nil {
return fmt.Errorf("chmod failed: %w", err)
}
log.Info().Msg("restarting process with new binary...")
// get the absolute path (syscall.Exec requires absolute path)
absPath, err := filepath.Abs(currentBinary)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
// execute the new binary, replacing current process
// this call does not return if successful, therefore we must perform a graceful deinitialization of all things
groups.ShutdownEmbeddedLiveKit()
cancelStartContext(updating)
global.End()
search.End()
err = syscall.Exec(absPath, append([]string{absPath}, os.Args[1:]...), os.Environ())
// if we reach here, exec failed
return fmt.Errorf("exec failed: %w", err)
}