Prevent SSH timeouts by closing connection when not needed

This commit is contained in:
Tony Blyler 2016-05-24 22:04:28 -04:00
parent a6db512926
commit ba49a850a2
No known key found for this signature in database
GPG key ID: 25C9D3A655D1A65C

View file

@ -125,26 +125,35 @@ func NewQueue(config *Config, logger *log.Logger) (*Queue, error) {
rtClient := rtorrent.New(config.Rtorrent.Addr, config.Rtorrent.InsecureCert) rtClient := rtorrent.New(config.Rtorrent.Addr, config.Rtorrent.InsecureCert)
rtClient.SetAuth(config.Rtorrent.Username, config.Rtorrent.Password) rtClient.SetAuth(config.Rtorrent.Username, config.Rtorrent.Password)
sftpClient, err := easysftp.Connect(&easysftp.ClientConfig{ q := &Queue{
Username: config.SSH.Username,
Password: config.SSH.Password,
KeyPath: config.SSH.KeyPath,
Host: config.SSH.Addr,
Timeout: config.SSH.Timeout,
FileMode: config.DownloadFileMode,
})
if err != nil {
return nil, err
}
return &Queue{
rtClient: rtClient, rtClient: rtClient,
sftpClient: sftpClient, sftpClient: nil,
fsWatcher: fsWatcher, fsWatcher: fsWatcher,
config: config, config: config,
downloadQueue: make(map[string]string), downloadQueue: make(map[string]string),
logger: logger, logger: logger,
}, nil }
sftpClient, err := q.newSftpClient()
if err != nil {
return nil, err
}
// the sftpClient connection was only made to verify settings
sftpClient.Close()
return q, nil
}
func (q *Queue) newSftpClient() (*easysftp.Client, error) {
return easysftp.Connect(&easysftp.ClientConfig{
Username: q.config.SSH.Username,
Password: q.config.SSH.Password,
KeyPath: q.config.SSH.KeyPath,
Host: q.config.SSH.Addr,
Timeout: q.config.SSH.Timeout,
FileMode: q.config.DownloadFileMode,
})
} }
// Close all of the connections and watchers // Close all of the connections and watchers
@ -388,7 +397,11 @@ func (q *Queue) Run(stop <-chan bool) {
} }
} }
if len(downloadsRunning) > 0 { if len(downloadsRunning) == 0 {
// close the sftp connection since it is not being used
q.sftpClient.Close()
q.sftpClient = nil
} else {
cont = true cont = true
for cont { for cont {
select { select {
@ -419,6 +432,15 @@ func (q *Queue) Run(stop <-chan bool) {
continue continue
} }
if q.sftpClient == nil {
q.sftpClient, err = q.newSftpClient()
if err != nil {
q.logger.Println("Failed to connect to sftp: ", err)
q.sftpClient = nil
continue
}
}
go func(torrent rtorrent.Torrent, torrentPath string, hashChan chan<- string) { go func(torrent rtorrent.Torrent, torrentPath string, hashChan chan<- string) {
err := q.downloadTorrent(torrent, torrentPath) err := q.downloadTorrent(torrent, torrentPath)
if err != nil { if err != nil {