ssh2 icon indicating copy to clipboard operation
ssh2 copied to clipboard

Not able to connect to remote box multiple times

Open muthursyamburi opened this issue 8 years ago • 1 comments

Hi,

I am new to NodeJS world, and just trying out something. For my below issues, I Googled around and finally reaching here.

I am trying to connect to remotely via SSH to get the list of files with a specific naming pattern (step 1) and then read each of the files and process them (step 2). Step 1 is working fine and I am getting the list of files. However for step 2, it never gets into the on ready callback. I am using the latest and greatest ssh2 (v0.5.5).

Here is my code. Issue is that the readFile() method's conn.on('ready') never works fine. That means, the control never gets in to its callback method.

fileServer.js

function getFilesList(path, remotePath, dateFilter, matchFilter = true, callback) {
    var fileCnt = 0;
    var files = [];
    var conn = new Client();
    remotePath = pathCorrection(remotePath);
    conn.on('ready', function () {
        conn.sftp(function (err, sftp) {
            if (err) {
                conn.end(); throw err;
            }
            sftp.readdir(remotePath, function (err, list) {
                if (err) {
                    conn.end(); throw err;
                }
                list.forEach(function (file) {
                    if (file.attrs.isFile()) {
                        if (matchFilter) {
                            if (file.filename.match(dateFilter)) {
                                files.push(file.filename);
                            }
                        } else {
                            if (!file.filename.match(dateFilter)) {
                                files.push(file.filename);
                            }
                        }
                    }
                }, this);
                conn.end();
                callback(files);
            });
        });
    }).connect(cfg.getSFTPConfigObject());
}

function readFile(remotePath, filename, obj, callback) {
    var conn = new Client();
    remotePath = pathCorrection(remotePath);
    var buffer = [];
    var srcFilename = remotePath + filename;
    var destFile = (__dirname + "/" + filename).replace("//", "/");
    conn.on('ready', function () {
        conn.sftp(function (err, sftp) {
            if (err) throw err;
            var rstream = sftp.createReadStream(srcFilename);
            var wstream = fs.createWriteStream(destFile);
            rstream.pipe(wstream);
            rstream.on('error', function (err) { // To handle remote file issues
                log.error(err.message);
                conn.end();
                rstream.destroy();
                wstream.destroy();
            });
            rstream.on('end', function () {
                conn.end();
            });
            wstream.on('finish', function () {
                fs.readFile(destFile, 'utf8', function (err, buffer) {
                    if (err) throw err;
                    callback.call(obj, buffer);
                    fs.unlink(destFile);
                });
            });
        });
    }).connect(cfg.getSFTPConfigObject());
}

fileItem.js

module.exports.FileItem = class {
    constructor(filesList, max) {
        this.filesList = filesList;
        this.threadCnt = 0;
        this.MAX_THREADS = (max === undefined ? MAXIMUM_THREADS : max);
    }
run() {
        var keepChecking = false;
        var theadActive = new Array(this.MAX_THREADS);
        var fileCnt = this.filesList.length;
        this.filesList.forEach(function (file) {
            if (!theadActive[this.threadCnt]) {
                theadActive[this.threadCnt] = true;
                keepChecking = false;
                log.debug(`Found a hole at index [${this.threadCnt}]! Fitting File# [${this.threadCnt + 1}] there...`);
                this.processFile(file, function (err, obj) {
                    if (obj !== undefined) {
                        fileCnt--;
                        log.debug(`processFile completed -- Lets mark the thread active pool index [${obj.threadCnt}] as free...`);
                        theadActive[obj.threadCnt] = false;
                    }
                });
            } else {
                if (!this.keepChecking) {
                    log.debug('No holes found! Lets wait and keep checking...');
                    this.keepChecking = true;
                }
            }
            // If the MAX_THREADS reached and there are still items waiting to be allocated,
            // lets reset the this.threadCnt and check if there are any holes available(ie, items already finished).
            if (++this.threadCnt === this.MAX_THREADS && this.threadCnt < this.filesList.length) {
                log.debug(`Reached the max item limit of [${this.MAX_THREADS}]. Rechecking thread active pool from beginning to find a hole....`);
                this.threadCnt = 0;
            }
        }, this);

        while (fileCnt)  for(var i=0; i<1000000000; i++);
    }

processFile(file, cb) {
        .......
            this.readFile(file, function (isContinue, fileContents) {
                if (isContinue) {
                    this.validateFileContentFormat(file, fileContents, function (isContinue) {
                        if (isContinue) {
                            this.checkForDuplicates(file, fileContents, function (isContinue, colIndex) {
                                if (isContinue) {
                                    this.validatePrice(fileContents, colIndex, function (err, validPriceRecords) {
                                        if (err) {
                                            log.error(err);
                                        } else {
                                            this.dbInsertUpdatePriceRecords(validPriceRecords, function (err) {
                                                if (err) {
                                                    log.error(err);
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
                cb(new Error(), this);
            });
    }

Main Pgm

var fsrv = require('./fileServer');
var FileItem = require('./fileItem');
.............
fsrv.getFilesList('./', './', cfg.fpaCfg[cfg.fpaCC].file_name_format, true, processFiles);

function processFiles(filesList) {
    var fileTM = new FileItem(filesList, 75);
    fileTM.run();
..........
}

muthursyamburi avatar Jan 01 '18 21:01 muthursyamburi

You should always handle the various events on the connection object, including 'close'. It could be that the server is ending the connection immediately. Currently that doesn't cause an 'error' event to be emitted, but that is on the TODO list. In the meantime you can just listen for 'close' and check if you saw a 'ready' event or not (or wrap the callback so that it only gets called once and just call the wrapped callback in the 'close' event handler and in your 'ready' event handler.

mscdex avatar Jul 08 '19 19:07 mscdex