-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathbuildlet.go
1742 lines (1599 loc) · 48.7 KB
/
buildlet.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The buildlet is an HTTP server that untars content to disk and runs
// commands it has untarred, streaming their output back over HTTP.
// It is part of Go's continuous build system.
//
// This program intentionally allows remote code execution, and
// provides no security of its own. It is assumed that any user uses
// it with an appropriately-configured firewall between their VM
// instances.
package main // import "golang.org/x/build/cmd/buildlet"
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha1"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"cloud.google.com/go/compute/metadata"
"golang.org/x/build/buildlet"
"golang.org/x/build/envutil"
"golang.org/x/build/internal/httpdl"
"golang.org/x/build/pargzip"
)
var (
haltEntireOS = flag.Bool("halt", true, "halt OS in /halt handler. If false, the buildlet process just ends.")
rebootOnHalt = flag.Bool("reboot", false, "reboot system in /halt handler.")
workDir = flag.String("workdir", "", "Temporary directory to use. The contents of this directory may be deleted at any time. If empty, TempDir is used to create one.")
listenAddr = flag.String("listen", "AUTO", "address to listen on. Unused in reverse mode. Warning: this service is inherently insecure and offers no protection of its own. Do not expose this port to the world.")
reverse = flag.String("reverse", "", "[deprecated; use --reverse-type instead] if non-empty, go into reverse mode where the buildlet dials the coordinator instead of listening for connections. The value is a comma-separated list of modes, e.g. 'darwin-arm,darwin-amd64-race'")
reverseType = flag.String("reverse-type", "", "if non-empty, go into reverse mode where the buildlet dials the coordinator instead of listening for connections. The value is the dashboard/builders.go Hosts map key, naming a HostConfig. This buildlet will receive work for any BuildConfig specifying this named HostConfig.")
coordinator = flag.String("coordinator", "localhost:8119", "address of coordinator, in production use farmer.golang.org. Only used in reverse mode.")
hostname = flag.String("hostname", "", "hostname to advertise to coordinator for reverse mode; default is actual hostname")
)
// Bump this whenever something notable happens, or when another
// component needs a certain feature. This shows on the coordinator
// per reverse client, and is also accessible via the buildlet
// package's client API (via the Status method).
//
// Notable versions:
// 3: switched to revdial protocol
// 5: reverse dialing uses timeouts+tcp keepalives, pargzip fix
// 7: version bumps while debugging revdial hang (Issue 12816)
// 8: mac screensaver disabled
// 11: move from self-signed cert to LetsEncrypt (Issue 16442)
// 15: ssh support
// 16: make macstadium builders always haltEntireOS
// 17: make macstadium halts use sudo
const buildletVersion = 17
func defaultListenAddr() string {
if runtime.GOOS == "darwin" {
// Darwin will never run on GCE, so let's always
// listen on a high port (so we don't need to be
// root).
return ":5936"
}
if !metadata.OnGCE() {
return "localhost:5936"
}
// In production, default to port 80 or 443, depending on
// whether TLS is configured.
if metadataValue("tls-cert") != "" {
return ":443"
}
return ":80"
}
// Functionality set non-nil by some platforms:
var (
osHalt func()
configureSerialLogOutput func()
setOSRlimit func() error
)
func main() {
switch os.Getenv("GO_BUILDER_ENV") {
case "macstadium_vm":
configureMacStadium()
}
onGCE := metadata.OnGCE()
switch runtime.GOOS {
case "plan9":
log.SetOutput(&plan9LogWriter{w: os.Stderr})
case "linux":
if onGCE && !inKube {
if w, err := os.OpenFile("/dev/console", os.O_WRONLY, 0); err == nil {
log.SetOutput(w)
}
}
case "windows":
if onGCE {
configureSerialLogOutput()
}
}
log.Printf("buildlet starting.")
flag.Parse()
if *reverse == "solaris-amd64-smartosbuildlet" {
// These machines were setup without GO_BUILDER_ENV
// set in their base image, so do init work here after
// flag parsing instead of at top.
*rebootOnHalt = true
}
// Optimize emphemeral filesystems. Prefer speed over safety, since these machines
// will be gone soon.
switch runtime.GOOS {
case "openbsd", "freebsd", "netbsd":
makeBSDFilesystemFast()
}
if setOSRlimit != nil {
err := setOSRlimit()
if err != nil {
log.Fatalf("setOSRLimit: %v", err)
}
log.Printf("set OS rlimits.")
}
if *reverse != "" && *reverseType != "" {
log.Fatalf("can't specify both --reverse and --reverse-type")
}
isReverse := *reverse != "" || *reverseType != ""
if *listenAddr == "AUTO" && !isReverse {
v := defaultListenAddr()
log.Printf("Will listen on %s", v)
*listenAddr = v
}
if !onGCE && !isReverse && !strings.HasPrefix(*listenAddr, "localhost:") {
log.Printf("** WARNING *** This server is unsafe and offers no security. Be careful.")
}
if onGCE {
fixMTU()
}
if *workDir == "" && setWorkdirToTmpfs != nil {
setWorkdirToTmpfs()
}
if *workDir == "" {
switch runtime.GOOS {
case "windows":
// We want a short path on Windows, due to
// Windows issues with maximum path lengths.
*workDir = `C:\workdir`
if err := os.MkdirAll(*workDir, 0755); err != nil {
log.Fatalf("error creating workdir: %v", err)
}
default:
wdName := "workdir"
if *reverseType != "" {
wdName += "-" + *reverseType
}
dir := filepath.Join(os.TempDir(), wdName)
if err := os.RemoveAll(dir); err != nil { // should be no-op
log.Fatal(err)
}
if err := os.Mkdir(dir, 0755); err != nil {
log.Fatal(err)
}
*workDir = dir
}
}
os.Setenv("WORKDIR", *workDir) // mostly for demos
if _, err := os.Lstat(*workDir); err != nil {
log.Fatalf("invalid --workdir %q: %v", *workDir, err)
}
initGorootBootstrap()
http.HandleFunc("/", handleRoot)
http.HandleFunc("/debug/goroutines", handleGoroutines)
http.HandleFunc("/debug/x", handleX)
var password string
if !isReverse {
password = metadataValue("password")
}
requireAuth := func(handler func(w http.ResponseWriter, r *http.Request)) http.Handler {
return requirePasswordHandler{http.HandlerFunc(handler), password}
}
http.Handle("/writetgz", requireAuth(handleWriteTGZ))
http.Handle("/write", requireAuth(handleWrite))
http.Handle("/exec", requireAuth(handleExec))
http.Handle("/halt", requireAuth(handleHalt))
http.Handle("/tgz", requireAuth(handleGetTGZ))
http.Handle("/removeall", requireAuth(handleRemoveAll))
http.Handle("/workdir", requireAuth(handleWorkDir))
http.Handle("/status", requireAuth(handleStatus))
http.Handle("/ls", requireAuth(handleLs))
http.Handle("/connect-ssh", requireAuth(handleConnectSSH))
if !isReverse {
listenForCoordinator()
} else {
if err := dialCoordinator(); err != nil {
log.Fatalf("Error dialing coordinator: %v", err)
}
log.Printf("buildlet reverse mode exiting.")
os.Exit(0)
}
}
var inheritedGorootBootstrap string
func initGorootBootstrap() {
// Remember any GOROOT_BOOTSTRAP to use as a backup in handleExec
// if $WORKDIR/go1.4 ends up not existing.
inheritedGorootBootstrap = os.Getenv("GOROOT_BOOTSTRAP")
// Default if not otherwise configured in dashboard/builders.go:
os.Setenv("GOROOT_BOOTSTRAP", filepath.Join(*workDir, "go1.4"))
if runtime.GOOS == "solaris" && runtime.GOARCH == "amd64" {
gbenv := os.Getenv("GO_BUILDER_ENV")
if strings.Contains(gbenv, "oracle") {
// Oracle Solaris; not OpenSolaris-based or
// Illumos-based. Do nothing.
return
}
// Assume this is an OpenSolaris-based machine or a
// SmartOS/Illumos machine before GOOS=="illumos" split. For
// these machines, the old Joyent builders need to get the
// bootstrap and some config fixed.
os.Setenv("PATH", os.Getenv("PATH")+":/opt/local/bin")
downloadBootstrapGoroot("/root/go-solaris-amd64-bootstrap", "https://storage.googleapis.com/go-builder-data/gobootstrap-solaris-amd64.tar.gz")
}
if runtime.GOOS == "linux" && runtime.GOARCH == "ppc64" {
downloadBootstrapGoroot("/usr/local/go-bootstrap", "https://storage.googleapis.com/go-builder-data/gobootstrap-linux-ppc64.tar.gz")
}
}
func downloadBootstrapGoroot(destDir, url string) {
tarPath := destDir + ".tar.gz"
origInfo, err := os.Stat(tarPath)
if err != nil && !os.IsNotExist(err) {
log.Fatalf("Checking for tar existence: %v", err)
}
if err := httpdl.Download(tarPath, url); err != nil {
log.Fatalf("Downloading %s to %s: %v", url, tarPath, err)
}
newInfo, err := os.Stat(tarPath)
if err != nil {
log.Fatalf("Stat after download: %v", err)
}
if os.SameFile(origInfo, newInfo) {
// The file on disk was unmodified, so we probably untarred it already.
return
}
if err := os.RemoveAll(destDir); err != nil {
log.Fatal(err)
}
if err := os.MkdirAll(destDir, 0755); err != nil {
log.Fatal(err)
}
f, err := os.Open(tarPath)
if err != nil {
log.Fatalf("Opening after download: %v", err)
}
defer f.Close()
if err := untar(f, destDir); err != nil {
os.Remove(tarPath)
os.RemoveAll(destDir)
log.Fatalf("Untarring %s: %v", url, err)
}
}
func listenForCoordinator() {
tlsCert, tlsKey := metadataValue("tls-cert"), metadataValue("tls-key")
if (tlsCert == "") != (tlsKey == "") {
log.Fatalf("tls-cert and tls-key must both be supplied, or neither.")
}
log.Printf("Listening on %s ...", *listenAddr)
ln, err := net.Listen("tcp", *listenAddr)
if err != nil {
log.Fatalf("Failed to listen on %s: %v", *listenAddr, err)
}
ln = tcpKeepAliveListener{ln.(*net.TCPListener)}
var srv http.Server
if tlsCert != "" {
cert, err := tls.X509KeyPair([]byte(tlsCert), []byte(tlsKey))
if err != nil {
log.Fatalf("TLS cert error: %v", err)
}
tlsConf := &tls.Config{
Certificates: []tls.Certificate{cert},
}
ln = tls.NewListener(ln, tlsConf)
}
serveErr := make(chan error, 1)
go func() {
serveErr <- srv.Serve(ln)
}()
signalChan := make(chan os.Signal, 1)
if registerSignal != nil {
registerSignal(signalChan)
}
select {
case sig := <-signalChan:
log.Printf("received signal %v; shutting down gracefully.", sig)
case err := <-serveErr:
log.Fatalf("Serve: %v", err)
}
time.AfterFunc(5*time.Second, func() {
log.Printf("timeout shutting down gracefully; exiting immediately")
os.Exit(1)
})
if err := srv.Shutdown(context.Background()); err != nil {
log.Printf("Graceful shutdown error: %v; exiting immediately instead", err)
os.Exit(1)
}
log.Printf("graceful shutdown complete.")
os.Exit(0)
}
// registerSignal if non-nil registers shutdown signals with the provided chan.
var registerSignal func(chan<- os.Signal)
var inKube, _ = strconv.ParseBool(os.Getenv("IN_KUBERNETES"))
// metadataValue returns the GCE metadata instance value for the given key.
// If the metadata is not defined, the returned string is empty.
//
// If not running on GCE, it falls back to using environment variables
// for local development.
func metadataValue(key string) string {
// The common case (on GCE, but not in Kubernetes):
if metadata.OnGCE() && !inKube {
v, err := metadata.InstanceAttributeValue(key)
if _, notDefined := err.(metadata.NotDefinedError); notDefined {
return ""
}
if err != nil {
log.Fatalf("metadata.InstanceAttributeValue(%q): %v", key, err)
}
return v
}
// Else allow use of environment variables to fake
// metadata keys, for Kubernetes pods or local testing.
envKey := "META_" + strings.Replace(key, "-", "_", -1)
v := os.Getenv(envKey)
// Respect curl-style '@' prefix to mean the rest is a filename.
if strings.HasPrefix(v, "@") {
slurp, err := ioutil.ReadFile(v[1:])
if err != nil {
log.Fatalf("Error reading file for GCEMETA_%v: %v", key, err)
}
return string(slurp)
}
if v == "" {
log.Printf("Warning: not running on GCE, and no %v environment variable defined", envKey)
}
return v
}
// tcpKeepAliveListener is a net.Listener that sets TCP keep-alive
// timeouts on accepted connections.
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func fixMTU_freebsd() error { return fixMTU_ifconfig("vtnet0") }
func fixMTU_openbsd() error { return fixMTU_ifconfig("vio0") }
func fixMTU_ifconfig(iface string) error {
out, err := exec.Command("/sbin/ifconfig", iface, "mtu", "1460").CombinedOutput()
if err != nil {
return fmt.Errorf("/sbin/ifconfig %s mtu 1460: %v, %s", iface, err, out)
}
return nil
}
func fixMTU_plan9() error {
f, err := os.OpenFile("/net/ipifc/0/ctl", os.O_WRONLY, 0)
if err != nil {
return err
}
if _, err := io.WriteString(f, "mtu 1460\n"); err != nil {
f.Close()
return err
}
return f.Close()
}
func fixMTU() {
fn, ok := map[string]func() error{
"openbsd": fixMTU_openbsd,
"freebsd": fixMTU_freebsd,
"plan9": fixMTU_plan9,
}[runtime.GOOS]
if ok {
if err := fn(); err != nil {
log.Printf("Failed to set MTU: %v", err)
} else {
log.Printf("Adjusted MTU.")
}
}
}
// flushWriter is an io.Writer that Flushes after each Write if the
// underlying Writer implements http.Flusher.
type flushWriter struct {
rw http.ResponseWriter
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.rw.Write(p)
if f, ok := fw.rw.(http.Flusher); ok {
f.Flush()
}
return
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprintf(w, "buildlet running on %s-%s\n", runtime.GOOS, runtime.GOARCH)
}
// unauthenticated /debug/goroutines handler
func handleGoroutines(w http.ResponseWriter, r *http.Request) {
log.Printf("Dumping goroutines.")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
buf := make([]byte, 2<<20)
buf = buf[:runtime.Stack(buf, true)]
w.Write(buf)
log.Printf("Dumped goroutines.")
}
// unauthenticated /debug/x handler, to test MTU settings.
func handleX(w http.ResponseWriter, r *http.Request) {
n, _ := strconv.Atoi(r.FormValue("n"))
if n > 1<<20 {
n = 1 << 20
}
log.Printf("Dumping %d X.", n)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
buf := make([]byte, n)
for i := range buf {
buf[i] = 'X'
}
w.Write(buf)
log.Printf("Dumped X.")
}
// This is a remote code execution daemon, so security is kinda pointless, but:
func validRelativeDir(dir string) bool {
if strings.Contains(dir, `\`) || path.IsAbs(dir) {
return false
}
dir = path.Clean(dir)
if strings.HasPrefix(dir, "../") || strings.HasSuffix(dir, "/..") || dir == ".." {
return false
}
return true
}
func handleGetTGZ(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "requires GET method", http.StatusBadRequest)
return
}
dir := r.FormValue("dir")
if !validRelativeDir(dir) {
http.Error(w, "bogus dir", http.StatusBadRequest)
return
}
var zw io.WriteCloser
if r.FormValue("pargzip") == "0" {
zw = gzip.NewWriter(w)
} else {
zw = pargzip.NewWriter(w)
}
tw := tar.NewWriter(zw)
base := filepath.Join(*workDir, filepath.FromSlash(dir))
err := filepath.Walk(base, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
rel := strings.TrimPrefix(filepath.ToSlash(strings.TrimPrefix(path, base)), "/")
var linkName string
if fi.Mode()&os.ModeSymlink != 0 {
linkName, err = os.Readlink(path)
if err != nil {
return err
}
}
th, err := tar.FileInfoHeader(fi, linkName)
if err != nil {
return err
}
th.Name = rel
if fi.IsDir() && !strings.HasSuffix(th.Name, "/") {
th.Name += "/"
}
if th.Name == "/" {
return nil
}
if err := tw.WriteHeader(th); err != nil {
return err
}
if fi.Mode().IsRegular() {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return err
}
}
return nil
})
if err != nil {
log.Printf("Walk error: %v", err)
panic(http.ErrAbortHandler)
}
tw.Close()
zw.Close()
}
func handleWriteTGZ(w http.ResponseWriter, r *http.Request) {
urlParam, _ := url.ParseQuery(r.URL.RawQuery)
baseDir := *workDir
if dir := urlParam.Get("dir"); dir != "" {
if !validRelativeDir(dir) {
log.Printf("writetgz: bogus dir %q", dir)
http.Error(w, "bogus dir", http.StatusBadRequest)
return
}
dir = filepath.FromSlash(dir)
baseDir = filepath.Join(baseDir, dir)
// Special case: if the directory is "go1.4" and it already exists, do nothing.
// This lets clients do a blind write to it and not do extra work.
if r.Method == "POST" && dir == "go1.4" {
if fi, err := os.Stat(baseDir); err == nil && fi.IsDir() {
log.Printf("writetgz: skipping URL puttar to go1.4 dir; already exists")
io.WriteString(w, "SKIP")
return
}
}
if err := os.MkdirAll(baseDir, 0755); err != nil {
log.Printf("writetgz: %v", err)
http.Error(w, "mkdir of base: "+err.Error(), http.StatusInternalServerError)
return
}
}
var tgz io.Reader
var urlStr string
switch r.Method {
case "PUT":
tgz = r.Body
log.Printf("writetgz: untarring Request.Body into %s", baseDir)
case "POST":
urlStr = r.FormValue("url")
if urlStr == "" {
log.Printf("writetgz: missing url POST param")
http.Error(w, "missing url POST param", http.StatusBadRequest)
return
}
t0 := time.Now()
res, err := http.Get(urlStr)
if err != nil {
log.Printf("writetgz: failed to fetch tgz URL %s: %v", urlStr, err)
http.Error(w, fmt.Sprintf("fetching URL %s: %v", urlStr, err), http.StatusInternalServerError)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("writetgz: failed to fetch tgz URL %s: status=%v", urlStr, res.Status)
http.Error(w, fmt.Sprintf("writetgz: fetching provided URL %q: %s", urlStr, res.Status), http.StatusInternalServerError)
return
}
tgz = res.Body
log.Printf("writetgz: untarring %s (got headers in %v) into %s", urlStr, time.Since(t0), baseDir)
default:
log.Printf("writetgz: invalid method %q", r.Method)
http.Error(w, "requires PUT or POST method", http.StatusBadRequest)
return
}
err := untar(tgz, baseDir)
if err != nil {
status := http.StatusInternalServerError
if he, ok := err.(httpStatuser); ok {
status = he.httpStatus()
}
http.Error(w, err.Error(), status)
return
}
io.WriteString(w, "OK")
}
func handleWrite(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
http.Error(w, "requires POST method", http.StatusBadRequest)
return
}
param, _ := url.ParseQuery(r.URL.RawQuery)
path := param.Get("path")
if path == "" || !validRelPath(path) {
http.Error(w, "bad path", http.StatusBadRequest)
return
}
path = filepath.FromSlash(path)
path = filepath.Join(*workDir, path)
modeInt, err := strconv.ParseInt(param.Get("mode"), 10, 64)
mode := os.FileMode(modeInt)
if err != nil || !mode.IsRegular() {
http.Error(w, "bad mode", http.StatusBadRequest)
return
}
// Make the directory if it doesn't exist.
// TODO(adg): support dirmode parameter?
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := writeFile(r.Body, path, mode); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(w, "OK")
}
func writeFile(r io.Reader, path string, mode os.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
if _, err := io.Copy(f, r); err != nil {
f.Close()
return err
}
// Try to set the mode again, in case the file already existed.
if runtime.GOOS != "windows" {
if err := f.Chmod(mode); err != nil {
f.Close()
return err
}
}
return f.Close()
}
// untar reads the gzip-compressed tar file from r and writes it into dir.
func untar(r io.Reader, dir string) (err error) {
t0 := time.Now()
nFiles := 0
madeDir := map[string]bool{}
defer func() {
td := time.Since(t0)
if err == nil {
log.Printf("extracted tarball into %s: %d files, %d dirs (%v)", dir, nFiles, len(madeDir), td)
} else {
log.Printf("error extracting tarball into %s after %d files, %d dirs, %v: %v", dir, nFiles, len(madeDir), td, err)
}
}()
zr, err := gzip.NewReader(r)
if err != nil {
return badRequest("requires gzip-compressed body: " + err.Error())
}
tr := tar.NewReader(zr)
loggedChtimesError := false
for {
f, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
log.Printf("tar reading error: %v", err)
return badRequest("tar error: " + err.Error())
}
if f.Typeflag == tar.TypeXGlobalHeader {
// golang.org/issue/22748: git archive exports
// a global header ('g') which after Go 1.9
// (for a bit?) contained an empty filename.
// Ignore it.
continue
}
if !validRelPath(f.Name) {
return badRequest(fmt.Sprintf("tar file contained invalid name %q", f.Name))
}
rel := filepath.FromSlash(f.Name)
abs := filepath.Join(dir, rel)
fi := f.FileInfo()
mode := fi.Mode()
switch {
case mode.IsRegular():
// Make the directory. This is redundant because it should
// already be made by a directory entry in the tar
// beforehand. Thus, don't check for errors; the next
// write will fail with the same error.
dir := filepath.Dir(abs)
if !madeDir[dir] {
if err := os.MkdirAll(filepath.Dir(abs), 0755); err != nil {
return err
}
madeDir[dir] = true
}
wf, err := os.OpenFile(abs, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return err
}
n, err := io.Copy(wf, tr)
if closeErr := wf.Close(); closeErr != nil && err == nil {
err = closeErr
}
if err != nil {
return fmt.Errorf("error writing to %s: %v", abs, err)
}
if n != f.Size {
return fmt.Errorf("only wrote %d bytes to %s; expected %d", n, abs, f.Size)
}
modTime := f.ModTime
if modTime.After(t0) {
// Clamp modtimes at system time. See
// golang.org/issue/19062 when clock on
// buildlet was behind the gitmirror server
// doing the git-archive.
modTime = t0
}
if !modTime.IsZero() {
if err := os.Chtimes(abs, modTime, modTime); err != nil && !loggedChtimesError {
// benign error. Gerrit doesn't even set the
// modtime in these, and we don't end up relying
// on it anywhere (the gomote push command relies
// on digests only), so this is a little pointless
// for now.
log.Printf("error changing modtime: %v (further Chtimes errors suppressed)", err)
loggedChtimesError = true // once is enough
}
}
nFiles++
case mode.IsDir():
if err := os.MkdirAll(abs, 0755); err != nil {
return err
}
madeDir[abs] = true
default:
return badRequest(fmt.Sprintf("tar file entry %s contained unsupported file type %v", f.Name, mode))
}
}
return nil
}
// Process-State is an HTTP Trailer set in the /exec handler to "ok"
// on success, or os.ProcessState.String() on failure.
const hdrProcessState = "Process-State"
func handleExec(w http.ResponseWriter, r *http.Request) {
cn := w.(http.CloseNotifier)
clientGone := cn.CloseNotify()
handlerDone := make(chan bool)
defer close(handlerDone)
if r.Method != "POST" {
http.Error(w, "requires POST method", http.StatusBadRequest)
return
}
if r.ProtoMajor*10+r.ProtoMinor < 11 {
// We need trailers, only available in HTTP/1.1 or HTTP/2.
http.Error(w, "HTTP/1.1 or higher required", http.StatusBadRequest)
return
}
w.Header().Set("Trailer", hdrProcessState) // declare it so we can set it
cmdPath := r.FormValue("cmd") // required
absCmd := cmdPath
dir := r.FormValue("dir") // optional
sysMode := r.FormValue("mode") == "sys"
debug, _ := strconv.ParseBool(r.FormValue("debug"))
if sysMode {
if cmdPath == "" {
http.Error(w, "requires 'cmd' parameter", http.StatusBadRequest)
return
}
if dir == "" {
dir = *workDir
} else {
dir = filepath.FromSlash(dir)
if !filepath.IsAbs(dir) {
dir = filepath.Join(*workDir, dir)
}
}
} else {
if !validRelPath(cmdPath) {
http.Error(w, "requires 'cmd' parameter", http.StatusBadRequest)
return
}
absCmd = filepath.Join(*workDir, filepath.FromSlash(cmdPath))
if dir == "" {
dir = filepath.Dir(absCmd)
} else {
if !validRelPath(dir) {
http.Error(w, "bogus 'dir' parameter", http.StatusBadRequest)
return
}
dir = filepath.Join(*workDir, filepath.FromSlash(dir))
}
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
goarch := "amd64" // unless we find otherwise
for _, pair := range r.PostForm["env"] {
if hasPrefixFold(pair, "GOARCH=") {
goarch = pair[len("GOARCH="):]
}
}
env := append(baseEnv(goarch), r.PostForm["env"]...)
// Set TMPDIR in the child process and clean up after it.
// Do this at least for Solaris (golang.org/issue/22798)
// because Solaris reuses its disk per run (for now). The other builders
// generally run in their own containers/VMs and thus don't leak.
// Ideally Solaris would do the same and we wouldn't need this.
if builder := getEnv(env, "GO_BUILDER_NAME"); builder == "solaris-amd64-smartosbuildlet" {
childTmp, err := ioutil.TempDir("", "buildlet-exec")
if err != nil {
// Not critical. Not worth dying over. (at least for now)
log.Printf("failed to create a temp directory: %v", err)
} else {
env = append(env, "TMPDIR="+childTmp)
defer os.RemoveAll(childTmp)
}
}
env = envutil.Dedup(runtime.GOOS == "windows", env)
// Prefer buildlet process's inherited GOROOT_BOOTSTRAP if
// there was one and the one we're about to use doesn't exist.
if v := getEnv(env, "GOROOT_BOOTSTRAP"); v != "" && inheritedGorootBootstrap != "" && pathNotExist(v) {
env = envutil.Dedup(runtime.GOOS == "windows", append(env,
"GOROOT_BOOTSTRAP="+inheritedGorootBootstrap))
}
env = setPathEnv(env, r.PostForm["path"], *workDir)
cmd := exec.Command(absCmd, r.PostForm["cmdArg"]...)
cmd.Dir = dir
cmdOutput := flushWriter{w}
cmd.Stdout = cmdOutput
cmd.Stderr = cmdOutput
cmd.Env = env
log.Printf("[%p] Running %s with args %q and env %q in dir %s",
cmd, cmd.Path, cmd.Args, cmd.Env, cmd.Dir)
if debug {
fmt.Fprintf(cmdOutput, ":: Running %s with args %q and env %q in dir %s\n\n",
cmd.Path, cmd.Args, cmd.Env, cmd.Dir)
}
t0 := time.Now()
err := cmd.Start()
if err == nil {
go func() {
select {
case <-clientGone:
err := killProcessTree(cmd.Process)
if err != nil {
log.Printf("Kill failed: %v", err)
}
case <-handlerDone:
return
}
}()
err = cmd.Wait()
}
state := "ok"
if err != nil {
if ps := cmd.ProcessState; ps != nil {
state = ps.String()
} else {
state = err.Error()
}
}
w.Header().Set(hdrProcessState, state)
log.Printf("[%p] Run = %s, after %v", cmd, state, time.Since(t0))
}
// pathNotExist reports whether path does not exist.
func pathNotExist(path string) bool {
_, err := os.Stat(path)
return os.IsNotExist(err)
}
func getEnv(env []string, key string) string {
for _, kv := range env {
if len(kv) <= len(key) || kv[len(key)] != '=' {
continue
}
if runtime.GOOS == "windows" {
// Case insensitive.
if strings.EqualFold(kv[:len(key)], key) {
return kv[len(key)+1:]
}
} else {
// Case sensitive.
if kv[:len(key)] == key {
return kv[len(key)+1:]
}
}
}
return ""
}
// setPathEnv returns a copy of the provided environment with any existing
// PATH variables replaced by the user-provided path.
// These substitutions are applied to user-supplied path elements:
// - the string "$PATH" expands to the original PATH elements
// - the substring "$WORKDIR" expands to the provided workDir
// A path of just ["$EMPTY"] removes the PATH variable from the environment.
func setPathEnv(env, path []string, workDir string) []string {
if len(path) == 0 {
return env
}
var (
pathIdx = -1
pathOrig = ""
)
for i, s := range env {
if isPathEnvPair(s) {
pathIdx = i
pathOrig = s[len("PaTh="):] // in whatever case
break
}
}
if len(path) == 1 && path[0] == "$EMPTY" {
// Remove existing path variable if it exists.
if pathIdx >= 0 {
env = append(env[:pathIdx], env[pathIdx+1:]...)
}
return env
}
// Apply substitions to a copy of the path argument.
path = append([]string{}, path...)