Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement retry logic with exponential backoff for connection errors #20

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions cmd/frpc/gssh_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
package main

import (
"context"
"sync"
"time"

"github.com/gofrp/tiny-frpc/pkg/config"
v1 "github.com/gofrp/tiny-frpc/pkg/config/v1"
Expand Down Expand Up @@ -103,3 +105,36 @@ func (gr *GoSSHRun) Close() error {
}
return nil
}

func (gr *GoSSHRun) retryConnection(ctx context.Context, cmd config.GoSSHParam, idx int) {
backoff := 1 * time.Second
for {
select {
case <-ctx.Done():
return
default:
tc, err := gssh.NewTunnelClient(cmd.LocalAddr, cmd.ServerAddr, cmd.SSHExtraCmd)
if err != nil {
log.Errorf("retry new ssh tunnel client error: %v", err)
continue
}

err = tc.Start()
if err != nil {
log.Errorf("retry cmd: %v run error: %v", cmd, err)
time.Sleep(backoff)
if backoff < 30*time.Second {
backoff *= 2
}
continue
}

gr.mu.Lock()
gr.tcs[idx] = tc
gr.mu.Unlock()

gr.wg.Done()
return
}
}
}
27 changes: 27 additions & 0 deletions cmd/frpc/nssh_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import (
"context"
"sync"
"time"

"github.com/gofrp/tiny-frpc/pkg/config"
v1 "github.com/gofrp/tiny-frpc/pkg/config/v1"
Expand Down Expand Up @@ -79,6 +80,32 @@
nr.mu.Unlock()

cmdWrapper.ExecuteCommand(nr.ctx)

// Retry logic with exponential backoff
backoff := 1 * time.Second
for {
select {
case <-nr.ctx.Done():
return
default:
cmdWrapper := nssh.NewCmdWrapper(nr.ctx, cmd)
cmdWrapper.ExecuteCommand(nr.ctx)
if cmdWrapper.cmd.ProcessState.Success() {

Check failure on line 93 in cmd/frpc/nssh_runner.go

View workflow job for this annotation

GitHub Actions / build

cmdWrapper.cmd undefined (type *nssh.CmdWrapper has no field or method cmd)
log.Infof("Command %v executed successfully after retry", cmd)
nr.mu.Lock()
nr.cws[idx] = cmdWrapper
nr.mu.Unlock()
nr.wg.Done()
return
} else {
log.Errorf("Retry command %v failed, retrying in %v seconds", cmd, backoff)
time.Sleep(backoff)
if backoff < 30*time.Second {
backoff *= 2
}
}
}
}
}(cmd, i)
}

Expand Down
Loading