-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_extractor.go
99 lines (83 loc) · 2.28 KB
/
cache_extractor.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
package helpers
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"time"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/common"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/helpers/archives"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/helpers/formatter"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/helpers/url"
)
type CacheExtractorCommand struct {
retryHelper
File string `long:"file" description:"The file containing your cache artifacts"`
URL string `long:"url" description:"Download artifacts instead of uploading them"`
}
func (c *CacheExtractorCommand) download() (bool, error) {
os.MkdirAll(filepath.Dir(c.File), 0700)
file, err := ioutil.TempFile(filepath.Dir(c.File), "cache")
if err != nil {
return false, err
}
defer file.Close()
defer os.Remove(file.Name())
resp, err := http.Get(c.URL)
if err != nil {
return true, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return false, os.ErrNotExist
} else if resp.StatusCode/100 != 2 {
// Retry on server errors
retry := resp.StatusCode/100 == 5
return retry, fmt.Errorf("Received: %s", resp.Status)
}
fi, _ := os.Lstat(c.File)
date, _ := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified"))
if fi != nil && !date.After(fi.ModTime()) {
logrus.Infoln(filepath.Base(c.File), "is up to date")
return false, nil
}
logrus.Infoln("Downloading", filepath.Base(c.File), "from", url_helpers.CleanURL(c.URL))
_, err = io.Copy(file, resp.Body)
if err != nil {
return true, err
}
os.Chtimes(file.Name(), time.Now(), date)
err = os.Rename(file.Name(), c.File)
if err != nil {
return false, err
}
return false, nil
}
func (c *CacheExtractorCommand) Execute(context *cli.Context) {
formatter.SetRunnerFormatter()
if len(c.File) == 0 {
logrus.Fatalln("Missing cache file")
}
if c.URL != "" {
err := c.doRetry(c.download)
if err != nil {
logrus.Fatalln(err)
}
}
err := archives.ExtractZipFile(c.File)
if err != nil && !os.IsNotExist(err) {
logrus.Fatalln(err)
}
}
func init() {
common.RegisterCommand2("cache-extractor", "download and extract cache artifacts (internal)", &CacheExtractorCommand{
retryHelper: retryHelper{
Retry: 2,
RetryTime: time.Second,
},
})
}