-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdependency_download.go
More file actions
553 lines (461 loc) · 14.4 KB
/
Copy pathdependency_download.go
File metadata and controls
553 lines (461 loc) · 14.4 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
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// PlatformInfo represents platform-specific information
type PlatformInfo struct {
OS string
Arch string
}
// DependencyConfig represents configuration for a dependency
type DependencyConfig struct {
Name string
Version string
BaseURL string
Patterns map[string]PlatformPattern // Key: "os-arch" or "os"
DestDir string
TempDir string // Directory for temporary files (defaults to "./temp")
Executable string // Name of the executable file
MaxRetries int
Timeout time.Duration
ForceUpdate bool
VerifyHash bool
ExpectedHash string // Optional expected SHA256 hash
}
// PlatformPattern defines how to construct download URLs and extract files for a platform
type PlatformPattern struct {
URLTemplate string // Template with placeholders like {version}, {os}, {arch}
ArchiveFormat string // "zip", "tar.gz", or "binary"
ExecutableName string // Name of executable inside archive
}
// DependencyDownloader handles downloading and managing dependencies
type DependencyDownloader struct {
config *DependencyConfig
client *http.Client
}
// NewDependencyDownloader creates a new dependency downloader
func NewDependencyDownloader(config *DependencyConfig) *DependencyDownloader {
if config.MaxRetries == 0 {
config.MaxRetries = 3
}
if config.Timeout == 0 {
config.Timeout = 30 * time.Second
}
if config.TempDir == "" {
config.TempDir = "./temp"
}
return &DependencyDownloader{
config: config,
client: &http.Client{Timeout: config.Timeout},
}
}
// Download downloads and installs the dependency
func (d *DependencyDownloader) Download() error {
platform := d.getCurrentPlatform()
pattern, err := d.getPatternForPlatform(platform)
if err != nil {
return fmt.Errorf("unsupported platform %s-%s: %w", platform.OS, platform.Arch, err)
}
// Create destination directory
if err := os.MkdirAll(d.config.DestDir, 0755); err != nil {
return fmt.Errorf("failed to create destination directory: %w", err)
}
// Create temp directory
if err := os.MkdirAll(d.config.TempDir, 0755); err != nil {
return fmt.Errorf("failed to create temp directory: %w", err)
}
executablePath := filepath.Join(d.config.DestDir, d.config.Executable)
// Check if update is needed
if !d.config.ForceUpdate && !d.isUpdateNeeded(executablePath) {
log.WithFields(log.Fields{
"dependency": d.config.Name,
"path": executablePath,
}).Debug("Dependency already exists and is up to date")
return nil
}
// Construct download URL
downloadURL := d.buildDownloadURL(pattern, platform)
log.WithFields(log.Fields{
"dependency": d.config.Name,
"version": d.config.Version,
"url": downloadURL,
"platform": fmt.Sprintf("%s-%s", platform.OS, platform.Arch),
}).Info("Downloading dependency")
// Download with retry logic
tempFile, err := d.downloadWithRetry(downloadURL)
if err != nil {
return fmt.Errorf("failed to download %s: %w", d.config.Name, err)
}
defer os.Remove(tempFile)
// Extract and install
hash, err := d.extractAndInstall(tempFile, pattern, executablePath)
if err != nil {
return fmt.Errorf("failed to extract and install %s: %w", d.config.Name, err)
}
// Verify hash if expected hash is provided
if d.config.VerifyHash && d.config.ExpectedHash != "" {
if hash != d.config.ExpectedHash {
return fmt.Errorf("hash verification failed for %s: expected %s, got %s",
d.config.Name, d.config.ExpectedHash, hash)
}
log.WithField("dependency", d.config.Name).Debug("Hash verification passed")
}
// Store hash for future comparisons
if err := d.storeHash(executablePath, hash); err != nil {
log.WithError(err).Warn("Failed to store hash file")
}
// Clean up temp directory (optional - remove old temp files)
d.cleanupTempDir()
log.WithFields(log.Fields{
"dependency": d.config.Name,
"path": executablePath,
"hash": hash[:8] + "...", // Show first 8 chars of hash
}).Info("Successfully downloaded and installed dependency")
return nil
}
// getCurrentPlatform returns the current platform information
func (d *DependencyDownloader) getCurrentPlatform() PlatformInfo {
return PlatformInfo{
OS: runtime.GOOS,
Arch: runtime.GOARCH,
}
}
// getPatternForPlatform gets the appropriate pattern for the current platform
func (d *DependencyDownloader) getPatternForPlatform(platform PlatformInfo) (PlatformPattern, error) {
// Try exact match first (os-arch)
key := fmt.Sprintf("%s-%s", platform.OS, platform.Arch)
if pattern, exists := d.config.Patterns[key]; exists {
return pattern, nil
}
// Try OS-only match
if pattern, exists := d.config.Patterns[platform.OS]; exists {
return pattern, nil
}
// Try common aliases
aliases := d.getPlatformAliases(platform)
for _, alias := range aliases {
if pattern, exists := d.config.Patterns[alias]; exists {
return pattern, nil
}
}
return PlatformPattern{}, fmt.Errorf("no pattern found for platform %s-%s", platform.OS, platform.Arch)
}
// getPlatformAliases returns common aliases for a platform
func (d *DependencyDownloader) getPlatformAliases(platform PlatformInfo) []string {
var aliases []string
// OS aliases
switch platform.OS {
case "darwin":
aliases = append(aliases, "macos", "mac", "osx")
case "windows":
aliases = append(aliases, "win")
}
// Architecture aliases
switch platform.Arch {
case "amd64":
aliases = append(aliases, "x86_64", "x64")
case "arm64":
aliases = append(aliases, "aarch64")
case "386":
aliases = append(aliases, "i386", "x86")
case "mips":
aliases = append(aliases, "mips32")
case "mipsle":
aliases = append(aliases, "mipsel")
}
return aliases
}
// buildDownloadURL constructs the download URL using the pattern template
func (d *DependencyDownloader) buildDownloadURL(pattern PlatformPattern, platform PlatformInfo) string {
url := d.config.BaseURL + pattern.URLTemplate
// Replace placeholders
replacements := map[string]string{
"{version}": d.config.Version,
"{os}": platform.OS,
"{arch}": platform.Arch,
"{name}": d.config.Name,
}
// Add architecture aliases for common patterns
if platform.Arch == "amd64" {
replacements["{x86_64}"] = "x86_64"
replacements["{x64}"] = "x64"
}
if platform.Arch == "arm64" {
replacements["{aarch64}"] = "aarch64"
}
for placeholder, value := range replacements {
url = strings.ReplaceAll(url, placeholder, value)
}
return url
}
// downloadWithRetry downloads a file with retry logic
func (d *DependencyDownloader) downloadWithRetry(url string) (string, error) {
var lastErr error
for attempt := 1; attempt <= d.config.MaxRetries; attempt++ {
if attempt > 1 {
waitTime := time.Duration(attempt-1) * 2 * time.Second
log.WithFields(log.Fields{
"attempt": attempt,
"wait": waitTime,
}).Warn("Retrying download after failure")
time.Sleep(waitTime)
}
tempFile, err := d.downloadFile(url)
if err == nil {
return tempFile, nil
}
lastErr = err
log.WithError(err).WithField("attempt", attempt).Warn("Download attempt failed")
}
return "", fmt.Errorf("failed after %d attempts: %w", d.config.MaxRetries, lastErr)
}
// downloadFile downloads a file to a temporary location within the working directory
func (d *DependencyDownloader) downloadFile(url string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), d.config.Timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return "", err
}
resp, err := d.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status)
}
// Create temporary file in our temp directory
tempFileName := fmt.Sprintf("%s-download-%d-%d", d.config.Name, time.Now().Unix(), os.Getpid())
tempFilePath := filepath.Join(d.config.TempDir, tempFileName)
tempFile, err := os.Create(tempFilePath)
if err != nil {
return "", fmt.Errorf("failed to create temp file: %w", err)
}
defer tempFile.Close()
// Copy with progress (for large files)
written, err := io.Copy(tempFile, resp.Body)
if err != nil {
os.Remove(tempFile.Name())
return "", fmt.Errorf("failed to write temp file: %w", err)
}
log.WithFields(log.Fields{
"dependency": d.config.Name,
"size": formatBytes(written),
"tempFile": tempFilePath,
}).Debug("Download completed")
return tempFile.Name(), nil
}
// cleanupTempDir removes old temporary files from the temp directory
func (d *DependencyDownloader) cleanupTempDir() {
// Clean up files older than 1 hour
cutoffTime := time.Now().Add(-1 * time.Hour)
entries, err := os.ReadDir(d.config.TempDir)
if err != nil {
log.WithError(err).Debug("Failed to read temp directory for cleanup")
return
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
if info.ModTime().Before(cutoffTime) && strings.Contains(entry.Name(), "-download-") {
filePath := filepath.Join(d.config.TempDir, entry.Name())
if err := os.Remove(filePath); err != nil {
log.WithError(err).WithField("file", filePath).Debug("Failed to remove old temp file")
} else {
log.WithField("file", filePath).Debug("Removed old temp file")
}
}
}
}
// extractAndInstall extracts the downloaded file and installs the executable
func (d *DependencyDownloader) extractAndInstall(archivePath string, pattern PlatformPattern, executablePath string) (string, error) {
switch pattern.ArchiveFormat {
case "zip":
return d.extractZipAndInstall(archivePath, pattern.ExecutableName, executablePath)
case "tar.gz":
return d.extractTarGzAndInstall(archivePath, pattern.ExecutableName, executablePath)
case "binary":
return d.installBinary(archivePath, executablePath)
default:
return "", fmt.Errorf("unsupported archive format: %s", pattern.ArchiveFormat)
}
}
// extractZipAndInstall extracts a ZIP archive and installs the executable
func (d *DependencyDownloader) extractZipAndInstall(archivePath, executableName, destPath string) (string, error) {
reader, err := zip.OpenReader(archivePath)
if err != nil {
return "", err
}
defer reader.Close()
for _, file := range reader.File {
if file.FileInfo().IsDir() {
continue
}
if filepath.Base(file.Name) == executableName {
return d.extractFileFromZip(file, destPath)
}
}
return "", fmt.Errorf("executable '%s' not found in ZIP archive", executableName)
}
// extractFileFromZip extracts a single file from a ZIP archive
func (d *DependencyDownloader) extractFileFromZip(file *zip.File, destPath string) (string, error) {
src, err := file.Open()
if err != nil {
return "", err
}
defer src.Close()
dst, err := os.Create(destPath)
if err != nil {
return "", err
}
defer dst.Close()
hasher := sha256.New()
writer := io.MultiWriter(dst, hasher)
if _, err := io.Copy(writer, src); err != nil {
return "", err
}
// Make executable
if err := os.Chmod(destPath, 0755); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// extractTarGzAndInstall extracts a tar.gz archive and installs the executable
func (d *DependencyDownloader) extractTarGzAndInstall(archivePath, executableName, destPath string) (string, error) {
file, err := os.Open(archivePath)
if err != nil {
return "", err
}
defer file.Close()
gzr, err := gzip.NewReader(file)
if err != nil {
return "", err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
if header.Typeflag == tar.TypeReg && filepath.Base(header.Name) == executableName {
return d.extractFileFromTar(tr, destPath)
}
}
return "", fmt.Errorf("executable '%s' not found in tar.gz archive", executableName)
}
// extractFileFromTar extracts a single file from a tar reader
func (d *DependencyDownloader) extractFileFromTar(tr *tar.Reader, destPath string) (string, error) {
dst, err := os.Create(destPath)
if err != nil {
return "", err
}
defer dst.Close()
hasher := sha256.New()
writer := io.MultiWriter(dst, hasher)
if _, err := io.Copy(writer, tr); err != nil {
return "", err
}
// Make executable
if err := os.Chmod(destPath, 0755); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// installBinary installs a direct binary file
func (d *DependencyDownloader) installBinary(srcPath, destPath string) (string, error) {
src, err := os.Open(srcPath)
if err != nil {
return "", err
}
defer src.Close()
dst, err := os.Create(destPath)
if err != nil {
return "", err
}
defer dst.Close()
hasher := sha256.New()
writer := io.MultiWriter(dst, hasher)
if _, err := io.Copy(writer, src); err != nil {
return "", err
}
// Make executable
if err := os.Chmod(destPath, 0755); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// isUpdateNeeded checks if an update is needed
func (d *DependencyDownloader) isUpdateNeeded(executablePath string) bool {
// Check if executable exists
if _, err := os.Stat(executablePath); os.IsNotExist(err) {
return true
}
// Check if hash file exists (indicates previous successful download)
hashFile := executablePath + ".hash"
if _, err := os.Stat(hashFile); os.IsNotExist(err) {
return true
}
// If we have a specific expected hash, verify it
if d.config.ExpectedHash != "" {
currentHash, err := d.getFileHash(executablePath)
if err != nil || currentHash != d.config.ExpectedHash {
return true
}
}
return false
}
// getFileHash calculates the SHA256 hash of a file
func (d *DependencyDownloader) getFileHash(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// storeHash stores the hash of the downloaded file
func (d *DependencyDownloader) storeHash(executablePath, hash string) error {
hashFile := executablePath + ".hash"
return os.WriteFile(hashFile, []byte(hash), 0644)
}
// formatBytes formats byte count as human readable string
func formatBytes(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}