-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
jupyter.go
105 lines (88 loc) · 2.48 KB
/
jupyter.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
package codespace
import (
"context"
"fmt"
"net"
"strings"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/spf13/cobra"
)
func newJupyterCmd(app *App) *cobra.Command {
var selector *CodespaceSelector
jupyterCmd := &cobra.Command{
Use: "jupyter",
Short: "Open a codespace in JupyterLab",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Jupyter(cmd.Context(), selector)
},
}
selector = AddCodespaceSelector(jupyterCmd, app.apiClient)
return jupyterCmd
}
func (a *App) Jupyter(ctx context.Context, selector *CodespaceSelector) (err error) {
// Ensure all child tasks (e.g. port forwarding) terminate before return.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
var (
invoker rpc.Invoker
serverPort int
serverUrl string
)
err = a.RunWithProgress("Starting JupyterLab on codespace", func() (err error) {
invoker, err = rpc.CreateInvoker(ctx, fwd)
if err != nil {
return
}
serverPort, serverUrl, err = invoker.StartJupyterServer(ctx)
return
})
if invoker != nil {
defer safeClose(invoker, &err)
}
if err != nil {
return err
}
// Pass 0 to pick a random port
listen, _, err := codespaces.ListenTCP(0, false)
if err != nil {
return err
}
defer listen.Close()
destPort := listen.Addr().(*net.TCPAddr).Port
tunnelClosed := make(chan error, 1)
go func() {
opts := portforwarder.ForwardPortOpts{
Port: serverPort,
}
tunnelClosed <- fwd.ForwardPortToListener(ctx, opts, listen)
}()
// Server URL contains an authentication token that must be preserved
targetUrl := strings.Replace(serverUrl, fmt.Sprintf("%d", serverPort), fmt.Sprintf("%d", destPort), 1)
err = a.browser.Browse(targetUrl)
if err != nil {
return fmt.Errorf("failed to open JupyterLab in browser: %w", err)
}
fmt.Fprintln(a.io.Out, targetUrl)
select {
case err := <-tunnelClosed:
return fmt.Errorf("tunnel closed: %w", err)
case <-ctx.Done():
return nil // success
}
}