-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
executable file
·299 lines (280 loc) · 8.16 KB
/
util.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
package util
import (
"cloud.google.com/go/storage"
"context"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/google/go-github/v27/github"
go_logger "github.com/pefish/go-logger"
"github.com/pefish/selenium-server/pkg/global"
"google.golang.org/api/option"
"hash"
"io"
"net/http"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strings"
"sync"
)
type file struct {
url string
name string
hash string
hashType string // default is sha256
rename []string
browser bool
}
var files = []file{
{
// https://console.cloud.google.com/storage/browser/selenium-release
url: "https://selenium-release.storage.googleapis.com/3.141/selenium-server-standalone-3.141.59.jar",
//url: "https://storage.cloud.google.com/selenium-release/3.9/selenium-server-standalone-3.9.1.jar",
name: "selenium-server.jar",
// TODO(minusnine): reimplement hashing so that it is less annoying for maintenance.
// hash: "acf71b77d1b66b55db6fb0bed6d8bae2bbd481311bcbedfeff472c0d15e8f3cb",
},
//{
// url: "https://saucelabs.com/downloads/sc-4.5.4-linux.tar.gz",
// name: "sauce-connect.tar.gz",
// rename: []string{"sc-4.5.4-linux", "sauce-connect"},
//},
}
func addLatestGithubRelease(ctx context.Context, owner, repo, assetName, localFileName string) error {
client := github.NewClient(nil)
rel, _, err := client.Repositories.GetLatestRelease(ctx, owner, repo)
if err != nil {
return err
}
assetNameRE, err := regexp.Compile(assetName)
if err != nil {
return fmt.Errorf("invalid asset name regular expression %q: %s", assetName, err)
}
for _, a := range rel.Assets {
if !assetNameRE.MatchString(a.GetName()) {
continue
}
u := a.GetBrowserDownloadURL()
if u == "" {
return fmt.Errorf("%s does not have a download URL", a.GetName())
}
files = append(files, file{
name: localFileName,
url: u,
})
return nil
}
return fmt.Errorf("Release for %s not found at http://github.com/%s/%s/releases", assetName, owner, repo)
}
func addChromeDriver(ctx context.Context, latestChromeBuild string) error {
prefix := ""
suffix := ""
switch runtime.GOOS {
case "windows":
prefix = "Win_x64"
suffix = "win32"
case "darwin":
prefix = "Mac"
suffix = "mac64"
case "linux":
prefix = "Linux_x64"
suffix = "linux64"
}
// Bucket URL: https://console.cloud.google.com/storage/browser/chromium-browser-snapshots/?pli=1
storageBktName := "chromium-browser-snapshots"
chromeDriverName := "chromedriver"
gcsPath := fmt.Sprintf("gs://%s/", storageBktName)
client, err := storage.NewClient(ctx, option.WithHTTPClient(http.DefaultClient))
if err != nil {
return fmt.Errorf("cannot create a storage client for downloading the chrome browser: %v", err)
}
bkt := client.Bucket(storageBktName)
if latestChromeBuild == "" {
lastChangeFile := fmt.Sprintf("%s/LAST_CHANGE", prefix)
r, err := bkt.Object(lastChangeFile).NewReader(ctx)
if err != nil {
return fmt.Errorf("cannot create a reader for %s%s file: %v", gcsPath, lastChangeFile, err)
}
defer r.Close()
// Read the last change file content for the latest build directory name
data, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("cannot read from %s%s file: %v", gcsPath, lastChangeFile, err)
}
latestChromeBuild = string(data)
//go_logger.Logger.InfoF("latestChromeBuild: %s", latestChromeBuild)
}
filename := fmt.Sprintf("%s_%s.zip", chromeDriverName, suffix)
latestChromeDriverPackage := path.Join(prefix, latestChromeBuild, filename)
//go_logger.Logger.InfoF("file: %s", latestChromeDriverPackage)
cpAttrs, err := bkt.Object(latestChromeDriverPackage).Attrs(ctx)
if err != nil {
return fmt.Errorf("cannot get the chrome driver package %s%s attrs: %v", gcsPath, latestChromeDriverPackage, err)
}
files = append(files, file{
name: filename,
url: cpAttrs.MediaLink,
rename: []string{
fmt.Sprintf("%s_%s/%s", chromeDriverName, suffix, chromeDriverName),
chromeDriverName,
},
})
return nil
}
func addFirefoxDriver(ctx context.Context, version string) error {
return addLatestGithubRelease(
ctx,
"mozilla",
"geckodriver",
"geckodriver-.*linux64.tar.gz",
"geckodriver.tar.gz",
)
}
func handleFile(file file, downloadBrowsers bool) error {
if file.browser && !downloadBrowsers {
go_logger.Logger.InfoF("Skipping %q because --download_browser is not set.", file.name)
return nil
}
if file.hash != "" && fileSameHash(file) {
go_logger.Logger.InfoF("Skipping file %q which has already been downloaded.", file.name)
} else {
go_logger.Logger.InfoF("Downloading %q from %q", file.name, file.url)
if err := downloadFile(file); err != nil {
return err
}
}
switch path.Ext(file.name) {
case ".zip":
go_logger.Logger.InfoF("Unzipping %q", file.name)
if err := exec.Command("unzip", "-o", file.name).Run(); err != nil {
return fmt.Errorf("Error unzipping %q: %v", file.name, err)
}
os.RemoveAll(file.name)
case ".gz":
go_logger.Logger.InfoF("Unzipping %q", file.name)
if err := exec.Command("tar", "-xzf", file.name).Run(); err != nil {
return fmt.Errorf("Error unzipping %q: %v", file.name, err)
}
os.RemoveAll(file.name)
case ".bz2":
go_logger.Logger.InfoF("Unzipping %q", file.name)
if err := exec.Command("tar", "-xjf", file.name).Run(); err != nil {
return fmt.Errorf("Error unzipping %q: %v", file.name, err)
}
os.RemoveAll(file.name)
}
if rename := file.rename; len(rename) == 2 {
go_logger.Logger.InfoF("Renaming %q to %q", rename[0], rename[1])
os.RemoveAll(rename[1])
if err := os.Rename(rename[0], rename[1]); err != nil {
return fmt.Errorf("Error renaming %q to %q: %v", rename[0], rename[1], err)
}
arr := strings.Split(rename[0], "/")
if len(arr) > 1 {
os.RemoveAll(arr[0])
}
}
return nil
}
func downloadFile(file file) (err error) {
f, err := os.Create(file.name)
if err != nil {
return fmt.Errorf("error creating %q: %v", file.name, err)
}
defer func() {
if closeErr := f.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("error closing %q: %v", file.name, err)
}
}()
resp, err := http.Get(file.url)
if err != nil {
return fmt.Errorf("%s: error downloading %q: %v", file.name, file.url, err)
}
defer resp.Body.Close()
if file.hash != "" {
var h hash.Hash
switch strings.ToLower(file.hashType) {
case "md5":
h = md5.New()
case "sha1":
h = sha1.New()
default:
h = sha256.New()
}
if _, err := io.Copy(io.MultiWriter(f, h), resp.Body); err != nil {
return fmt.Errorf("%s: error downloading %q: %v", file.name, file.url, err)
}
if h := hex.EncodeToString(h.Sum(nil)); h != file.hash {
return fmt.Errorf("%s: got %s hash %q, want %q", file.name, file.hashType, h, file.hash)
}
} else {
if _, err := io.Copy(f, resp.Body); err != nil {
return fmt.Errorf("%s: error downloading %q: %v", file.name, file.url, err)
}
}
return nil
}
func fileSameHash(file file) bool {
if _, err := os.Stat(file.name); err != nil {
return false
}
var h hash.Hash
switch strings.ToLower(file.hashType) {
case "md5":
h = md5.New()
default:
h = sha256.New()
}
f, err := os.Open(file.name)
if err != nil {
return false
}
defer f.Close()
if _, err := io.Copy(h, f); err != nil {
return false
}
sum := hex.EncodeToString(h.Sum(nil))
if sum != file.hash {
go_logger.Logger.WarnF("File %q: got hash %q, expect hash %q", file.name, sum, file.hash)
return false
}
return true
}
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func DownloadDeps(ctx context.Context, browserName, driverBuildVersion string) error {
switch browserName {
case string(global.Browser_Firefox):
if err := addFirefoxDriver(ctx, driverBuildVersion); err != nil {
go_logger.Logger.ErrorF("Unable to download firefox driver: %v", err)
}
case string(global.Browser_Chrome):
if err := addChromeDriver(ctx, driverBuildVersion); err != nil {
go_logger.Logger.ErrorF("Unable to download chrome driver: %v", err)
}
}
var wg sync.WaitGroup
for _, file := range files {
wg.Add(1)
file := file
go func() {
if err := handleFile(file, true); err != nil {
go_logger.Logger.ErrorF("Error handling %s: %s", file.name, err)
os.Exit(1)
}
wg.Done()
}()
}
wg.Wait()
return nil
}