Skip to content

Commit f034804

Browse files
zeripath6543
andauthored
Set self-adjusting deadline for connection writing (#16068) (#16123)
In #16055 it appears that the simple 5s deadline doesn't work for large file writes. Now we can't - or at least shouldn't just set no deadline as go will happily let these connections block indefinitely. However, what seems reasonable is to set some minimum rate we expect for writing. This PR suggests the following algorithm: * Every write has a minimum timeout of 5s (adjustable at compile time.) * If there has been a previous write - then consider its previous deadline, add half of the minimum timeout + 2s per kb about to written. * If that new deadline is after the minimum timeout use that. Fix #16055 Signed-off-by: Andrew Thornton <[email protected]> Co-authored-by: 6543 <[email protected]>
1 parent c1887bf commit f034804

File tree

5 files changed

+75
-34
lines changed

5 files changed

+75
-34
lines changed

custom/conf/app.example.ini

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,10 @@ HTTP_PORT = 3000
281281
; PORT_TO_REDIRECT.
282282
REDIRECT_OTHER_PORT = false
283283
PORT_TO_REDIRECT = 80
284+
; Timeout for any write to the connection. (Set to 0 to disable all timeouts.)
285+
PER_WRITE_TIMEOUT = 30s
286+
; Timeout per Kb written to connections.
287+
PER_WRITE_PER_KB_TIMEOUT = 30s
284288
; Permission for unix socket
285289
UNIX_SOCKET_PERMISSION = 666
286290
; Local (DMZ) URL for Gitea workers (such as SSH update) accessing web service.

docs/content/doc/advanced/config-cheat-sheet.en-us.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,9 @@ Values containing `#` or `;` must be quoted using `` ` `` or `"""`.
237237
most cases you do not need to change the default value. Alter it only if
238238
your SSH server node is not the same as HTTP node. Do not set this variable
239239
if `PROTOCOL` is set to `unix`.
240+
- `PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the connection. (Set to 0 to
241+
disable all timeouts.)
242+
- `PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to connections.
240243

241244
- `DISABLE_SSH`: **false**: Disable SSH feature when it's not available.
242245
- `START_SSH_SERVER`: **false**: When enabled, use the built-in SSH server.
@@ -260,6 +263,9 @@ Values containing `#` or `;` must be quoted using `` ` `` or `"""`.
260263
- `SSH_KEY_TEST_PATH`: **/tmp**: Directory to create temporary files in when testing public keys using ssh-keygen, default is the system temporary directory.
261264
- `SSH_KEYGEN_PATH`: **ssh-keygen**: Path to ssh-keygen, default is 'ssh-keygen' which means the shell is responsible for finding out which one to call.
262265
- `SSH_EXPOSE_ANONYMOUS`: **false**: Enable exposure of SSH clone URL to anonymous visitors, default is false.
266+
- `SSH_PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the SSH connections. (Set to
267+
0 to disable all timeouts.)
268+
- `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to SSH connections.
263269
- `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type.
264270

265271
- `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures.

modules/graceful/server.go

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"time"
1818

1919
"code.gitea.io/gitea/modules/log"
20+
"code.gitea.io/gitea/modules/setting"
2021
)
2122

2223
var (
@@ -26,11 +27,12 @@ var (
2627
DefaultWriteTimeOut time.Duration
2728
// DefaultMaxHeaderBytes default max header bytes
2829
DefaultMaxHeaderBytes int
30+
// PerWriteWriteTimeout timeout for writes
31+
PerWriteWriteTimeout = 30 * time.Second
32+
// PerWriteWriteTimeoutKbTime is a timeout taking account of how much there is to be written
33+
PerWriteWriteTimeoutKbTime = 10 * time.Second
2934
)
3035

31-
// PerWriteWriteTimeout timeout for writes
32-
const PerWriteWriteTimeout = 5 * time.Second
33-
3436
func init() {
3537
DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)
3638
}
@@ -40,14 +42,16 @@ type ServeFunction = func(net.Listener) error
4042

4143
// Server represents our graceful server
4244
type Server struct {
43-
network string
44-
address string
45-
listener net.Listener
46-
wg sync.WaitGroup
47-
state state
48-
lock *sync.RWMutex
49-
BeforeBegin func(network, address string)
50-
OnShutdown func()
45+
network string
46+
address string
47+
listener net.Listener
48+
wg sync.WaitGroup
49+
state state
50+
lock *sync.RWMutex
51+
BeforeBegin func(network, address string)
52+
OnShutdown func()
53+
PerWriteTimeout time.Duration
54+
PerWritePerKbTimeout time.Duration
5155
}
5256

5357
// NewServer creates a server on network at provided address
@@ -58,11 +62,13 @@ func NewServer(network, address, name string) *Server {
5862
log.Info("Starting new %s server: %s:%s on PID: %d", name, network, address, os.Getpid())
5963
}
6064
srv := &Server{
61-
wg: sync.WaitGroup{},
62-
state: stateInit,
63-
lock: &sync.RWMutex{},
64-
network: network,
65-
address: address,
65+
wg: sync.WaitGroup{},
66+
state: stateInit,
67+
lock: &sync.RWMutex{},
68+
network: network,
69+
address: address,
70+
PerWriteTimeout: setting.PerWriteTimeout,
71+
PerWritePerKbTimeout: setting.PerWritePerKbTimeout,
6672
}
6773

6874
srv.BeforeBegin = func(network, addr string) {
@@ -224,9 +230,11 @@ func (wl *wrappedListener) Accept() (net.Conn, error) {
224230
closed := int32(0)
225231

226232
c = wrappedConn{
227-
Conn: c,
228-
server: wl.server,
229-
closed: &closed,
233+
Conn: c,
234+
server: wl.server,
235+
closed: &closed,
236+
perWriteTimeout: wl.server.PerWriteTimeout,
237+
perWritePerKbTimeout: wl.server.PerWritePerKbTimeout,
230238
}
231239

232240
wl.server.wg.Add(1)
@@ -249,13 +257,23 @@ func (wl *wrappedListener) File() (*os.File, error) {
249257

250258
type wrappedConn struct {
251259
net.Conn
252-
server *Server
253-
closed *int32
260+
server *Server
261+
closed *int32
262+
deadline time.Time
263+
perWriteTimeout time.Duration
264+
perWritePerKbTimeout time.Duration
254265
}
255266

256267
func (w wrappedConn) Write(p []byte) (n int, err error) {
257-
if PerWriteWriteTimeout > 0 {
258-
_ = w.Conn.SetWriteDeadline(time.Now().Add(PerWriteWriteTimeout))
268+
if w.perWriteTimeout > 0 {
269+
minTimeout := time.Duration(len(p)/1024) * w.perWritePerKbTimeout
270+
minDeadline := time.Now().Add(minTimeout).Add(w.perWriteTimeout)
271+
272+
w.deadline = w.deadline.Add(minTimeout)
273+
if minDeadline.After(w.deadline) {
274+
w.deadline = minDeadline
275+
}
276+
_ = w.Conn.SetWriteDeadline(w.deadline)
259277
}
260278
return w.Conn.Write(p)
261279
}

modules/setting/setting.go

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ var (
117117
GracefulRestartable bool
118118
GracefulHammerTime time.Duration
119119
StartupTimeout time.Duration
120+
PerWriteTimeout = 30 * time.Second
121+
PerWritePerKbTimeout = 10 * time.Second
120122
StaticURLPrefix string
121123
AbsoluteAssetURL string
122124

@@ -147,18 +149,22 @@ var (
147149
TrustedUserCAKeys []string `ini:"SSH_TRUSTED_USER_CA_KEYS"`
148150
TrustedUserCAKeysFile string `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
149151
TrustedUserCAKeysParsed []gossh.PublicKey `ini:"-"`
152+
PerWriteTimeout time.Duration `ini:"SSH_PER_WRITE_TIMEOUT"`
153+
PerWritePerKbTimeout time.Duration `ini:"SSH_PER_WRITE_PER_KB_TIMEOUT"`
150154
}{
151-
Disabled: false,
152-
StartBuiltinServer: false,
153-
Domain: "",
154-
Port: 22,
155-
ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "[email protected]", "arcfour256", "arcfour128"},
156-
ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "[email protected]"},
157-
ServerMACs: []string{"[email protected]", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
158-
KeygenPath: "ssh-keygen",
159-
MinimumKeySizeCheck: true,
160-
MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2048},
161-
ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
155+
Disabled: false,
156+
StartBuiltinServer: false,
157+
Domain: "",
158+
Port: 22,
159+
ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "[email protected]", "arcfour256", "arcfour128"},
160+
ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "[email protected]"},
161+
ServerMACs: []string{"[email protected]", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
162+
KeygenPath: "ssh-keygen",
163+
MinimumKeySizeCheck: true,
164+
MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2048},
165+
ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
166+
PerWriteTimeout: PerWriteTimeout,
167+
PerWritePerKbTimeout: PerWritePerKbTimeout,
162168
}
163169

164170
// Security settings
@@ -607,6 +613,8 @@ func NewContext() {
607613
GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
608614
GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
609615
StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)
616+
PerWriteTimeout = sec.Key("PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
617+
PerWritePerKbTimeout = sec.Key("PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
610618

611619
defaultAppURL := string(Protocol) + "://" + Domain
612620
if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
@@ -772,6 +780,8 @@ func NewContext() {
772780
}
773781

774782
SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
783+
SSH.PerWriteTimeout = sec.Key("SSH_PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
784+
SSH.PerWritePerKbTimeout = sec.Key("SSH_PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
775785

776786
if err = Cfg.Section("oauth2").MapTo(&OAuth2); err != nil {
777787
log.Fatal("Failed to OAuth2 settings: %v", err)

modules/ssh/ssh_graceful.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@ package ssh
77
import (
88
"code.gitea.io/gitea/modules/graceful"
99
"code.gitea.io/gitea/modules/log"
10+
"code.gitea.io/gitea/modules/setting"
1011

1112
"github.com/gliderlabs/ssh"
1213
)
1314

1415
func listen(server *ssh.Server) {
1516
gracefulServer := graceful.NewServer("tcp", server.Addr, "SSH")
17+
gracefulServer.PerWriteTimeout = setting.SSH.PerWriteTimeout
18+
gracefulServer.PerWritePerKbTimeout = setting.SSH.PerWritePerKbTimeout
1619

1720
err := gracefulServer.ListenAndServe(server.Serve)
1821
if err != nil {

0 commit comments

Comments
 (0)