Skip to content

Commit

Permalink
incus/file/delete: Cache the SFTP client
Browse files Browse the repository at this point in the history
Signed-off-by: Stéphane Graber <[email protected]>
  • Loading branch information
stgraber committed Oct 2, 2024
1 parent c953583 commit bd16f87
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions cmd/incus/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"strconv"
"strings"

"github.com/pkg/sftp"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"

Expand Down Expand Up @@ -334,18 +335,30 @@ func (c *cmdFileDelete) Run(cmd *cobra.Command, args []string) error {
return err
}

// Store clients.
sftpClients := map[string]*sftp.Client{}

defer func() {
for _, sftpClient := range sftpClients {
_ = sftpClient.Close()
}
}()

for _, resource := range resources {
pathSpec := strings.SplitN(resource.name, "/", 2)
if len(pathSpec) != 2 {
return fmt.Errorf(i18n.G("Invalid path %s"), resource.name)
}

sftpConn, err := resource.server.GetInstanceFileSFTP(pathSpec[0])
if err != nil {
return err
}
sftpConn, ok := sftpClients[pathSpec[0]]
if !ok {
sftpConn, err = resource.server.GetInstanceFileSFTP(pathSpec[0])
if err != nil {
return err
}

defer func() { _ = sftpConn.Close() }()
sftpClients[pathSpec[0]] = sftpConn
}

if c.flagForce {
err = sftpConn.RemoveAll(pathSpec[1])
Expand Down

0 comments on commit bd16f87

Please sign in to comment.