ssh2 end event invoked without an error event on connection failure

1.6k views Asked by At

I am using ssh2 to connect to a remote sftp server. The code is as shown below:

fetchFileList() {
    return new Promise((resolve, reject) => {
        const sshClient = new Client();
        let isReady = false;
        logger.info("fetchFileList making SF connection");
        sshClient.on("ready", () => {
            isReady = true;
            logger.info("Ready");
            sshClient.sftp((err, sftp) => {
            if (err) {
                logger.error("Some error occoured ", { err });
                reject("Error establishing sftp connection");
            }
            logger.info("Sftp connection is successful");
            sftp.readdir(CONST.EXTRACT.FTP_DIRECTORY, (err, files) => {
                if (err) {
                reject(new CustomError("Sftp read dir", err));
                }
                // Read all file 'formats' from entity db
                sortFilesByTables(files)
                .then(result => {
                    resolve({ sshClient, sftp, result });
                })
                .catch(err => {
                    reject(new CustomError("Error sorting files by tables ", err));
                });
            });
            });
        });
        sshClient.on("error", err => {
            logger.error("Error connecting to sftp server ", err);
            webHook
            .send(
                utils.composeSlackMessage(
                "Error connecting to sftp server",
                CONST.EXPORT.SLACK_MESSAGE_TYPES.ERROR,
                err
                )
            )
            .catch(err => logger.error("Webkook catch ", err));
            reject(new CustomError("Error connecting to sftp server ", err));
        });

        sshClient.on("end", () => {
            if (!isReady) {
            logger.error(
                "fetchFileList on end Callback could not establish sftp connection"
            );
            reject(
                "fetchFileList on end Callback could not establish sftp connection"
            );
            }
        });

        sshClient.connect({
            host: ftpCredentials.host,
            port: ftpCredentials.port,
            username: ftpCredentials.username,
            password: ftpCredentials.password,
            readyTimeout: 90000
        });
    });
}

Sometimes when trying to connect, the end callback is invoked, but not the error or ready callback. Has anyone got any idea why this happens? Isn't the error callback supposed to happen when, a connection could not be established with the sftp server? (Earlier I only had ready and error callback, in this case neither was invoked and my server program hangs inside this promise).

The node module I am using is "ssh2": "^0.6.1",

0

There are 0 answers