-
Notifications
You must be signed in to change notification settings - Fork 9
/
vnc.go
99 lines (80 loc) · 2.31 KB
/
vnc.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cluster
import (
"context"
"errors"
"fmt"
"net"
"github.com/pkg/browser"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"namespacelabs.dev/foundation/framework/netcopy"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
)
func NewVncCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vnc [instance-id]",
Short: "Start a VNC session.",
Args: cobra.ArbitraryArgs,
Hidden: true,
}
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
cluster, _, err := SelectRunningCluster(ctx, args)
if err != nil {
if errors.Is(err, ErrEmptyClusterList) {
PrintCreateClusterMsg(ctx)
return nil
}
return err
}
if cluster == nil {
return nil
}
return runVnc(ctx, cluster)
})
return cmd
}
func runVnc(ctx context.Context, instance *api.KubernetesCluster) error {
vncSvc := api.ClusterService(instance, "vnc")
if vncSvc == nil || vncSvc.Endpoint == "" {
return fnerrors.New("instance does not have vnc")
}
if vncSvc.Status != "READY" {
return fnerrors.New("expected vnc to be READY, saw %q", vncSvc.Status)
}
peerConn, err := api.DialEndpoint(ctx, vncSvc.Endpoint)
if err != nil {
return err
}
fmt.Fprint(console.Stdout(ctx), "Connected to instance.\n")
defer peerConn.Close()
ctxWithCancel, cancel := context.WithCancel(ctx)
defer cancel()
var d net.ListenConfig
lst, err := d.Listen(ctxWithCancel, "tcp", "127.0.0.1:0")
if err != nil {
return err
}
eg, _ := errgroup.WithContext(ctxWithCancel)
eg.Go(func() error {
conn, err := lst.Accept()
if err != nil {
return err
}
fmt.Fprint(console.Stdout(ctx), "VNC client connected.\n")
_ = netcopy.CopyConns(nil, conn, peerConn)
fmt.Fprint(console.Stdout(ctx), "VNC client disconnected, leaving.\n")
return nil
})
fmt.Fprint(console.Stdout(ctx), "Opening VNC client...\n")
// XXX receive credentials.
if err := browser.OpenURL(fmt.Sprintf("vnc://admin:admin@%s", lst.Addr())); err != nil {
return err
}
return eg.Wait()
}