From d281c094b88ab6bb2d6ccd0eb572d4275a9ab371 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Thu, 14 Dec 2023 19:21:12 +0700 Subject: all: close the SSH connection once Play finished Previously, we used to run awwan as CLI so each connection is open and closed (forcefully). Since we now use awwan WUI frequently, any command that execute Play does not close the session immediately once finished. This cause many connections open in remote server. This changes close the SSH connections immediately once the Play command finished. --- awwan.go | 8 ++++---- session.go | 10 ++++++++++ ssh_client.go | 25 +++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/awwan.go b/awwan.go index 5164245..7eb5d6b 100644 --- a/awwan.go +++ b/awwan.go @@ -405,10 +405,10 @@ func (aww *Awwan) Play(req *ExecRequest) (err error) { } req.mlog.Outf(`=== END: %s %s %s`, req.Mode, req.Script, req.LineRange) out: - if ses != nil && ses.sshc != nil { - var errRemove = ses.sshc.rmdirAll(ses.sshc.dirTmp) - if errRemove != nil { - req.mlog.Errf(`!!! %s`, errRemove) + if ses != nil { + var errclose = ses.close() + if errclose != nil { + req.mlog.Errf(`!!! %s`, errclose) } } if err != nil { diff --git a/session.go b/session.go index 9f33094..52f0388 100644 --- a/session.go +++ b/session.go @@ -410,6 +410,16 @@ func ExecLocal(req *ExecRequest, stmt *Statement) (err error) { return nil } +// close the session and release all resources. +func (ses *Session) close() (err error) { + ses.cryptoc = nil + if ses.sshc != nil { + err = ses.sshc.close() + ses.sshc = nil + } + return err +} + // executeRequires run the "#require:" statements from line 0 until // the start argument in the local system. func (ses *Session) executeRequires(req *ExecRequest, pos linePosition) (err error) { diff --git a/ssh_client.go b/ssh_client.go index 766e40b..e47b47b 100644 --- a/ssh_client.go +++ b/ssh_client.go @@ -4,6 +4,7 @@ package awwan import ( + "errors" "fmt" "io/fs" "path/filepath" @@ -96,6 +97,30 @@ func (sshc *sshClient) chown(remoteFile, owner string) (err error) { return nil } +// close the connections and release all resources. +func (sshc *sshClient) close() (err error) { + err = sshc.rmdirAll(sshc.dirTmp) + + var errClose error + + if sshc.sftpc != nil { + errClose = sshc.sftpc.Close() + if errClose != nil { + err = errors.Join(err, errClose) + } + sshc.sftpc = nil + } + + errClose = sshc.conn.Close() + if errClose != nil { + err = errors.Join(err, errClose) + } + sshc.conn = nil + sshc.section = nil + + return err +} + // get the remote file and write it to local path. func (sshc *sshClient) get(remote, local string) (err error) { if sshc.sftpc == nil { -- cgit v1.3