-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
installer.go
501 lines (399 loc) · 11.6 KB
/
installer.go
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// Package installer is responsible for finding, acquiring and addressing
// runtime dependencies for this package (e.g. Ruby standalone, Rust bindings etc.)
package installer
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"runtime"
"strings"
getter "github.com/hashicorp/go-getter"
goversion "github.com/hashicorp/go-version"
"gopkg.in/yaml.v2"
"crypto/md5"
"github.com/spf13/afero"
)
// Installer is used to check the Pact Go installation is setup correctly, and can automatically install
// packages if required
type Installer struct {
downloader downloader
hasher hasher
config configReadWriter
os string
arch string
fs afero.Fs
libDir string
force bool
}
type installerConfig func(*Installer) error
// NewInstaller creates a new initialised Installer
func NewInstaller(opts ...installerConfig) (*Installer, error) {
i := &Installer{downloader: &defaultDownloader{}, fs: afero.NewOsFs(), hasher: &defaultHasher{}, config: &configuration{}}
for _, opt := range opts {
err := opt(i)
if err != nil {
log.Println("[ERROR] failure when configuring installer:", err)
return nil, err
}
}
if _, ok := supportedOSes[runtime.GOOS]; !ok {
return nil, fmt.Errorf("%s is not a supported OS", runtime.GOOS)
}
i.os = supportedOSes[runtime.GOOS]
if !strings.Contains(runtime.GOARCH, "64") {
return nil, fmt.Errorf("%s is not a supported architecture, only 64 bit architectures are supported", runtime.GOARCH)
}
switch runtime.GOARCH {
case "amd64":
i.arch = x86_64
case "arm64":
if runtime.GOOS == "darwin" {
i.arch = osx_aarch64
} else {
i.arch = aarch64
}
default:
i.arch = x86_64
log.Println("[WARN] amd64 architecture not detected, defaulting to x86_64. Behaviour may be undefined")
}
// Only perform a check if current OS is linux
if runtime.GOOS == "linux" {
err := i.checkMusl()
if err != nil {
log.Println("[DEBUG] unable to check for presence musl library due to error:", err)
}
}
return i, nil
}
// SetLibDir overrides the default library dir
func (i *Installer) SetLibDir(dir string) {
i.libDir = dir
}
// Force installs over the top
func (i *Installer) Force(force bool) {
i.force = force
}
// CheckInstallation checks installation of all of the required libraries
// and downloads if they aren't present
func (i *Installer) CheckInstallation() error {
// Check if files exist
// --> Check if existing installed files
if !i.force {
if err := i.CheckPackageInstall(); err == nil {
return nil
}
}
// Download dependencies
if err := i.downloadDependencies(); err != nil {
return err
}
// Install dependencies
if err := i.installDependencies(); err != nil {
return err
}
// Double check files landed correctly (can't execute 'version' call here,
// because of dependency on the native libs we're trying to download!)
if err := i.CheckPackageInstall(); err != nil {
return fmt.Errorf("unable to verify downloaded/installed dependencies: %s", err)
}
return nil
}
func (i *Installer) getLibDir() string {
if i.libDir != "" {
return i.libDir
}
env := os.Getenv(downloadEnvVar)
if env != "" {
return env
}
return "/usr/local/lib"
}
// CheckPackageInstall discovers any existing packages, and checks installation of a given binary using semver-compatible checks
func (i *Installer) CheckPackageInstall() error {
for pkg, info := range packages {
dst, _ := i.getLibDstForPackage(pkg)
if _, err := i.fs.Stat(dst); err != nil {
log.Println("[INFO] package", info.libName, "not found")
return err
} else {
log.Println("[INFO] package", info.libName, "found")
}
lib, ok := i.config.readConfig().Libraries[pkg]
if ok {
if err := checkVersion(info.libName, lib.Version, info.semverRange); err != nil {
return err
}
log.Println("[INFO] package", info.libName, "is correctly installed")
} else {
log.Println("[INFO] no package metadata information was found, run `pact-go install -f` to correct")
}
// This will only be populated during test when the ffi is loaded, but will actually test the FFI itself
// It is helpful because it will prevent issues where the FFI is manually updated without using the `pact-go install` command
if len(LibRegistry) == 0 {
log.Println("[DEBUG] skip checking ffi version() call because FFI not loaded. This is expected when running the 'pact-go' command.")
} else {
lib, ok := LibRegistry[pkg]
if ok {
log.Println("[INFO] checking version", lib.Version(), "for lib", info.libName, "within semver range", info.semverRange)
if err := checkVersion(info.libName, lib.Version(), info.semverRange); err != nil {
return err
}
} else {
log.Println("[DEBUG] unable to determine current version of package", pkg, "in LibRegistry", LibRegistry)
}
// Correct the configuration to reduce drift
err := i.updateConfiguration(dst, pkg, info)
if err != nil {
return err
}
}
}
return nil
}
// Download all dependencies, and update the pact-go configuration file
func (i *Installer) downloadDependencies() error {
for pkg, pkgInfo := range packages {
src, err := i.getDownloadURLForPackage(pkg)
if err != nil {
return err
}
dst, err := i.getLibDstForPackage(pkg)
if err != nil {
return err
}
err = i.downloader.download(src, dst)
if err != nil {
return err
}
err = os.Chmod(dst, 0755)
if err != nil {
log.Println("[WARN] unable to set permissions on file", dst, "due to error:", err)
}
err = i.updateConfiguration(dst, pkg, pkgInfo)
if err != nil {
return err
}
}
return nil
}
func (i *Installer) installDependencies() error {
if i.os == osx {
for pkg, info := range packages {
log.Println("[INFO] setting install_name on library", info.libName, "for osx")
dst, err := i.getLibDstForPackage(pkg)
if err != nil {
return err
}
err = setOSXInstallName(dst)
if err != nil {
return err
}
}
}
return nil
}
// returns src
func (i *Installer) getDownloadURLForPackage(pkg string) (string, error) {
pkgInfo, ok := packages[pkg]
if !ok {
return "", fmt.Errorf("unable to find package details for package: %s", pkg)
}
return fmt.Sprintf(downloadTemplate, pkg, pkgInfo.version, osToLibName[i.os], i.os, i.arch, osToExtension[i.os]), nil
}
func (i *Installer) getLibDstForPackage(pkg string) (string, error) {
_, ok := packages[pkg]
if !ok {
return "", fmt.Errorf("unable to find package details for package: %s", pkg)
}
return path.Join(i.getLibDir(), osToLibName[i.os]) + "." + osToExtension[i.os], nil
}
// Write the metadata to reduce drift
func (i *Installer) updateConfiguration(dst string, pkg string, info packageInfo) error {
// Get hash of file
fmt.Println(i.hasher)
hash, err := i.hasher.hash(dst)
if err != nil {
return err
}
// Read metadata
c := i.config.readConfig()
// Update config
c.Libraries[pkg] = packageMetadata{
LibName: info.libName,
Version: info.version,
Hash: hash,
}
// Write metadata
return i.config.writeConfig(c)
}
var setOSXInstallName = func(file string) error {
cmd := exec.Command("install_name_tool", "-id", file, file)
log.Println("[DEBUG] running command:", cmd)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error setting install name on pact lib: %s", err)
}
log.Println("[DEBUG] output from command", stdoutStderr)
return err
}
func checkVersion(lib, version, versionRange string) error {
log.Println("[INFO] checking version", version, "of", lib, "against semver constraint", versionRange)
v, err := goversion.NewVersion(version)
if err != nil {
return err
}
constraints, err := goversion.NewConstraint(versionRange)
if err != nil {
return err
}
if constraints.Check(v) {
log.Println("[DEBUG]", v, "satisfies constraints", v, constraints)
return nil
}
return fmt.Errorf("version %s of %s does not match constraint %s", version, lib, versionRange)
}
// checkMusl checks if the OS uses musl library instead of glibc
func (i *Installer) checkMusl() error {
lddPath, err := exec.LookPath("ldd")
if err != nil {
return fmt.Errorf("could not find ldd in environment path")
}
cmd := exec.Command(lddPath, "/bin/echo")
out, err := cmd.CombinedOutput()
if strings.Contains(string(out), "musl") {
log.Println("[WARN] Usage of musl library is known to cause problems, prefer using glibc instead.")
}
return err
}
// download template structure: "https://github.com/pact-foundation/pact-reference/releases/download/PACKAGE-vVERSION/LIBNAME-OS-ARCH.EXTENSION.gz"
var downloadTemplate = "https://github.com/pact-foundation/pact-reference/releases/download/%s-v%s/%s-%s-%s.%s.gz"
var supportedOSes = map[string]string{
"darwin": osx,
windows: windows,
linux: linux,
}
var osToExtension = map[string]string{
windows: "dll",
linux: "so",
osx: "dylib",
}
var osToLibName = map[string]string{
windows: "pact_ffi",
linux: "libpact_ffi",
osx: "libpact_ffi",
}
type packageInfo struct {
libName string
version string
semverRange string
}
const (
FFIPackage = "libpact_ffi"
downloadEnvVar = "PACT_GO_LIB_DOWNLOAD_PATH"
linux = "linux"
windows = "windows"
osx = "osx"
x86_64 = "x86_64"
osx_aarch64 = "aarch64-apple-darwin"
aarch64 = "aarch64"
)
var packages = map[string]packageInfo{
FFIPackage: {
libName: "libpact_ffi",
version: "0.4.5",
semverRange: ">= 0.4.0, < 1.0.0",
},
}
type Versioner interface {
Version() string
}
var LibRegistry = map[string]Versioner{}
type downloader interface {
download(src string, dst string) error
}
type defaultDownloader struct{}
func (d *defaultDownloader) download(src string, dst string) error {
log.Println("[INFO] downloading library from", src, "to", dst)
return getter.GetFile(dst, src)
}
type packageMetadata struct {
LibName string
Version string
Hash string
}
type pactConfig struct {
Libraries map[string]packageMetadata
}
type configReader interface {
readConfig() pactConfig
}
type configWriter interface {
writeConfig(pactConfig) error
}
type configReadWriter interface {
configReader
configWriter
}
type configuration struct{}
func getConfigPath() string {
user, err := user.Current()
if err != nil {
log.Fatalf(err.Error())
}
return path.Join(user.HomeDir, ".pact", "pact-go.yml")
}
func (configuration) readConfig() pactConfig {
pactConfigPath := getConfigPath()
c := pactConfig{
Libraries: map[string]packageMetadata{},
}
bytes, err := ioutil.ReadFile(pactConfigPath)
if err != nil {
log.Println("[DEBUG] error reading file", pactConfigPath, "error: ", err)
return c
}
err = yaml.Unmarshal(bytes, &c)
if err != nil {
log.Println("[DEBUG] error unmarshalling YAML", pactConfigPath, "error: ", err)
}
return c
}
func (configuration) writeConfig(c pactConfig) error {
log.Println("[DEBUG] writing config", c)
pactConfigPath := getConfigPath()
err := os.MkdirAll(filepath.Dir(pactConfigPath), 0755)
if err != nil {
log.Println("[DEBUG] error creating pact config directory")
return err
}
bytes, err := yaml.Marshal(c)
if err != nil {
log.Println("[DEBUG] error marshalling YAML", pactConfigPath, "error: ", err)
return err
}
log.Println("[DEBUG] writing yaml config to file", string(bytes))
return ioutil.WriteFile(pactConfigPath, bytes, 0644)
}
type hasher interface {
hash(src string) (string, error)
}
type defaultHasher struct{}
func (d *defaultHasher) hash(src string) (string, error) {
log.Println("[DEBUG] obtaining hash for file", src)
f, err := os.Open(src)
if err != nil {
return "", err
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}