-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_archiver.go
100 lines (83 loc) · 2 KB
/
cache_archiver.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
package helpers
import (
"fmt"
"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"
)
type CacheArchiverCommand struct {
fileArchiver
retryHelper
File string `long:"file" description:"The path to file"`
URL string `long:"url" description:"Download artifacts instead of uploading them"`
}
func (c *CacheArchiverCommand) upload() (bool, error) {
logrus.Infoln("Uploading", filepath.Base(c.File))
file, err := os.Open(c.File)
if err != nil {
return false, err
}
defer file.Close()
fi, err := file.Stat()
if err != nil {
return false, err
}
req, err := http.NewRequest("PUT", c.URL, file)
if err != nil {
return true, err
}
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
req.ContentLength = fi.Size()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return true, err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
// Retry on server errors
retry := resp.StatusCode/100 == 5
return retry, fmt.Errorf("Received: %s", resp.Status)
}
return false, nil
}
func (c *CacheArchiverCommand) Execute(*cli.Context) {
if c.File == "" {
logrus.Fatalln("Missing --file")
}
// Enumerate files
err := c.enumerate()
if err != nil {
logrus.Fatalln(err)
}
// Check if list of files changed
if !c.isFileChanged(c.File) {
logrus.Infoln("Archive is up to date!")
return
}
// Create archive
err = archives.CreateZipFile(c.File, c.sortedFiles())
if err != nil {
logrus.Fatalln(err)
}
// Upload archive if needed
if c.URL != "" {
err := c.doRetry(c.upload)
if err != nil {
logrus.Warningln(err)
}
}
}
func init() {
common.RegisterCommand2("cache-archiver", "create and upload cache artifacts (internal)", &CacheArchiverCommand{
retryHelper: retryHelper{
Retry: 2,
RetryTime: time.Second,
},
})
}