Repository navigation
Expand file tree
/
Copy pathsupervisor_binary.go
More file actions
230 lines (221 loc) · 5.92 KB
/
Copy pathsupervisor_binary.go
File metadata and controls
230 lines (221 loc) · 5.92 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
package embeddedpostgres
import (
"bufio"
"context"
"errors"
"fmt"
"github.com/fergusstrange/embedded-postgres/v2/internal/filelock"
"github.com/fergusstrange/embedded-postgres/v2/internal/platform"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"strings"
"time"
)
// ReleaseVersion is set for CLI builds; Go consumers use module build metadata.
var ReleaseVersion = "v2.0.0-dev"
func resolveSupervisor(ctx context.Context, c Config) (string, error) {
selected := c.supervisorPath
if selected == "" {
selected = os.Getenv("EP_SUPERVISOR")
}
if selected != "" {
p, err := filepath.Abs(selected)
if err != nil {
return "", err
}
st, err := os.Stat(p)
if err != nil {
return "", err
}
if !st.Mode().IsRegular() {
return "", errors.New("supervisor must be an executable file")
}
return p, nil
}
version := supervisorVersion()
if !publishedVersion(version) {
return "", errors.New("source build requires Config.Supervisor(path) or EP_SUPERVISOR; build ./cmd/embedded-postgres first")
}
cache, err := cacheDirectory(c.storage.CacheDir)
if err != nil {
return "", err
}
name := platform.Executable("embedded-postgres_" + runtime.GOOS + "_" + runtime.GOARCH)
return cacheSupervisor(ctx, cache, version, name, "https://github.com/fergusstrange/embedded-postgres/releases/download/"+version, &http.Client{Timeout: time.Minute})
}
var releaseVersionPattern = regexp.MustCompile(`^v2\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$`)
var pseudoVersionPattern = regexp.MustCompile(`(?:[.-])[0-9]{14}-[0-9a-f]{12}$`)
func publishedVersion(version string) bool {
return releaseVersionPattern.MatchString(version) && !pseudoVersionPattern.MatchString(version) && version != "v2.0.0-dev"
}
func moduleVersion(info *debug.BuildInfo) string {
for _, d := range info.Deps {
if d.Path == "github.com/fergusstrange/embedded-postgres/v2" && d.Replace == nil {
return d.Version
}
}
return ""
}
func supervisorVersion() string {
if info, ok := debug.ReadBuildInfo(); ok && len(info.Deps) != 0 {
return moduleVersion(info)
}
// Go test binaries omit dependency versions. Module-cache source paths
// retain them, including with -trimpath (module/path@version/file.go).
_, source, _, ok := runtime.Caller(0)
if !ok {
return ""
}
return sourceModuleVersion(source)
}
func sourceModuleVersion(source string) string {
source = strings.ReplaceAll(source, `\`, "/")
_, suffix, found := strings.Cut("/"+source, "/github.com/fergusstrange/embedded-postgres/v2@")
version, file, separated := strings.Cut(suffix, "/")
if !found || !separated || file != "supervisor_binary.go" || !publishedVersion(version) {
return ""
}
return version
}
func cacheSupervisor(ctx context.Context, cache, version, name, base string, client *http.Client) (string, error) {
path := filepath.Join(cache, version+"-"+name)
lock, err := filelock.Acquire(ctx, path+".lock", true)
if err != nil {
return "", err
}
defer lock.Close()
if st, e := os.Stat(path); e == nil && st.Mode().IsRegular() {
return path, nil
}
req, err := http.NewRequestWithContext(ctx, "GET", base+"/checksums.txt", nil)
if err != nil {
return "", err
}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", fmt.Errorf("supervisor checksum HTTP %d", res.StatusCode)
}
digest := ""
scanner := bufio.NewScanner(io.LimitReader(res.Body, 1<<20))
for scanner.Scan() {
f := strings.Fields(scanner.Text())
if len(f) == 2 && strings.TrimPrefix(f[1], "*") == name {
digest = f[0]
}
}
if err = scanner.Err(); err != nil {
return "", err
}
if digest == "" {
return "", errors.New("release missing supervisor checksum")
}
f, err := download(ctx, client, base+"/"+name, digest, cache, 64<<20)
if err != nil {
return "", err
}
temp := f.Name()
defer os.Remove(temp)
if err = f.Close(); err != nil {
return "", err
}
if err = os.Chmod(temp, 0755); err != nil {
return "", err
}
if err = os.Rename(temp, path); err != nil {
return "", err
}
return path, nil
}
func withoutPassword(s string) string {
u, err := url.Parse(s)
if err != nil {
return ""
}
if u.User != nil {
u.User = url.User(u.User.Username())
}
return u.String()
}
func copyFile(source, dest string, mode os.FileMode) (err error) {
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
if mode&0111 != 0 {
unlock := platform.ProtectExecutableWrite()
defer unlock()
}
out, err := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
if err != nil {
return err
}
_, err = io.Copy(out, in)
return errors.Join(err, out.Close())
}
func copyInstallation(ctx context.Context, source, dest string) error {
var err error
source, err = filepath.EvalSymlinks(source)
if err != nil {
return err
}
source, err = filepath.Abs(source)
if err != nil {
return err
}
return filepath.WalkDir(source, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if err = ctx.Err(); err != nil {
return err
}
rel, err := filepath.Rel(source, path)
if err != nil {
return err
}
target := filepath.Join(dest, rel)
if d.IsDir() {
return os.MkdirAll(target, 0755)
}
if d.Type()&os.ModeSymlink != 0 {
link, err := os.Readlink(path)
if err != nil {
return err
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
inside, err := filepath.Rel(source, resolved)
if err != nil || !filepath.IsLocal(inside) {
return fmt.Errorf("binary symlink escapes installation: %s", rel)
}
if filepath.IsAbs(link) {
link, err = filepath.Rel(filepath.Dir(target), filepath.Join(dest, inside))
if err != nil {
return err
}
}
return os.Symlink(link, target)
}
info, err := d.Info()
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("unsupported binary file: %s", path)
}
return copyFile(path, target, info.Mode().Perm()&0755)
})
}