in internal/sshd/connection.go [102:159]
func (c *connection) handleRequests(ctx context.Context, sconn *ssh.ServerConn, chans <-chan ssh.NewChannel, handler channelHandler) {
ctxlog := log.WithContextFields(ctx, log.Fields{"remote_addr": c.remoteAddr})
for newChannel := range chans {
ctxlog.WithField("channel_type", newChannel.ChannelType()).Info("connection: handle: new channel requested")
if newChannel.ChannelType() != "session" {
ctxlog.Info("connection: handleRequests: unknown channel type")
_ = newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
if !c.concurrentSessions.TryAcquire(1) {
ctxlog.Info("connection: handleRequests: too many concurrent sessions")
_ = newChannel.Reject(ssh.ResourceShortage, "too many concurrent sessions")
metrics.SshdHitMaxSessions.Inc()
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
ctxlog.WithError(err).Error("connection: handleRequests: accepting channel failed")
c.concurrentSessions.Release(1)
continue
}
go func() {
defer func(started time.Time) {
duration := time.Since(started).Seconds()
metrics.SshdSessionDuration.Observe(duration)
ctxlog.WithFields(log.Fields{"duration_s": duration}).Info("connection: handleRequests: done")
}(time.Now())
defer c.concurrentSessions.Release(1)
// Prevent a panic in a single session from taking out the whole server
defer func() {
if err := recover(); err != nil {
ctxlog.WithField("recovered_error", err).Error("panic handling session")
}
}()
metrics.SliSshdSessionsTotal.Inc()
err := handler(ctx, sconn, channel, requests)
if err != nil {
c.trackError(ctxlog, err)
}
}()
}
// When a connection has been prematurely closed we block execution until all concurrent sessions are released
// in order to allow Gitaly complete the operations and close all the channels gracefully.
// If it didn't happen within timeout, we unblock the execution
// Related issue: https://gitlab.com/gitlab-org/gitlab-shell/-/issues/563
ctx, cancel := context.WithTimeout(ctx, EOFTimeout)
defer cancel()
_ = c.concurrentSessions.Acquire(ctx, c.maxSessions)
}