-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
supervisor.go
1847 lines (1612 loc) · 52.1 KB
/
supervisor.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 (c) 2020 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License.AGPL.txt in the project root for license information.
package supervisor
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"math"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/gorilla/websocket"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
grpcruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"github.com/prometheus/common/route"
"github.com/soheilhy/cmux"
"golang.org/x/crypto/ssh"
"golang.org/x/xerrors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/gitpod-io/gitpod/common-go/analytics"
"github.com/gitpod-io/gitpod/common-go/experiments"
"github.com/gitpod-io/gitpod/common-go/log"
"github.com/gitpod-io/gitpod/common-go/pprof"
csapi "github.com/gitpod-io/gitpod/content-service/api"
"github.com/gitpod-io/gitpod/content-service/pkg/executor"
"github.com/gitpod-io/gitpod/content-service/pkg/git"
gitpod "github.com/gitpod-io/gitpod/gitpod-protocol"
"github.com/gitpod-io/gitpod/supervisor/api"
"github.com/gitpod-io/gitpod/supervisor/pkg/config"
"github.com/gitpod-io/gitpod/supervisor/pkg/dropwriter"
"github.com/gitpod-io/gitpod/supervisor/pkg/metrics"
"github.com/gitpod-io/gitpod/supervisor/pkg/ports"
"github.com/gitpod-io/gitpod/supervisor/pkg/serverapi"
"github.com/gitpod-io/gitpod/supervisor/pkg/terminal"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/pushgateway/handler"
"github.com/prometheus/pushgateway/storage"
)
const (
gitpodUID = 33333
gitpodUserName = "gitpod"
gitpodGID = 33333
gitpodGroupName = "gitpod"
desktopIDEPort = 24000
debugProxyPort = 23003
)
var (
additionalServices []RegisterableService
apiEndpointOpts []grpc.ServerOption
Version = ""
)
// RegisterAdditionalService registers additional services for the API endpoint
// of supervisor.
func RegisterAdditionalService(services ...RegisterableService) {
additionalServices = append(additionalServices, services...)
}
// AddAPIEndpointOpts adds additional grpc server options for the API endpoint.
func AddAPIEndpointOpts(opts ...grpc.ServerOption) {
apiEndpointOpts = append(apiEndpointOpts, opts...)
}
type runOptions struct {
Args []string
RunGP bool
}
// RunOption customizes the run behaviour.
type RunOption func(*runOptions)
// WithArgs sets the arguments passed to Run.
func WithArgs(args []string) RunOption {
return func(r *runOptions) {
r.Args = args
}
}
// WithRunGP disables some functionality for use with run-gp
func WithRunGP(enable bool) RunOption {
return func(r *runOptions) {
r.RunGP = enable
}
}
// The sum of those timeBudget* times has to fit within the terminationGracePeriod of the workspace pod.
const (
timeBudgetIDEShutdown = 15 * time.Second
)
const (
// KindGit marks any kind of Git access token.
KindGit = "git"
)
type ShutdownReason int16
const (
ShutdownReasonSuccess ShutdownReason = 0
ShutdownReasonExecutionError ShutdownReason = 1
)
type IDEKind int64
const (
WebIDE IDEKind = iota
DesktopIDE
)
func (s IDEKind) String() string {
switch s {
case WebIDE:
return "web"
case DesktopIDE:
return "desktop"
}
return "unknown"
}
var childProcEnvvars []string
// Run serves as main entrypoint to the supervisor.
func Run(options ...RunOption) {
exitCode := 0
defer handleExit(&exitCode)
defer func() {
r := recover()
if r == nil {
return
}
log.WithField("cause", r).WithField("stack", string(debug.Stack())).Error("panicked")
if exitCode == 0 {
exitCode = 1
}
}()
opts := runOptions{
Args: os.Args,
}
for _, o := range options {
o(&opts)
}
cfg, err := GetConfig()
if err != nil {
log.WithError(err).Fatal("configuration error")
}
if len(os.Args) < 2 || os.Args[1] != "run" {
fmt.Println("supervisor makes sure your workspace/IDE keeps running smoothly.\nYou don't have to call this thing, Gitpod calls it for you.")
return
}
// BEWARE: we can only call buildChildProcEnv once, because it might download env vars from a one-time-secret
// URL, which would fail if we tried another time.
childProcEnvvars = buildChildProcEnv(cfg, nil, opts.RunGP)
err = AddGitpodUserIfNotExists()
if err != nil {
log.WithError(err).Fatal("cannot ensure Gitpod user exists")
}
symlinkBinaries(cfg)
configureGit(cfg)
telemetry := analytics.NewFromEnvironment()
defer telemetry.Close()
tokenService := NewInMemoryTokenService()
if !opts.RunGP {
tkns, err := cfg.GetTokens(true)
if err != nil {
log.WithError(err).Warn("cannot prepare tokens")
}
for i := range tkns {
_, err = tokenService.SetToken(context.Background(), &tkns[i].SetTokenRequest)
if err != nil {
log.WithError(err).Warn("cannot prepare tokens")
}
}
}
tunneledPortsService := ports.NewTunneledPortsService(cfg.DebugEnable)
_, err = tunneledPortsService.Tunnel(context.Background(),
&ports.TunnelOptions{
SkipIfExists: false,
},
&ports.PortTunnelDescription{
LocalPort: uint32(cfg.APIEndpointPort),
TargetPort: uint32(cfg.APIEndpointPort),
Visibility: api.TunnelVisiblity_host,
},
&ports.PortTunnelDescription{
LocalPort: uint32(cfg.SSHPort),
TargetPort: uint32(cfg.SSHPort),
Visibility: api.TunnelVisiblity_host,
},
)
if err != nil {
log.WithError(err).Warn("cannot tunnel internal ports")
}
ctx, cancel := context.WithCancel(context.Background())
internalPorts := []uint32{uint32(cfg.IDEPort), uint32(cfg.APIEndpointPort), uint32(cfg.SSHPort)}
if cfg.GetDesktopIDE() != nil {
internalPorts = append(internalPorts, desktopIDEPort)
}
if cfg.isDebugWorkspace() {
internalPorts = append(internalPorts, debugProxyPort)
}
endpoint, host, err := cfg.GitpodAPIEndpoint()
if err != nil {
log.WithError(err).Fatal("cannot find Gitpod API endpoint")
}
experimentsClientOpts := []experiments.ClientOpt{}
if cfg.ConfigcatEnabled {
experimentsClientOpts = append(experimentsClientOpts, experiments.WithGitpodProxy(host))
}
exps := experiments.NewClient(experimentsClientOpts...)
var (
ideReady = &ideReadyState{cond: sync.NewCond(&sync.Mutex{})}
desktopIdeReady *ideReadyState = nil
cstate = NewInMemoryContentState(cfg.RepoRoot)
gitpodService serverapi.APIInterface
notificationService = NewNotificationService()
)
if !opts.RunGP {
gitpodService = serverapi.NewServerApiService(ctx, &serverapi.ServiceConfig{
Host: host,
Endpoint: endpoint,
InstanceID: cfg.WorkspaceInstanceID,
WorkspaceID: cfg.WorkspaceID,
OwnerID: cfg.OwnerId,
SupervisorVersion: Version,
ConfigcatEnabled: cfg.ConfigcatEnabled,
}, tokenService, exps)
}
if cfg.GetDesktopIDE() != nil {
desktopIdeReady = &ideReadyState{cond: sync.NewCond(&sync.Mutex{})}
}
if !cfg.isHeadless() && !opts.RunGP && !cfg.isDebugWorkspace() {
go trackReadiness(ctx, telemetry, cfg, cstate, ideReady, desktopIdeReady)
}
tokenService.provider[KindGit] = []tokenProvider{NewGitTokenProvider(gitpodService, cfg.WorkspaceConfig, notificationService)}
gitpodConfigService := config.NewConfigService(cfg.RepoRoot+"/.gitpod.yml", cstate.ContentReady())
go gitpodConfigService.Watch(ctx)
var exposedPorts ports.ExposedPortsInterface
if !opts.RunGP {
exposedPorts = createExposedPortsImpl(cfg, gitpodService)
}
portMgmt := ports.NewManager(
exposedPorts,
&ports.PollingServedPortsObserver{
RefreshInterval: 2 * time.Second,
},
ports.NewConfigService(cfg.WorkspaceID, gitpodConfigService),
tunneledPortsService,
internalPorts...,
)
topService := NewTopService()
if !opts.RunGP {
topService.Observe(ctx)
}
if !cfg.isHeadless() && !opts.RunGP {
go analyseConfigChanges(ctx, cfg, telemetry, gitpodConfigService)
go analysePerfChanges(ctx, cfg, telemetry, topService)
}
supervisorMetrics := metrics.NewMetrics()
var metricsReporter *metrics.GrpcMetricsReporter
if !opts.RunGP && !cfg.isDebugWorkspace() && !strings.Contains("ephemeral", cfg.WorkspaceClusterHost) {
_, gitpodHost, err := cfg.GitpodAPIEndpoint()
if err != nil {
log.WithError(err).Error("grpc metrics: failed to parse gitpod host")
} else {
metricsReporter = metrics.NewGrpcMetricsReporter(gitpodHost)
if err := supervisorMetrics.Register(metricsReporter.Registry); err != nil {
log.WithError(err).Error("could not register supervisor metrics")
}
if err := gitpodService.RegisterMetrics(metricsReporter.Registry); err != nil {
log.WithError(err).Error("could not register public api metrics")
}
}
}
termMux := terminal.NewMux()
termMuxSrv := terminal.NewMuxTerminalService(termMux)
termMuxSrv.DefaultWorkdir = cfg.RepoRoot
if cfg.WorkspaceRoot != "" {
termMuxSrv.DefaultWorkdirProvider = func() string {
<-cstate.ContentReady()
stat, err := os.Stat(cfg.WorkspaceRoot)
if err != nil {
log.WithError(err).Error("default workdir provider: cannot resolve the workspace root")
} else if stat.IsDir() {
return cfg.WorkspaceRoot
}
return ""
}
}
termMuxSrv.Env = childProcEnvvars
termMuxSrv.DefaultCreds = &syscall.Credential{
Uid: gitpodUID,
Gid: gitpodGID,
}
taskManager := newTasksManager(cfg, termMuxSrv, cstate, nil, ideReady, desktopIdeReady)
gitStatusWg := &sync.WaitGroup{}
gitStatusCtx, stopGitStatus := context.WithCancel(ctx)
if !cfg.isPrebuild() && !cfg.isHeadless() && !opts.RunGP && !cfg.isDebugWorkspace() {
gitStatusWg.Add(1)
gitStatusService := &GitStatusService{
cfg: cfg,
experiments: exps,
content: cstate,
git: &git.Client{Location: cfg.RepoRoot},
gitpodService: gitpodService,
}
go gitStatusService.Run(gitStatusCtx, gitStatusWg)
}
willShutdownCtx, fireWillShutdown := context.WithCancel(ctx)
apiServices := []RegisterableService{
&statusService{
willShutdownCtx: willShutdownCtx,
ContentState: cstate,
Ports: portMgmt,
Tasks: taskManager,
ideReady: ideReady,
desktopIdeReady: desktopIdeReady,
topService: topService,
},
termMuxSrv,
RegistrableTokenService{Service: tokenService},
notificationService,
NewInfoService(cfg, cstate, gitpodService),
&ControlService{portsManager: portMgmt},
&portService{portsManager: portMgmt},
}
apiServices = append(apiServices, additionalServices...)
if !cfg.isPrebuild() {
// We need to checkout dotfiles first, because they may be changing the path which affects the IDE.
// TODO(cw): provide better feedback if the IDE start fails because of the dotfiles (provide any feedback at all).
installDotfiles(ctx, cfg, tokenService)
}
var ideWG sync.WaitGroup
ideWG.Add(1)
go startAndWatchIDE(ctx, cfg, &cfg.IDE, &ideWG, cstate, ideReady, WebIDE, supervisorMetrics)
if cfg.GetDesktopIDE() != nil {
ideWG.Add(1)
go startAndWatchIDE(ctx, cfg, cfg.GetDesktopIDE(), &ideWG, cstate, desktopIdeReady, DesktopIDE, supervisorMetrics)
}
var (
wg sync.WaitGroup
shutdown = make(chan ShutdownReason, 1)
)
if opts.RunGP {
cstate.MarkContentReady(csapi.WorkspaceInitFromOther)
} else if cfg.isDebugWorkspace() {
cstate.MarkContentReady(cfg.GetDebugWorkspaceContentSource())
} else {
wg.Add(1)
go startContentInit(ctx, cfg, &wg, cstate, supervisorMetrics)
}
wg.Add(1)
go startAPIEndpoint(ctx, cfg, &wg, apiServices, tunneledPortsService, metricsReporter, supervisorMetrics, topService, apiEndpointOpts...)
wg.Add(1)
go startSSHServer(ctx, cfg, &wg)
wg.Add(1)
tasksSuccessChan := make(chan taskSuccess, 1)
go taskManager.Run(ctx, &wg, tasksSuccessChan)
if !opts.RunGP {
wg.Add(1)
go socketActivationForDocker(ctx, &wg, termMux, cfg, telemetry, notificationService, cstate)
}
if cfg.isHeadless() {
wg.Add(1)
go stopWhenTasksAreDone(ctx, &wg, shutdown, tasksSuccessChan)
} else if !opts.RunGP {
wg.Add(1)
go portMgmt.Run(ctx, &wg)
}
if cfg.PreventMetadataAccess {
go func() {
if !hasMetadataAccess() {
return
}
log.Error("metadata access is possible - shutting down")
shutdown <- ShutdownReasonExecutionError
}()
}
if !cfg.isPrebuild() && !opts.RunGP && !cfg.isDebugWorkspace() {
go func() {
for _, repoRoot := range strings.Split(cfg.RepoRoots, ",") {
<-cstate.ContentReady()
waitForIde(ctx, ideReady, desktopIdeReady, 1*time.Second)
start := time.Now()
defer func() {
log.Debugf("unshallow of local repository took %v", time.Since(start))
}()
if !isShallowRepository(repoRoot) {
return
}
cmd := runAsGitpodUser(exec.Command("git", "fetch", "--unshallow", "--tags"))
cmd.Dir = repoRoot
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.WithError(err).Error("git fetch error")
}
}
}()
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
select {
case <-sigChan:
case shutdownReason := <-shutdown:
exitCode = int(shutdownReason)
}
log.Info("received SIGTERM (or shutdown) - tearing down")
fireWillShutdown()
// wait for last git status to persist
stopGitStatus()
gitStatusWg.Wait()
terminalShutdownCtx, cancelTermination := context.WithTimeout(context.Background(), cfg.GetTerminationGracePeriod())
defer cancelTermination()
cancel()
ideWG.Wait()
// terminate all terminal processes once the IDE is gone
termMux.Close(terminalShutdownCtx)
wg.Wait()
}
func isShallowRepository(rootDir string) bool {
cmd := runAsGitpodUser(exec.Command("git", "rev-parse", "--is-shallow-repository"))
cmd.Dir = rootDir
out, err := cmd.CombinedOutput()
if err != nil {
log.WithError(err).Error("unexpected error checking if git repository is shallow")
return true
}
isShallow, err := strconv.ParseBool(strings.TrimSpace(string(out)))
if err != nil {
log.WithError(err).WithField("input", string(out)).Error("unexpected error parsing bool")
return true
}
return isShallow
}
func installDotfiles(ctx context.Context, cfg *Config, tokenService *InMemoryTokenService) {
repo := cfg.DotfileRepo
if repo == "" {
return
}
const dotfilePath = "/home/gitpod/.dotfiles"
if _, err := os.Stat(dotfilePath); err == nil {
// dotfile path exists already - nothing to do here
return
}
prep := func(cfg *Config, out io.Writer, name string, args ...string) *exec.Cmd {
cmd := exec.Command(name, args...)
cmd.Dir = "/home/gitpod"
runAsGitpodUser(cmd)
cmd.Stdout = out
cmd.Stderr = out
return cmd
}
err := func() (err error) {
out, err := os.OpenFile("/home/gitpod/.dotfiles.log", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer out.Close()
defer func() {
if err != nil {
out.WriteString(fmt.Sprintf("# dotfile init failed: %s\n", err.Error()))
}
}()
done := make(chan error, 1)
go func() {
repoUrl, err := url.Parse(repo)
if err != nil {
done <- err
close(done)
return
}
authProvider := func() (username string, password string, err error) {
resp, err := tokenService.GetToken(ctx, &api.GetTokenRequest{
Host: repoUrl.Host,
Kind: KindGit,
})
if err != nil {
return
}
username = resp.User
password = resp.Token
return
}
client := &git.Client{
AuthProvider: authProvider,
AuthMethod: git.BasicAuth,
Location: dotfilePath,
RemoteURI: repo,
}
done <- client.Clone(ctx)
close(done)
}()
select {
case err := <-done:
if err != nil {
return err
}
case <-time.After(120 * time.Second):
return xerrors.Errorf("dotfiles repo clone did not finish within two minutes")
}
filepath.Walk(dotfilePath, func(name string, info os.FileInfo, err error) error {
if err == nil {
err = os.Chown(name, gitpodUID, gitpodGID)
}
return err
})
// at this point we have the dotfile repo cloned, let's try and install it
var candidates = []string{
"install.sh",
"install",
"bootstrap.sh",
"bootstrap",
"script/bootstrap",
"setup.sh",
"setup",
"script/setup",
}
for _, c := range candidates {
fn := filepath.Join(dotfilePath, c)
stat, err := os.Stat(fn)
if err != nil {
_, _ = out.WriteString(fmt.Sprintf("# installation script candidate %s is not available\n", fn))
continue
}
if stat.IsDir() {
_, _ = out.WriteString(fmt.Sprintf("# installation script candidate %s is a directory\n", fn))
continue
}
if stat.Mode()&0111 == 0 {
_, _ = out.WriteString(fmt.Sprintf("# installation script candidate %s is not executable\n", fn))
continue
}
_, _ = out.WriteString(fmt.Sprintf("# executing installation script candidate %s\n", fn))
// looks like we've found a candidate, let's run it
cmd := prep(cfg, out, "/bin/sh", "-c", "exec "+fn)
err = cmd.Start()
if err != nil {
return err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
close(done)
}()
select {
case err = <-done:
return err
case <-time.After(120 * time.Second):
cmd.Process.Kill()
return xerrors.Errorf("installation process %s tool longer than 120 seconds", fn)
}
}
// no installation script candidate was found, let's try and symlink this stuff
err = filepath.Walk(dotfilePath, func(path string, info fs.FileInfo, err error) error {
if strings.Contains(path, "/.git") {
// don't symlink the .git directory or any of its content
return nil
}
homeFN := filepath.Join("/home/gitpod", strings.TrimPrefix(path, dotfilePath))
if _, err := os.Stat(homeFN); err == nil {
// homeFN exists already - do nothing
return nil
}
if info.IsDir() {
err = os.MkdirAll(homeFN, info.Mode().Perm())
if err != nil {
return err
}
return nil
}
// write some feedback to the terminal
out.WriteString(fmt.Sprintf("# echo linking %s -> %s\n", path, homeFN))
return os.Symlink(path, homeFN)
})
return nil
}()
if err != nil {
// installing the dotfiles failed for some reason - we must tell the user
// TODO(cw): tell the user
log.WithError(err).Warn("installing dotfiles failed")
}
}
func createExposedPortsImpl(cfg *Config, gitpodService serverapi.APIInterface) ports.ExposedPortsInterface {
if gitpodService == nil {
log.Error("auto-port exposure won't work")
return &ports.NoopExposedPorts{}
}
return ports.NewGitpodExposedPorts(cfg.WorkspaceID, cfg.WorkspaceInstanceID, cfg.WorkspaceUrl, gitpodService)
}
// supervisor ships some binaries we want in the PATH. We could just add some directory to the path, but
// instead of producing a strange path setup, we symlink the binary to /usr/bin.
func symlinkBinaries(cfg *Config) {
bin, err := os.Executable()
if err != nil {
log.WithError(err).Error("cannot get executable path - hence cannot symlink binaries")
return
}
base := filepath.Dir(bin)
binaries := map[string]string{
"gitpod-cli": "gp",
}
for k, v := range binaries {
var (
from = filepath.Join(base, k)
to = filepath.Join("/usr/bin", v)
)
// remove possibly existing symlink target
if err = os.Remove(to); err != nil && !os.IsNotExist(err) {
log.WithError(err).WithField("to", to).Warn("cannot remove possibly existing symlink target")
}
err = os.Symlink(from, to)
if err != nil {
log.WithError(err).WithField("from", from).WithField("to", to).Warn("cannot create symlink")
}
}
}
func configureGit(cfg *Config) {
settings := [][]string{
{"push.default", "simple"},
{"alias.lg", "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"},
{"credential.helper", "/usr/bin/gp credential-helper"},
{"safe.directory", "*"},
}
if cfg.GitUsername != "" {
settings = append(settings, []string{"user.name", cfg.GitUsername})
}
if cfg.GitEmail != "" {
settings = append(settings, []string{"user.email", cfg.GitEmail})
}
for _, s := range settings {
cmd := exec.Command("git", append([]string{"config", "--global"}, s...)...)
cmd = runAsGitpodUser(cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.WithError(err).WithField("args", s).Warn("git config error")
}
}
}
func hasMetadataAccess() bool {
// curl --connect-timeout 10 -s -H "Metadata-Flavor: Google" 'http://169.254.169.254/computeMetadata/v1/instance/'
client := &http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequest("GET", "http://169.254.169.254/computeMetadata/v1/instance/", nil)
if err != nil {
log.WithError(err).Error("cannot check metadata access - this should never happen")
return true
}
req.Header.Add("Metadata-Flavor", "Google")
resp, err := client.Do(req)
// We did not see an error. That's a problem because that means that users can reach the metadata endpoint.
if err == nil {
resp.Body.Close()
return true
}
// if we see any error here we're good because then the request timed out or failed for some other reason.
return false
}
type ideStatus int
const (
statusNeverRan ideStatus = iota
statusShouldRun
statusShouldShutdown
)
var (
errSignalTerminated = errors.New("signal: terminated")
)
func startAndWatchIDE(ctx context.Context, cfg *Config, ideConfig *IDEConfig, wg *sync.WaitGroup, cstate *InMemoryContentState, ideReady *ideReadyState, ide IDEKind, metrics *metrics.SupervisorMetrics) {
defer wg.Done()
defer log.WithField("ide", ide.String()).Debug("startAndWatchIDE shutdown")
if cfg.isHeadless() {
ideReady.Set(true, nil)
return
}
// Wait until content ready to launch IDE
<-cstate.ContentReady()
ideStatus := statusNeverRan
var (
cmd *exec.Cmd
ideStopped chan struct{}
firstStart bool = true
)
supervisorLoop:
for {
if ideStatus == statusShouldShutdown {
break
}
ideStopped = make(chan struct{}, 1)
startTime := time.Now()
cmd = prepareIDELaunch(cfg, ideConfig)
launchIDE(cfg, ideConfig, cmd, ideStopped, ideReady, &ideStatus, ide)
if firstStart {
firstStart = false
go func() {
select {
case <-ideReady.Wait():
cost := time.Since(startTime).Seconds()
his, err := metrics.IDEReadyDurationTotal.GetMetricWithLabelValues(ide.String())
if err != nil {
log.WithError(err).Error("cannot get metrics for IDEReadyDurationTotal")
return
}
his.Observe(cost)
case <-ctx.Done():
}
}()
}
select {
case <-ideStopped:
// kill all processes in same pgid
_ = syscall.Kill(-1*cmd.Process.Pid, syscall.SIGKILL)
// IDE was stopped - let's just restart it after a small delay (in case the IDE doesn't start at all) in the next round
if ideStatus == statusShouldShutdown {
break supervisorLoop
}
time.Sleep(1 * time.Second)
case <-ctx.Done():
// we've been asked to shut down
ideStatus = statusShouldShutdown
if cmd == nil || cmd.Process == nil {
log.WithField("ide", ide.String()).Error("cmd or cmd.Process is nil, cannot send SIGTERM signal")
} else {
_ = cmd.Process.Signal(syscall.SIGTERM)
}
break supervisorLoop
}
}
log.WithField("ide", ide.String()).WithField("budget", timeBudgetIDEShutdown.String()).Info("IDE supervisor loop ended - waiting for IDE to come down")
select {
case <-ideStopped:
log.WithField("ide", ide.String()).WithField("budget", timeBudgetIDEShutdown.String()).Info("IDE has been stopped in time")
return
case <-time.After(timeBudgetIDEShutdown):
log.WithField("ide", ide.String()).WithField("timeBudgetIDEShutdown", timeBudgetIDEShutdown.String()).Error("IDE did not stop in time - sending SIGKILL")
if cmd == nil || cmd.Process == nil {
log.WithField("ide", ide.String()).Error("cmd or cmd.Process is nil, cannot send SIGKILL")
} else {
_ = cmd.Process.Signal(syscall.SIGKILL)
}
}
}
func launchIDE(cfg *Config, ideConfig *IDEConfig, cmd *exec.Cmd, ideStopped chan struct{}, ideReady *ideReadyState, s *ideStatus, ide IDEKind) {
go func() {
// prepareIDELaunch sets Pdeathsig, which on on Linux, will kill the
// child process when the thread dies, not when the process dies.
// runtime.LockOSThread ensures that as long as this function is
// executing that OS thread will still be around.
//
// see https://github.com/golang/go/issues/27505#issuecomment-713706104
runtime.LockOSThread()
defer runtime.UnlockOSThread()
log.Info("start launchIDE")
err := cmd.Start()
if err != nil {
if s == func() *ideStatus { i := statusNeverRan; return &i }() {
log.WithField("ide", ide.String()).WithError(err).Fatal("IDE failed to start")
}
return
}
s = func() *ideStatus { i := statusShouldRun; return &i }()
go func() {
IDEStatus := runIDEReadinessProbe(cfg, ideConfig, ide)
ideReady.Set(true, IDEStatus)
}()
err = cmd.Wait()
if err != nil {
if errSignalTerminated.Error() != err.Error() {
log.WithField("ide", ide.String()).WithError(err).Warn("IDE was stopped")
}
ideWasReady, _ := ideReady.Get()
if !ideWasReady {
log.WithField("ide", ide.String()).WithError(err).Fatal("IDE failed to start")
return
}
}
ideReady.Set(false, nil)
close(ideStopped)
}()
}
func prepareIDELaunch(cfg *Config, ideConfig *IDEConfig) *exec.Cmd {
args := ideConfig.EntrypointArgs
for i := range args {
args[i] = strings.ReplaceAll(args[i], "{IDEPORT}", strconv.Itoa(cfg.IDEPort))
args[i] = strings.ReplaceAll(args[i], "{DESKTOPIDEPORT}", strconv.Itoa(desktopIDEPort))
}
log.WithField("args", args).WithField("entrypoint", ideConfig.Entrypoint).Info("preparing IDE launch")
cmd := exec.Command(ideConfig.Entrypoint, args...)
// All supervisor children run as gitpod user. The environment variables we produce are also
// gitpod user specific.
runAsGitpodUser(cmd)
// We need the child process to run in its own process group, s.t. we can suspend and resume
// IDE and its children.
cmd.SysProcAttr.Setpgid = true
cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL
// Here we must resist the temptation to "neaten up" the IDE output for headless builds.
// This would break the JSON parsing of the headless builds.
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if lrr := cfg.IDELogRateLimit(ideConfig); lrr > 0 {
limit := int64(lrr)
cmd.Stdout = dropwriter.Writer(cmd.Stdout, dropwriter.NewBucket(limit*1024*3, limit*1024))
cmd.Stderr = dropwriter.Writer(cmd.Stderr, dropwriter.NewBucket(limit*1024*3, limit*1024))
log.WithField("limit_kb_per_sec", limit).Info("rate limiting IDE log output")
}
return cmd
}
// buildChildProcEnv computes the environment variables passed to a child process, based on the total list
// of envvars. If envvars is nil, os.Environ() is used.
//
// Beware: if config contains an OTS URL the results may differ on subsequent calls.
func buildChildProcEnv(cfg *Config, envvars []string, runGP bool) []string {
if envvars == nil {
envvars = os.Environ()
}
envs := make(map[string]string)
for _, e := range envvars {
segs := strings.SplitN(e, "=", 2)
if len(segs) < 2 {
log.Printf("\"%s\" has invalid format, not including in IDE environment", e)
continue
}
nme, val := segs[0], segs[1]
if isBlacklistedEnvvar(nme) {
continue
}
envs[nme] = val
}
getEnv := func(name string) string {
return envs[name]
}
for _, ide := range []*IDEConfig{&cfg.IDE, cfg.GetDesktopIDE()} {
if ide == nil || ide.Env == nil {
continue
}
for _, name := range ide.Env.Keys() {
if isBlacklistedEnvvar(name) {
continue
}
raw, exists := ide.Env.Get(name)
if !exists {
continue
}
if value, ok := raw.(string); ok {
envs[name] = os.Expand(value, getEnv)
}
}
}
envs["SUPERVISOR_ADDR"] = fmt.Sprintf("localhost:%d", cfg.APIEndpointPort)
if cfg.EnvvarOTS != "" {
es, err := downloadEnvvarOTS(cfg.EnvvarOTS)