Skip to content

Commit

Permalink
client: make server downtime more graceful
Browse files Browse the repository at this point in the history
  • Loading branch information
gartnera committed Nov 26, 2024
1 parent 65967c3 commit 53e94cc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
9 changes: 5 additions & 4 deletions client/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
Expand Down Expand Up @@ -39,16 +39,17 @@ func NewTunnel(server, hostname, token string, useTLS, tlsSkipVerify, httpTarget
}
}

func (t *Tunnel) Start() {
func (t *Tunnel) Start() error {
conn, err := t.stage1(true)
if err != nil {
panic(fmt.Errorf("unable to connect to server: %w", err))
return fmt.Errorf("unable to complete initial connection to server: %w", err)
}
go t.stage2(conn)

for i := 0; i < 20; i++ {
go t.both()
}
return nil
}

func (t *Tunnel) Shutdown() {
Expand Down Expand Up @@ -170,7 +171,7 @@ func (t *Tunnel) stage2(conn net.Conn) {
s := fmt.Sprintf("target %s returned error %s", t.target, err)
r := http.Response{
StatusCode: 500,
Body: ioutil.NopCloser(bytes.NewBufferString(s)),
Body: io.NopCloser(bytes.NewBufferString(s)),
}
r.Write(conn)
return
Expand Down
15 changes: 9 additions & 6 deletions cmd/tunnel-client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ func init() {
}

var rootCmd = &cobra.Command{
Use: "tunnel <[http://]hostname:port>",
Short: "Start a tunnel to a local server",
Example: "tunnel localhost:8888",
Args: cobra.ExactArgs(1),
Use: "tunnel <[http://]hostname:port>",
Short: "Start a tunnel to a local server",
Example: "tunnel localhost:8888",
SilenceUsage: true,
Args: cobra.ExactArgs(1),
// use envy to parse TUNNEL_ vars into environment
PersistentPreRun: func(cmd *cobra.Command, args []string) {
envy.ParseCobra(cmd, envy.CobraConfig{
Expand Down Expand Up @@ -90,7 +91,10 @@ var rootCmd = &cobra.Command{
}

tunnel := client.NewTunnel(controlName, hostnameFqdn, token, useTLS, tlsSkipVerify, httpTargetHostHeader, target)
tunnel.Start()
err := tunnel.Start()
if err != nil {
return fmt.Errorf("start %s: %w", controlName, err)
}
tunnels = append(tunnels, tunnel)
}

Expand All @@ -107,7 +111,6 @@ var rootCmd = &cobra.Command{

func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

0 comments on commit 53e94cc

Please sign in to comment.