-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
572 lines (527 loc) · 13.2 KB
/
main.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
567
568
569
570
571
572
package main
import (
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"text/template"
"time"
"github.com/phayes/freeport"
"github.com/skratchdot/open-golang/open"
"github.com/zippoxer/george/forge"
kingpin "github.com/zippoxer/kingpin"
)
var (
// encryptionKey is used to encrypt Forge's API key before saving it.
encryptionKey = &[32]byte{0xfb, 0xb7, 0x41, 0xbf, 0xb2, 0xe5, 0x8, 0xb8, 0x3e, 0x6e, 0x4, 0x5f, 0x39, 0x2c, 0x55, 0xb9, 0xa1, 0x4e, 0xbb, 0x72, 0x5a, 0xd7, 0xa0, 0xe1, 0xb3, 0x83, 0x11, 0xeb, 0x98, 0xd7, 0x19, 0xce}
)
var (
app = kingpin.New("george", "A toolkit for Laravel Forge.")
appLogin = app.Command("login",
"Login with API key provided at https://forge.laravel.com/user/profile#/api")
appLoginKey = appLogin.Arg("api-key", "").Required().String()
appSSH = app.Command("ssh",
"SSH to a server by name, IP or site domain. Wildcards are supported.")
appSSHTarget = appSSH.
Arg("server", "Server name, IP or site domain.").
Required().
HintAction(hintTargets(hintAll)).
String()
appTunnel = app.Command("tunnel",
"Opens an SSH tunnel that forwards a server's port a local port.")
appTunnelTarget = appTunnel.
Arg("target", "Server name, IP or site domain.").
Required().
HintAction(hintTargets(hintAll)).
String()
appTunnelRemote = appTunnel.
Arg("remote-port", "").
Default("3306").
Uint16()
appTunnelLocal = appTunnel.
Arg("local-port", "").
Default("3307").
Uint16()
appMySQLDump = app.Command("mysqldump", "mysqldump a website.")
appMySQLDumpSite = appMySQLDump.
Arg("site", "Site name.").
Required().
HintAction(hintTargets(hintSites)).
String()
appLog = app.Command("log", "Print the latest Laravel application log.")
appLogSite = appLog.
Arg("site", "Site name.").
Required().
HintAction(hintTargets(hintSites)).
String()
appSequelPro = app.Command("sequelpro", "Open a site's database in Sequel Pro.")
appSequelProSite = appSequelPro.
Arg("site", "Site name.").
Required().
HintAction(hintTargets(hintSites)).
String()
appWinSCP = app.Command("winscp", "Opens an SFTP connection to a site or server in WinSCP.")
appWinSCPTarget = appWinSCP.
Arg("target", "Server name, IP or site domain.").
Required().
HintAction(hintTargets(hintSites)).
String()
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
app.HelpFlag.Hidden()
cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
key, err := loadAPIKey()
if os.IsNotExist(err) {
if cmd != "login" {
log.Fatal("You're not logged in. Login with 'george <api-key>'")
}
} else if err != nil {
log.Fatal(err)
}
client := forge.New(key)
george, err := New(client, time.Minute)
if err != nil {
log.Fatal(err)
}
switch cmd {
case appLogin.FullCommand():
err = saveAPIKey(*appLoginKey)
if err != nil {
log.Fatal(err)
}
case appLog.FullCommand():
server, site, err := george.SearchSite(*appLogSite)
if err != nil {
log.Fatal(err)
}
session, err := george.SSH(server.Id)
if err != nil {
log.Fatal(err)
}
session.Stderr = os.Stderr
pr, err := session.StdoutPipe()
if err != nil {
log.Fatal(err)
}
cmd := fmt.Sprintf("cat %q | gzip", site.Name+"/storage/logs/laravel.log")
if err := session.Start(cmd); err != nil {
log.Fatalf("%s: %v", cmd, err)
}
gzr, err := gzip.NewReader(pr)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(os.Stdout, gzr); err != nil {
log.Fatal(err)
}
if err := session.Wait(); err != nil {
log.Fatalf("%s: %v", cmd, err)
}
case appTunnel.FullCommand():
server, site, err := george.Search(*appTunnelTarget)
if err != nil {
log.Fatal(err)
}
if site != nil && *appTunnelRemote == 3306 {
go func() {
env, err := client.Env(server.Id, site.Id).Get()
if err != nil {
fmt.Printf("failed fetching .env: %v\n", err)
}
dbConn := env.Get("DB_CONNECTION")
dbHost := env.Get("DB_HOST")
dbPort := env.Get("DB_PORT")
dbName := env.Get("DB_DATABASE")
dbUser := env.Get("DB_USERNAME")
dbPwd := env.Get("DB_PASSWORD")
fmt.Printf("\n%s credentials for %s:\n", dbConn, site.Name)
fmt.Printf(" host: %s:%s\n user: %s\n password: %s\n database: %s\n",
dbHost, dbPort, dbUser, dbPwd, dbName)
}()
}
err = george.SSHInstallKey(server.Id)
if err != nil {
log.Fatal(err)
}
fmt.Printf("tunneling %s:%d to 127.0.0.1:%d\n",
server.IPAddress, *appTunnelRemote, *appTunnelLocal)
cmd := exec.Command("ssh",
"-L",
fmt.Sprintf("%d:%s:%d", *appTunnelLocal, server.IPAddress, *appTunnelRemote),
"-N",
fmt.Sprintf("forge@%s", server.IPAddress))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
<-c
cmd.Process.Kill()
os.Exit(1)
}()
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
case appSSH.FullCommand():
server, site, err := george.Search(*appSSHTarget)
if err != nil {
log.Fatal(err)
}
err = george.SSHInstallKey(server.Id)
if err != nil {
log.Fatal(err)
}
var flags, args []string
args = append(args, "forge@"+server.IPAddress)
if site != nil {
flags = append(flags, "-t")
args = append(args, fmt.Sprintf("cd %q; bash -l", site.Name))
}
cmd := exec.Command("ssh", append(flags, args...)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
case appMySQLDump.FullCommand():
server, site, err := george.SearchSite(*appMySQLDumpSite)
if err != nil {
log.Fatal(err)
}
// Parse .env file and extract MySQL connection settings.
env, err := client.Env(server.Id, site.Id).Get()
if err != nil {
log.Fatal(err)
}
if env.Get("DB_NAME") == "" {
// Not WordPress, try Laravel:
dbConn, _ := env["DB_CONNECTION"]
if dbConn == "" {
log.Fatal("No database found for this site.")
}
if dbConn != "mysql" {
log.Fatalf("Unsupported database %s", dbConn)
}
}
dbHost := env.Get("DB_HOST")
dbPort := env.Get("DB_PORT")
if dbPort == "" {
dbPort = "3306"
}
dbName := env.Get("DB_DATABASE", "DB_NAME")
dbUser := env.Get("DB_USERNAME", "DB_USER")
dbPwd := env.Get("DB_PASSWORD")
// Open an SSH session and execute mysqldump.
session, err := george.SSH(server.Id)
if err != nil {
log.Fatal(err)
}
session.Stderr = os.Stderr
pr, err := session.StdoutPipe()
if err != nil {
log.Fatal(err)
}
cmd := fmt.Sprintf("mysqldump --host=%q --port=%q --user=%q --password=%q %q | gzip",
dbHost, dbPort, dbUser, dbPwd, dbName)
if err := session.Start(cmd); err != nil {
log.Fatalf("mysqldump: %v", err)
}
gzr, err := gzip.NewReader(pr)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(os.Stdout, gzr); err != nil {
log.Fatal(err)
}
if err := session.Wait(); err != nil {
log.Fatalf("mysqldump: %v", err)
}
case appSequelPro.FullCommand():
server, site, err := george.SearchSite(*appSequelProSite)
if err != nil {
log.Fatal(err)
}
// Parse .env file and extract MySQL connection settings.
env, err := client.Env(server.Id, site.Id).Get()
if err != nil {
log.Fatal(err)
}
dbConn, _ := env["DB_CONNECTION"]
if dbConn == "" {
log.Fatal("No database found for this site.")
}
if dbConn != "mysql" {
log.Fatalf("Unsupported database %s", dbConn)
}
dbPort := env.Get("DB_PORT")
dbName := env.Get("DB_DATABASE")
dbUser := env.Get("DB_USERNAME")
dbPwd := env.Get("DB_PASSWORD")
// Open an SSH session and execute mysqldump.
err = george.SSHInstallKey(server.Id)
if err != nil {
log.Fatal(err)
}
localPort, err := freeport.GetFreePort()
if err != nil {
log.Fatal(err)
}
fmt.Printf("tunneling for database %s:%s to 127.0.0.1:%d\n",
server.IPAddress, dbPort, localPort)
cmd := exec.Command("ssh",
"-L",
fmt.Sprintf("%d:%s:%s", localPort, server.IPAddress, dbPort),
"-N",
fmt.Sprintf("forge@%s", server.IPAddress))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
<-c
cmd.Process.Kill()
os.Exit(1)
}()
go func() {
time.Sleep(1 * time.Second)
fmt.Printf("Opening database in Sequel Pro...")
const fileTemplate = `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ContentFilters</key>
<dict/>
<key>auto_connect</key>
<true/>
<key>data</key>
<dict>
<key>connection</key>
<dict>
<key>colorIndex</key>
<integer>0</integer>
<key>database</key>
<string>{{.DbName}}</string>
<key>host</key>
<string>127.0.0.1</string>
<key>name</key>
<string>{{.SiteName}}</string>
<key>password</key>
<string>{{.DbPwd}}</string>
<key>port</key>
<string>{{.LocalPort}}</string>
<key>rdbms_type</key>
<string>mysql</string>
<key>sslCACertFileLocation</key>
<string></string>
<key>sslCACertFileLocationEnabled</key>
<integer>0</integer>
<key>sslCertificateFileLocation</key>
<string></string>
<key>sslCertificateFileLocationEnabled</key>
<integer>0</integer>
<key>sslKeyFileLocation</key>
<string></string>
<key>sslKeyFileLocationEnabled</key>
<integer>0</integer>
<key>type</key>
<string>SPTCPIPConnection</string>
<key>useSSL</key>
<integer>0</integer>
<key>user</key>
<string>{{.DbUser}}</string>
</dict>
</dict>
<key>encrypted</key>
<false/>
<key>format</key>
<string>connection</string>
<key>queryFavorites</key>
<array/>
<key>queryHistory</key>
<array />
<key>rdbms_type</key>
<string>mysql</string>
<key>rdbms_version</key>
<string>5.6.10</string>
<key>version</key>
<integer>1</integer>
</dict>
</plist>
`
t := template.Must(template.New("spf").Parse(fileTemplate))
file, err := os.Create(os.TempDir() + site.Name + ".spf")
if err != nil {
log.Fatal(err)
}
t.Execute(file, struct {
DbName string
DbPwd string
DbUser string
LocalPort int
SiteName string
}{
dbName,
dbPwd,
dbUser,
localPort,
site.Name,
})
file.Close()
open.Run(file.Name())
}()
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
case appWinSCP.FullCommand():
winscpPaths := []string{
`C:\Program Files (x86)\WinSCP\WinSCP.exe`,
`C:\Program Files\WinSCP\WinSCP.exe`,
}
var path string
for _, p := range winscpPaths {
if _, err := os.Stat(p); err == nil {
path = p
}
}
if path == "" {
log.Fatal("WinSCP.exe does not exist.")
}
server, site, err := george.Search(*appWinSCPTarget)
if err != nil {
log.Fatal(err)
}
err = george.SSHInstallKey(server.Id)
if err != nil {
log.Fatal(err)
}
// Generate PPK (if not exists) using WinSCP.
privateKeyPath := george.SSHPrivateKeyPath()
ppkPath := privateKeyPath + ".ppk"
if _, err := os.Stat(ppkPath); err != nil {
cmd := exec.Command(
path,
"/keygen",
privateKeyPath,
fmt.Sprintf(`/output=%s`, ppkPath),
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
}
// Start WinSCP to open the connection to the given server.
connURL := &url.URL{
Scheme: "sftp",
User: url.User("forge"),
Host: server.IPAddress,
Path: "/",
}
args := []string{
connURL.String(),
"/privatekey=" + ppkPath,
}
if site != nil {
args = append(args, "/rawsettings", "RemoteDirectory=/home/forge/"+site.Name)
}
cmd := exec.Command(
path,
args...,
)
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
default:
app.FatalUsage("No command specified.")
}
return
}
func saveAPIKey(key string) error {
ciphertext, err := Encrypt([]byte(key), encryptionKey)
if err != nil {
return err
}
usr, err := user.Current()
if err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(usr.HomeDir, ".george-key"), ciphertext, 0644)
}
func loadAPIKey() (string, error) {
path, err := apiKeyPath()
if err != nil {
return "", err
}
ciphertext, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
key, err := Decrypt(ciphertext, encryptionKey)
if err != nil {
return "", err
}
return string(key), nil
}
func apiKeyPath() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
return filepath.Join(usr.HomeDir, ".george-key"), nil
}
type hintType int
const (
hintServers hintType = iota
hintSites
hintAll
)
func hintTargets(hintType hintType) func() []string {
return func() []string {
key, err := loadAPIKey()
if err != nil {
return nil
}
g, err := New(forge.New(key), cacheForever)
if err != nil {
return nil
}
var list []string
if hintType == hintAll || hintType == hintServers {
servers, err := g.cache.Servers()
if err != nil {
return nil
}
for _, s := range servers {
list = append(list, s.Name)
list = append(list, s.IPAddress)
}
}
if hintType == hintAll || hintType == hintSites {
sites, err := g.cache.ServerSites(nil)
if err != nil {
return nil
}
for _, server := range sites {
for _, site := range server.Sites {
list = append(list, site.Name)
}
}
}
return list
}
}