SFTP session ended early?
// readStream filePath
new Promise(function(resolve, reject) {
var ws = sftp.createWriteStream(filePath);
ws.on('finish', function() {
logger.warn('ws:', 1);
resolve();
});
readStream.pipe(ws);
}).then(function() {
logger.warn('end');
sshConnect.end();
return {result: 'success'};
});
the code run in mac or ubuntu is ok,but in red hat linux,it always get error:
[2015-09-19 13:40:26.836] [WARN] [default] - ws: 1
[2015-09-19 13:40:26.840] [WARN] [default] - end
{ result: 'success' }
events.js:85
throw er; // Unhandled 'error' event
^
Error: SFTP session ended early
at SFTPStream._cleanup (/home/lingyu.lly/workspaces/yangmei/node_modules/ssh2/node_modules/ssh2-streams/lib/sftp.js:191:15)
at SFTPStream.onFinish (/home/lingyu.lly/workspaces/yangmei/node_modules/ssh2/node_modules/ssh2-streams/lib/sftp.js:159:10)
at SFTPStream.emit (events.js:129:20)
at prefinish (_stream_writable.js:474:12)
at finishMaybe (_stream_writable.js:482:7)
at endWritable (_stream_writable.js:493:3)
at SFTPStream.Writable.end (_stream_writable.js:459:5)
at Channel.onend (_stream_readable.js:505:10)
at Channel.g (events.js:199:16)
at Channel.emit (events.js:129:20)
red hat information:
LSB Version: :core-4.0-amd64:core-4.0-ia32:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-ia32:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-ia32:printing-4.0-noarch
Distributor ID: RedHatEnterpriseServer
Description: Red Hat Enterprise Linux Server release 5.7 (Tikanga)
Release: 5.7
Codename: Tikanga
how to fix it?
Can you please try the master branch of ssh2-streams?:
# cd node_modules/ssh2
# npm install https://github.com/mscdex/ssh2-streams/tarball/master
I encountered the same problem. It was in code that had been working for some time; I have no idea what changed to cause it to start to fail. It could be that my code has always been wrong and I was just getting (un)lucky.
I moved my ftp.end() call from my stream 'end' handler to a stream 'finish' handler. This seems to have fixed the problem. At the very least, if I revert my change it fails consistently. I don't do anything on my ftp object after the end call so it is not a call ordering problem.
When I debugged the issue, I found that there was a "close" request still outstanding on the stream when I called ftp.end from the 'end' event handler, which is what made me try putting it in the 'finish' event.
@mscdex fwiw, I am using mikeal/sequest, a wrapper for ssh2 and I am seeing the same problem. I updated the ssh2-stream module per your instructions above, and I still see the same problem. If I can get some help crafting this call outside of the sequest wrapper, I'll gladly test in pure ssh2.
Here is my example code:
var sequest = require('/home/me/node_modules/sequest');
var test;
var reader = sequest.get('[email protected]', '/home/me/config.json', {
readyTimeout: 20000
}, function (error, stdout) {
if (error) {
throw error;
}
}
);
reader.pipe(test = process.stdout);
console.log(test);
returns the following:
reader.pipe(test = process.stdout);
{ _connecting: false,
_handle:
{ fd: 1,
writeQueueSize: 0,
owner: [Circular],
onread: [Function: onread] },
_readableState:
{ highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: false,
endEmitted: false,
reading: false,
calledRead: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
objectMode: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain: null,
_events:
{ end: { [Function: g] listener: [Function: onend] },
finish: [ [Function: onSocketFinish], [Object] ],
_socketEnd: [Function: onSocketEnd],
resize: [Function: onresize],
unpipe: [Function: onunpipe],
drain: [Function],
error: [Function: onerror],
close: { [Function: g] listener: [Function: onclose] } },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [] },
writable: true,
allowHalfOpen: false,
onend: null,
destroyed: false,
errorEmitted: false,
bytesRead: 0,
_bytesDispatched: 596,
_pendingData: null,
_pendingEncoding: '',
columns: 80,
rows: 24,
_type: 'tty',
fd: 1,
_isStdio: true,
destroySoon: [Function],
destroy: [Function] }
> console.log(test);
{ _connecting: false,
_handle:
{ fd: 1,
writeQueueSize: 0,
owner: [Circular],
onread: [Function: onread] },
_readableState:
{ highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: false,
endEmitted: false,
reading: false,
calledRead: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
objectMode: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain: null,
_events:
{ end: { [Function: g] listener: [Function: onend] },
finish: [ [Function: onSocketFinish], [Object] ],
_socketEnd: [Function: onSocketEnd],
resize: [Function: onresize],
unpipe: [Function: onunpipe],
drain: [Function],
error: [Function: onerror],
close: { [Function: g] listener: [Function: onclose] } },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [] },
writable: true,
allowHalfOpen: false,
onend: null,
destroyed: false,
errorEmitted: false,
bytesRead: 0,
_bytesDispatched: 3023,
_pendingData: null,
_pendingEncoding: '',
columns: 80,
rows: 24,
_type: 'tty',
fd: 1,
_isStdio: true,
destroySoon: [Function],
destroy: [Function] }
undefined
> {
"server":"myserver",
"server_port":8530,
"local_port":1080,
"password":"secret",
"timeout":600,
"method":"aes-256-cfb"
}
events.js:72
throw er; // Unhandled 'error' event
^
Error: SFTP session ended early
at SFTPStream._cleanup (/home/me/node_modules/sequest/node_modules/ssh2/node_modules/ssh2-streams/lib/sftp.js:195:15)
at SFTPStream.onFinish (/home/me/node_modules/sequest/node_modules/ssh2/node_modules/ssh2-streams/lib/sftp.js:159:10)
at SFTPStream.EventEmitter.emit (events.js:117:20)
at finishMaybe (_stream_writable.js:356:12)
at endWritable (_stream_writable.js:363:3)
at SFTPStream.Writable.end (_stream_writable.js:341:5)
at Channel.onend (_stream_readable.js:483:10)
at Channel.g (events.js:180:16)
at Channel.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
got the same problem.
try autoClose: true options
@damoore Can you post an example of how you moved the conn.end? I'm using createReadStream and the end event fires, but I don't ever get a finish event from the stream. It looks like there's a close event firing after the conn.end event is handled. Here's a sample of what I'm doing, just in case I might be doing something wrong here. (I left the conn.end in both end and finish handlers, for testing, but I've tried moving it to several places to no avail)
conn.on('ready', function() {
conn.sftp(function(err, sftp) {
var wstream = require('fs').createWriteStream('example.txt');
var rstream = sftp.createReadStream('example.txt');
rstream.pipe(wstream);
rstream.on('end', function() {
console.log('-- rstream.end Event');
conn.end();
});
rstream.on('finish', function() {
console.log('-- rstream.finish Event');
//conn.end();
});
wstream.on('finish', function() {
console.log('-- wstream.finish Event');
});
});
}).connect({
debug: console.log,
host: host,
port: 22,
username: username,
privateKey: require('fs').readFileSync(privateKey)
});
conn.on('end', function() {
console.log('-- conn.end Event');
});
DEBUG[SFTP]: Outgoing: Writing CLOSE
DEBUG: Outgoing: Writing CHANNEL_DATA (0)
-- wstream.finish Event
DEBUG: Outgoing: Writing DISCONNECT (BY_APPLICATION)
-- rstream.end Event
-- conn.end Event
DEBUG: Outgoing: Writing CHANNEL_CLOSE (0)
[Error: SFTP session ended early]
It's not in the conn end - it is an ftp end. Code fragment below. But I may not have checked that that on clause actually fires... Just did that. It is not getting called. Grrr.
connection.sftp(function (err, ftp) {
var stream = ftp.createReadStream(<filename>);
[...]
stream.on('finish', function() {
ftp.end();
});
I have spent some more time looking at this in a different case (uploading from the remote machine rather than downloading to it) and I found that by putting in a 1 second delay before I called sftp.end() I could make the problem go away. Looks like the stream is not quite cleaned up when the stream finish happens and the delay (plus giving up the thread, of course) allows some asynchronous code to happen. In other words, the underlying problem is a sequencing indeterminacy.
finish event is only on writeable stream, readable streams have end event.
Just figured out that you can safely close the connection (conn.cose()), in the read stream's close event.
Update: The autoClose was not specified, so the default true value was used.
var wstream = require('fs').createWriteStream('example.txt');
var rstream = sftp.createReadStream('example.txt');
rstream.pipe(wstream);
rstream.on('close', function() {
console.log('-- rstream.end Event');
conn.end();
})
That surprises me. I am resolving a promise in my write stream finish which eventually results in the ftp being ended. I would have expected the read stream close to be earlier than the write stream finish (I am also using pipe). But I suppose it is dependent on the implementation of pipe. I doubt the ordering of these events is something that is specified. Does someone know differently?
This should be fixed in the latest ssh2-streams. Reinstall your copy of ssh2 to pick up the new version.