-
Notifications
You must be signed in to change notification settings - Fork 18
/
agent.go
99 lines (80 loc) · 2.03 KB
/
agent.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 agent
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
var ErrAgentDownloadFailed = errors.New("failed to download agent")
func RetrieveBinary(
ctx context.Context,
agentVersion string,
agentOS string,
agentArchitecture string,
) (string, error) {
cacheDir, err := os.UserCacheDir()
if err != nil {
return "", err
}
agentCacheDir := filepath.Join(cacheDir, "cirrus", "agent")
if err := os.MkdirAll(agentCacheDir, 0700); err != nil {
return "", err
}
var agentSuffix string
if agentOS == "windows" {
agentSuffix = ".exe"
}
agentPath := filepath.Join(
agentCacheDir,
fmt.Sprintf("cirrus-ci-agent-%s-%s-%s%s", agentVersion, agentOS, agentArchitecture, agentSuffix),
)
// Agent found in the cache
_, err = os.Stat(agentPath)
if err == nil {
return agentPath, nil
}
tmpAgentFile, err := os.CreateTemp(agentCacheDir, "")
if err != nil {
return "", err
}
// Download the agent
agentURL := fmt.Sprintf("https://github.com/cirruslabs/cirrus-ci-agent/releases/download/v%s/agent-%s-%s%s",
agentVersion, agentOS, agentArchitecture, agentSuffix)
req, err := http.NewRequestWithContext(ctx, "GET", agentURL, http.NoBody)
if err != nil {
return "", err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%w: got HTTP code %d when downloading %s",
ErrAgentDownloadFailed, resp.StatusCode, agentURL)
}
_, err = io.Copy(tmpAgentFile, resp.Body)
if err != nil {
return "", err
}
// Make the agent binary executable
if err := os.Chmod(tmpAgentFile.Name(), 0500); err != nil {
return "", err
}
if err := tmpAgentFile.Close(); err != nil {
return "", err
}
// Move the agent to it's final destination
if err := os.Rename(tmpAgentFile.Name(), agentPath); err != nil {
// Already moved by another persistent worker instance?
if _, err := os.Stat(agentPath); err != nil {
return agentPath, nil
}
return "", err
}
return agentPath, nil
}