-
-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathlauncher.go
566 lines (476 loc) · 15 KB
/
launcher.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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
// Package launcher for launching browser utils.
package launcher
import (
"context"
"crypto"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync/atomic"
"github.com/go-rod/rod/lib/defaults"
"github.com/go-rod/rod/lib/launcher/flags"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/leakless"
)
// DefaultUserDataDirPrefix ...
var DefaultUserDataDirPrefix = filepath.Join(os.TempDir(), "rod", "user-data")
// Launcher is a helper to launch browser binary smartly.
type Launcher struct {
Flags map[flags.Flag][]string `json:"flags"`
ctx context.Context
ctxCancel func()
logger io.Writer
browser *Browser
parser *URLParser
pid int
exit chan struct{}
managed bool
serviceURL string
isLaunched int32 // zero means not launched
}
// New returns the default arguments to start browser.
// Headless will be enabled by default.
// Leakless will be enabled by default.
// UserDataDir will use OS tmp dir by default, this folder will usually be cleaned up by the OS after reboot.
// It will auto download the browser binary according to the current platform,
// check [Launcher.Bin] and [Launcher.Revision] for more info.
func New() *Launcher {
dir := defaults.Dir
if dir == "" {
dir = filepath.Join(DefaultUserDataDirPrefix, utils.RandString(8))
}
defaultFlags := map[flags.Flag][]string{
flags.Bin: {defaults.Bin},
flags.Leakless: nil,
flags.UserDataDir: {dir},
// use random port by default
flags.RemoteDebuggingPort: {defaults.Port},
// enable headless by default
flags.Headless: nil,
// to disable the init blank window
"no-first-run": nil,
"no-startup-window": nil,
// TODO: about the "site-per-process" see https://github.com/puppeteer/puppeteer/issues/2548
"disable-features": {"site-per-process", "TranslateUI"},
"disable-dev-shm-usage": nil,
"disable-background-networking": nil,
"disable-background-timer-throttling": nil,
"disable-backgrounding-occluded-windows": nil,
"disable-breakpad": nil,
"disable-client-side-phishing-detection": nil,
"disable-component-extensions-with-background-pages": nil,
"disable-default-apps": nil,
"disable-hang-monitor": nil,
"disable-ipc-flooding-protection": nil,
"disable-popup-blocking": nil,
"disable-prompt-on-repost": nil,
"disable-renderer-backgrounding": nil,
"disable-sync": nil,
"disable-site-isolation-trials": nil,
"enable-automation": nil,
"enable-features": {"NetworkService", "NetworkServiceInProcess"},
"force-color-profile": {"srgb"},
"metrics-recording-only": nil,
"use-mock-keychain": nil,
}
if defaults.Show {
delete(defaultFlags, flags.Headless)
}
if defaults.Devtools {
defaultFlags["auto-open-devtools-for-tabs"] = nil
}
if inContainer {
defaultFlags[flags.NoSandbox] = nil
}
if defaults.Proxy != "" {
defaultFlags[flags.ProxyServer] = []string{defaults.Proxy}
}
ctx, cancel := context.WithCancel(context.Background())
return &Launcher{
ctx: ctx,
ctxCancel: cancel,
Flags: defaultFlags,
exit: make(chan struct{}),
browser: NewBrowser(),
parser: NewURLParser(),
logger: io.Discard,
}
}
// NewUserMode is a preset to enable reusing current user data. Useful for automation of personal browser.
// If you see any error, it may because you can't launch debug port for existing browser, the solution is to
// completely close the running browser. Unfortunately, there's no API for rod to tell it automatically yet.
func NewUserMode() *Launcher {
ctx, cancel := context.WithCancel(context.Background())
bin, _ := LookPath()
return &Launcher{
ctx: ctx,
ctxCancel: cancel,
Flags: map[flags.Flag][]string{
flags.RemoteDebuggingPort: {"37712"},
"no-startup-window": nil,
flags.Bin: {bin},
},
browser: NewBrowser(),
exit: make(chan struct{}),
parser: NewURLParser(),
logger: io.Discard,
}
}
// NewAppMode is a preset to run the browser like a native application.
// The u should be a URL.
func NewAppMode(u string) *Launcher {
l := New()
l.Set(flags.App, u).
Set(flags.Env, "GOOGLE_API_KEY=no").
Headless(false).
Delete("no-startup-window").
Delete("enable-automation")
return l
}
// Context sets the context.
func (l *Launcher) Context(ctx context.Context) *Launcher {
ctx, cancel := context.WithCancel(ctx)
l.ctx = ctx
l.parser.Context(ctx)
l.ctxCancel = cancel
return l
}
// Set a command line argument when launching the browser.
// Be careful the first argument is a flag name, it shouldn't contain values. The values the will be joined with comma.
// A flag can have multiple values. If no values are provided the flag will be a boolean flag.
// You can use the [Launcher.FormatArgs] to debug the final CLI arguments.
// List of available flags: https://peter.sh/experiments/chromium-command-line-switches
func (l *Launcher) Set(name flags.Flag, values ...string) *Launcher {
name.Check()
l.Flags[name.NormalizeFlag()] = values
return l
}
// Get flag's first value.
func (l *Launcher) Get(name flags.Flag) string {
if list, has := l.GetFlags(name); has {
return list[0]
}
return ""
}
// Has flag or not.
func (l *Launcher) Has(name flags.Flag) bool {
_, has := l.GetFlags(name)
return has
}
// GetFlags from settings.
func (l *Launcher) GetFlags(name flags.Flag) ([]string, bool) {
flag, has := l.Flags[name.NormalizeFlag()]
return flag, has
}
// Append values to the flag.
func (l *Launcher) Append(name flags.Flag, values ...string) *Launcher {
flags, has := l.GetFlags(name)
if !has {
flags = []string{}
}
return l.Set(name, append(flags, values...)...)
}
// Delete a flag.
func (l *Launcher) Delete(name flags.Flag) *Launcher {
delete(l.Flags, name.NormalizeFlag())
return l
}
// Bin of the browser binary path to launch, if the path is not empty the auto download will be disabled.
func (l *Launcher) Bin(path string) *Launcher {
return l.Set(flags.Bin, path)
}
// Revision of the browser to auto download.
func (l *Launcher) Revision(rev int) *Launcher {
l.browser.Revision = rev
return l
}
// Headless switch. Whether to run browser in headless mode. A mode without visible UI.
func (l *Launcher) Headless(enable bool) *Launcher {
if enable {
return l.Set(flags.Headless)
}
return l.Delete(flags.Headless)
}
// HeadlessNew switch is the "--headless=new" switch: https://developer.chrome.com/docs/chromium/new-headless
func (l *Launcher) HeadlessNew(enable bool) *Launcher {
if enable {
return l.Set(flags.Headless, "new")
}
return l.Delete(flags.Headless)
}
// NoSandbox switch. Whether to run browser in no-sandbox mode.
// Linux users may face "running as root without --no-sandbox is not supported" in some Linux/Chrome combinations.
// This function helps switch mode easily.
// Be aware disabling sandbox is not trivial. Use at your own risk.
// Related doc: https://bugs.chromium.org/p/chromium/issues/detail?id=638180
func (l *Launcher) NoSandbox(enable bool) *Launcher {
if enable {
return l.Set(flags.NoSandbox)
}
return l.Delete(flags.NoSandbox)
}
// XVFB enables to run browser in by XVFB. Useful when you want to run headful mode on linux.
func (l *Launcher) XVFB(args ...string) *Launcher {
return l.Set(flags.XVFB, args...)
}
// Preferences set chromium user preferences, such as set the default search engine or disable the pdf viewer.
// The pref is a json string, the doc is here
// https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc
func (l *Launcher) Preferences(pref string) *Launcher {
return l.Set(flags.Preferences, pref)
}
// AlwaysOpenPDFExternally switch.
// It will set chromium user preferences to enable the always_open_pdf_externally option.
func (l *Launcher) AlwaysOpenPDFExternally() *Launcher {
return l.Set(flags.Preferences, `{"plugins":{"always_open_pdf_externally": true}}`)
}
// Leakless switch. If enabled, the browser will be force killed after the Go process exits.
// The doc of leakless: https://github.com/ysmood/leakless.
func (l *Launcher) Leakless(enable bool) *Launcher {
if enable {
return l.Set(flags.Leakless)
}
return l.Delete(flags.Leakless)
}
// Devtools switch to auto open devtools for each tab.
func (l *Launcher) Devtools(autoOpenForTabs bool) *Launcher {
if autoOpenForTabs {
return l.Set("auto-open-devtools-for-tabs")
}
return l.Delete("auto-open-devtools-for-tabs")
}
// IgnoreCerts configure the Chrome's ignore-certificate-errors-spki-list argument with the public keys.
func (l *Launcher) IgnoreCerts(pks []crypto.PublicKey) error {
spkis := make([]string, 0, len(pks))
for _, pk := range pks {
spki, err := certSPKI(pk)
if err != nil {
return fmt.Errorf("certSPKI: %w", err)
}
spkis = append(spkis, string(spki))
}
l.Set("ignore-certificate-errors-spki-list", spkis...)
return nil
}
// UserDataDir is where the browser will look for all of its state, such as cookie and cache.
// When set to empty, browser will use current OS home dir.
// Related doc: https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md
func (l *Launcher) UserDataDir(dir string) *Launcher {
if dir == "" {
l.Delete(flags.UserDataDir)
} else {
l.Set(flags.UserDataDir, dir)
}
return l
}
// ProfileDir is the browser profile the browser will use.
// When set to empty, the profile 'Default' is used.
// Related article: https://superuser.com/a/377195
func (l *Launcher) ProfileDir(dir string) *Launcher {
if dir == "" {
l.Delete(flags.ProfileDir)
} else {
l.Set(flags.ProfileDir, dir)
}
return l
}
// RemoteDebuggingPort to launch the browser. Zero for a random port. Zero is the default value.
// If it's not zero and the Launcher.Leakless is disabled, the launcher will try to reconnect to it first,
// if the reconnection fails it will launch a new browser.
func (l *Launcher) RemoteDebuggingPort(port int) *Launcher {
return l.Set(flags.RemoteDebuggingPort, fmt.Sprintf("%d", port))
}
// Proxy for the browser.
func (l *Launcher) Proxy(host string) *Launcher {
return l.Set(flags.ProxyServer, host)
}
// WindowSize for the browser.
func (l *Launcher) WindowSize(x, y int) *Launcher {
return l.Set(flags.WindowSize, fmt.Sprintf("%d,%d", x, y))
}
// WindowPosition for the browser.
func (l *Launcher) WindowPosition(x, y int) *Launcher {
return l.Set(flags.WindowPosition, fmt.Sprintf("%d,%d", x, y))
}
// WorkingDir to launch the browser process.
func (l *Launcher) WorkingDir(path string) *Launcher {
return l.Set(flags.WorkingDir, path)
}
// Env to launch the browser process. The default value is [os.Environ]().
// Usually you use it to set the timezone env. Such as:
//
// Env(append(os.Environ(), "TZ=Asia/Tokyo")...)
func (l *Launcher) Env(env ...string) *Launcher {
return l.Set(flags.Env, env...)
}
// StartURL to launch.
func (l *Launcher) StartURL(u string) *Launcher {
return l.Set("", u)
}
// FormatArgs returns the formatted arg list for cli.
func (l *Launcher) FormatArgs() []string {
execArgs := []string{}
for k, v := range l.Flags {
if k == flags.Arguments {
continue
}
if strings.HasPrefix(string(k), "rod-") {
continue
}
// fix a bug of chrome, if path is not absolute chrome will hang
if k == flags.UserDataDir {
abs, err := filepath.Abs(v[0])
utils.E(err)
v[0] = abs
}
str := "--" + string(k)
if v != nil {
str += "=" + strings.Join(v, ",")
}
execArgs = append(execArgs, str)
}
execArgs = append(execArgs, l.Flags[flags.Arguments]...)
sort.Strings(execArgs)
return execArgs
}
// Logger to handle stdout and stderr from browser.
// For example, pipe all browser output to stdout:
//
// launcher.New().Logger(os.Stdout)
func (l *Launcher) Logger(w io.Writer) *Launcher {
l.logger = w
return l
}
// MustLaunch is similar to Launch.
func (l *Launcher) MustLaunch() string {
u, err := l.Launch()
utils.E(err)
return u
}
// Launch a standalone temp browser instance and returns the debug url.
// bin and profileDir are optional, set them to empty to use the default values.
// If you want to reuse sessions, such as cookies, set the [Launcher.UserDataDir] to the same location.
//
// Please note launcher can only be used once.
func (l *Launcher) Launch() (string, error) {
if l.hasLaunched() {
return "", ErrAlreadyLaunched
}
defer l.ctxCancel()
bin, err := l.getBin()
if err != nil {
return "", err
}
l.setupUserPreferences()
var ll *leakless.Launcher
var cmd *exec.Cmd
args := l.FormatArgs()
if l.Has(flags.Leakless) && leakless.Support() {
ll = leakless.New()
cmd = ll.Command(bin, args...)
} else {
port := l.Get(flags.RemoteDebuggingPort)
u, err := ResolveURL(port)
if err == nil {
return u, nil
}
cmd = exec.Command(bin, args...)
}
l.setupCmd(cmd)
err = cmd.Start()
if err != nil {
return "", err
}
if ll == nil {
l.pid = cmd.Process.Pid
} else {
l.pid = <-ll.Pid()
if ll.Err() != "" {
return "", errors.New(ll.Err())
}
}
go func() {
_ = cmd.Wait()
close(l.exit)
}()
u, err := l.getURL()
if err != nil {
l.Kill()
return "", err
}
return ResolveURL(u)
}
func (l *Launcher) hasLaunched() bool {
return !atomic.CompareAndSwapInt32(&l.isLaunched, 0, 1)
}
func (l *Launcher) setupUserPreferences() {
userDir := l.Get(flags.UserDataDir)
pref := l.Get(flags.Preferences)
if userDir == "" || pref == "" {
return
}
userDir, err := filepath.Abs(userDir)
utils.E(err)
profile := l.Get(flags.ProfileDir)
if profile == "" {
profile = "Default"
}
path := filepath.Join(userDir, profile, "Preferences")
utils.E(utils.OutputFile(path, pref))
}
func (l *Launcher) setupCmd(cmd *exec.Cmd) {
l.osSetupCmd(cmd)
dir := l.Get(flags.WorkingDir)
env, _ := l.GetFlags(flags.Env)
cmd.Dir = dir
cmd.Env = env
cmd.Stdout = io.MultiWriter(l.logger, l.parser)
cmd.Stderr = io.MultiWriter(l.logger, l.parser)
}
func (l *Launcher) getBin() (string, error) {
bin := l.Get(flags.Bin)
if bin == "" {
l.browser.Context = l.ctx
return l.browser.Get()
}
return bin, nil
}
func (l *Launcher) getURL() (u string, err error) {
select {
case <-l.ctx.Done():
err = l.ctx.Err()
case u = <-l.parser.URL:
case <-l.exit:
err = l.parser.Err()
}
return
}
// PID returns the browser process pid.
func (l *Launcher) PID() int {
return l.pid
}
// Kill the browser process.
func (l *Launcher) Kill() {
// TODO: If kill too fast, the browser's children processes may not be ready.
// Browser don't have an API to tell if the children processes are ready.
utils.Sleep(1)
if l.PID() == 0 { // avoid killing the current process
return
}
killGroup(l.PID())
p, err := os.FindProcess(l.PID())
if err == nil {
_ = p.Kill()
}
}
// Cleanup wait until the Browser exits and remove [flags.UserDataDir].
func (l *Launcher) Cleanup() {
<-l.exit
dir := l.Get(flags.UserDataDir)
_ = os.RemoveAll(dir)
}