Undefined is not a function
We are running 100+ nodes and noticed about 10% of them dying daily with "undefined is not a function" and limited stack trace:
"undefined is not a function date=Fri Sep 13 2013 03:53:09 GMT+0000 (UTC), pid=889, uid=502, gid=502, cwd=/opt/our/node-server, execPath=/usr/bin/node, version=v0.10.16, argv=[/usr/bin/node, /opt/our/node-server/our-node.js], rss=474451968, heapTotal=115795712, heapUsed=74638544, loadavg=[0.0087890625, 0.00537109375, 0], uptime=751948.812361802, trace=[column=13, file=node.js, function=process._tickCallback, line=415, method=_tickCallback, native=false], stack=[TypeError: undefined is not a function, at process._tickCallback (node.js:415:13)]"
I have scanned the code to check where function to nextTick is not wrapped and only found two instances in websocket lib and in express ( middleware / limit.js ).
I have then added additional check before calling next tick to check whether callback is undefined, so in WebsocketConnection.js it was:
process.nextTick(this.outgoingFrameQueueHandler);
+ if ( !this.outgoingFrameQueueHandler ) {
+ throw new Error( "nextTick will crash node - WebsocketConnection.js" );
+ }
And few hours later I got the crash:
"Thu, 19 Sep 2013 16: 16: 21 GMT - error: uncaughtException: nextTick will crash node - WebsocketConnection.js date = Thu Sep 19 2013 16: 16: 21 GMT + 0000(UTC),
pid = 2213,
uid = 502,
gid = 502,
cwd = /opt/our / node - server,
execPath = /usr/bin / node,
version = v0.10.16,
argv = [/usr/bin / node, /opt/our / node - server / ournode.js],
rss = 236617728,
heapTotal = 103412480,
heapUsed = 69955176,
loadavg = [0, 0, 0],
uptime = 1314941.257227379,
trace = [column = 9, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
function = WebSocketConnection.processOutgoingFrameQueue, line = 715, method = processOutgoingFrameQueue, native = false, column = 14, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
function = WebSocketConnection.sendFrame, line = 674, method = sendFrame, native = false, column = 10, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
function = WebSocketConnection.sendCloseFrame, line = 661, method = sendCloseFrame, native = false, column = 14, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
function = WebSocketConnection.drop, line = 330, method = drop, native = false, column = 18, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
function = WebSocketConnection.handleSocketData, line = 240, method = handleSocketData, native = false, column = 17, file = events.js,
function = CleartextStream.EventEmitter.emit, line = 95, method = EventEmitter.emit, native = false, column = 14, file = _stream_readable.js,
function = , line = 738, method = null, native = false, column = 17, file = events.js,
function = CleartextStream.EventEmitter.emit, line = 92, method = EventEmitter.emit, native = false, column = 10, file = _stream_readable.js,
function = emitDataEvents, line = 763, method = null, native = false, column = 5, file = _stream_readable.js,
function = CleartextStream.Readable.on, line = 684, method = Readable.on, native = false
],
stack = [Error: nextTick will crash node - WebsocketConnection.js, at WebSocketConnection.processOutgoingFrameQueue(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 715: 9), at WebSocketConnection.sendFrame(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 674: 14), at WebSocketConnection.sendCloseFrame(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 661: 10), at WebSocketConnection.drop(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 330: 14), at WebSocketConnection.handleSocketData(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 240: 18), at CleartextStream.EventEmitter.emit(events.js: 95: 17), at CleartextStream. < anonymous > (_stream_readable.js: 738: 14), at CleartextStream.EventEmitter.emit(events.js: 92: 17), at emitDataEvents(_stream_readable.js: 763: 10), at CleartextStream.Readable.on(_stream_readable.js: 684: 5)]"
Followed by "undefined is not a function" and node dying.
I looked a little bit closer and noticed this.outgoingFrameQueueHandler that processOutgoingFrameQueue passes to nextTick is effectively "recursion" as in constructor we have:
this.outgoingFrameQueueHandler = this.processOutgoingFrameQueue.bind(this);
On http://blog.nodejs.org/2013/03/11/node-v0-10-0-stable/ (faster process.NextTick) if I understand it right it says that this kind of recursion should be changed to use setImmediate instead on nextTick as of node v10.
I'm yet to find the exact scenario to reproduce it every time and confirm setImmediate fix but thought I'll share my findings straight away.
WebSocketConnection.handleSocketData, line = 240, method = handleSocketData, native = false, column = 17, file = events.js
corresponds to drop in
if (this.currentFrame.rsv1 || this.currentFrame.rsv2 || this.currentFrame.rsv3) {
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
"Unsupported usage of rsv bits without negotiated extension.");
}
I'll need to figure out how rsv bits got there, but still simulated it locally and its closed properly without crash. Problem is to figure out how this.outgoingFrameQueueHandler could get undefined ....
(and btw shouldn't it return there after call to drop ? )
moved error throw higher up to get frame data:
if (this.currentFrame.rsv1 || this.currentFrame.rsv2 || this.currentFrame.rsv3) {
+ if ( !this.outgoingFrameQueueHandler ) {
+ var sError = this.currentFrame.toString() + ", \n\npayload : " + this.currentFrame.binaryPayload.toString('utf8') + "\n\n";
+ throw new Error( sError );
+ }
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
"Unsupported usage of rsv bits without negotiated extension.");
}
so far managed to get two failures with following trace and details:
Tue, 24 Sep 2013 16:10:57 GMT - error: uncaughtException: Opcode: 7, fin: false, length: 69, hasPayload: true, masked: false,
payload : T / HTTP/1.1
Connection: Upgrade
Host: this-is-my-node-99.wsserver.
date=Tue Sep 24 2013 16:10:57 GMT+0000 (UTC), pid=13704, uid=502, gid=502, cwd=/opt/our/node-server, execPath=/usr/bin/node, version=v0.10.16, argv=[/usr/bin/node, /opt/our/node-server/ournode.js], rss=427270144, heapTotal=178599424, heapUsed=126924856, loadavg=[0.0048828125, 0.0107421875, 0], uptime=1750255.42065925, trace=[column=10, file=/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js, function=WebSocketConnection.handleSocketData, line=242, method=handleSocketData, native=false, column=17, file=events.js, function=CleartextStream.EventEmitter.emit, line=95, method=EventEmitter.emit, native=false, column=14, file=_stream_readable.js, function=, line=738, method=null, native=false, column=17, file=events.js, function=CleartextStream.EventEmitter.emit, line=92, method=EventEmitter.emit, native=false, column=10, file=_stream_readable.js, function=emitDataEvents, line=763, method=null, native=false, column=5, file=_stream_readable.js, function=CleartextStream.Readable.on, line=684, method=Readable.on, native=false, column=17, file=WebSocketConnection (/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js, function=new, line=71, method=null, native=false, column=22, file=/opt/our/node-server/node_modules/websocket/lib/WebSocketRequest.js, function=WebSocketRequest.accept, line=254, method=accept, native=false, column=17, file=/opt/our/node-server/modules/request_router.js, function=, line=77, method=null, native=false, column=17, file=events.js, function=WebSocketServer.EventEmitter.emit, line=95, method=EventEmitter.emit, native=false], stack=[Error: Opcode: 7, fin: false, length: 69, hasPayload: true, masked: false, , , payload : T / HTTP/1.1
, Connection: Upgrade
, Host: this-is-my-node-99.wsserver., , , at WebSocketConnection.handleSocketData (/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js:242:10), at CleartextStream.EventEmitter.emit (events.js:95:17), at CleartextStream.<anonymous> (_stream_readable.js:738:14), at CleartextStream.EventEmitter.emit (events.js:92:17), at emitDataEvents (_stream_readable.js:763:10), at CleartextStream.Readable.on (_stream_readable.js:684:5), at new WebSocketConnection (/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js:71:17), at WebSocketRequest.accept (/opt/our/node-server/node_modules/websocket/lib/WebSocketRequest.js:254:22), at WebSocketServer.<anonymous> (/opt/our/node-server/modules/request_router.js:77:17), at WebSocketServer.EventEmitter.emit (events.js:95:17)]
payload seems to be truncated handshake (?) and frame opcode is 7
initial googling mentions "T problem" with chrome 19 : https://code.google.com/p/bauglir-websocket/
but downloaded few dev and beta versions of chrome 19 from oldapps and it didnt trigger it :/
It was suggested its down to "x-webkit-deflate-frame" extension, but my understanding is extension is not used until after handshake so that client could know whether its supported. As it looks here client (whatever it is: browser ? proxy edited handshake from our client ?) is using (some) extension during handshake :/
Yet none of it explains why this.outgoingFrameQueueHandler is undefined :[
any help appreciated
looking at stack trace again:
at WebSocketConnection.handleSocketData (/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js:242:10),
at CleartextStream.EventEmitter.emit (events.js:95:17),
at CleartextStream.<anonymous> (_stream_readable.js:738:14),
at CleartextStream.EventEmitter.emit (events.js:92:17),
at emitDataEvents (_stream_readable.js:763:10),
at CleartextStream.Readable.on (_stream_readable.js:684:5),
at new WebSocketConnection (/opt/our/node-server/node_modules/websocket/lib/WebSocketConnection.js:71:17),
at WebSocketRequest.accept (/opt/our/node-server/node_modules/websocket/lib/WebSocketRequest.js:254:22),
at WebSocketServer.<anonymous> (/opt/our/node-server/modules/request_router.js:77:17),
at WebSocketServer.EventEmitter.emit (events.js:95:17)]
it looks to me as if the event is triggered as soon as we bind to socket's data event
...
this.socket.on('error', this.handleSocketError.bind(this));
this.socket.on('data', this.handleSocketData.bind(this));
this.socket.on('end', this.handleSocketEnd.bind(this));
this.socket.on('close', this.handleSocketClose.bind(this));
this.socket.on('drain', this.handleSocketDrain.bind(this));
// Disable nagle algorithm?
this.socket.setNoDelay(this.config.disableNagleAlgorithm);
// Make sure there is no socket inactivity timeout
this.socket.setTimeout(0);
this.outgoingFrameQueue = [];
this.outputPaused = false;
this.outgoingFrameQueueHandler = this.processOutgoingFrameQueue.bind(this);
...
but this.outgoingFrameQueueHandler is defined later I thought its all synchronous and therefore whole constructor code needs to execute before events could be emmited. Apparently not.
I think it was suggested somewhere already that binding on sockets event should be wrapped in nextTick (or setImmediate).
@theturtle32 what do you think ?
still few things to consider as I was digging into it :
- use setImmediate rather thn nextTick to trigger this.outgoingFrameQueueHandler
- return after drop if reserved bits set
- call eventEmmiter constructor (the other bug I raised some time ago)
and just to confirm my previous thinking I've added additional variable to track constructor steps completed when issue is triggered:
function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) {
this.constructorStep = 0;
this.config = config;
this.socket = socket;
this.protocol = protocol;
this.extensions = extensions;
this.remoteAddress = socket.remoteAddress;
this.closeReasonCode = -1;
this.closeDescription = null;
// We have to mask outgoing packets if we're acting as a WebSocket client.
this.maskOutgoingPackets = maskOutgoingPackets;
// We re-use the same buffers for the mask and frame header for all frames
// received on each connection to avoid a small memory allocation for each
// frame.
this.maskBytes = new Buffer(4);
this.frameHeader = new Buffer(10);
// the BufferList will handle the data streaming in
this.bufferList = new BufferList();
// Prepare for receiving first frame
this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
this.fragmentationSize = 0; // data received so far...
this.frameQueue = [];
// Various bits of connection state
this.connected = true;
this.state = STATE_OPEN;
this.waitingForCloseResponse = false;
this.closeTimeout = this.config.closeTimeout;
this.assembleFragments = this.config.assembleFragments;
this.maxReceivedMessageSize = this.config.maxReceivedMessageSize;
// The HTTP Client seems to subscribe to socket error events
// and re-dispatch them in such a way that doesn't make sense
// for users of our client, so we want to make sure nobody
// else is listening for error events on the socket besides us.
this.socket.removeAllListeners('error');
this.constructorStep = 1;
this.socket.on('error', this.handleSocketError.bind(this));
this.constructorStep = 2;
this.socket.on('data', this.handleSocketData.bind(this));
this.constructorStep = 3;
this.socket.on('end', this.handleSocketEnd.bind(this));
this.constructorStep = 4;
this.socket.on('close', this.handleSocketClose.bind(this));
this.constructorStep = 5;
this.socket.on('drain', this.handleSocketDrain.bind(this));
this.constructorStep = 6;
// Disable nagle algorithm?
this.socket.setNoDelay(this.config.disableNagleAlgorithm);
this.outgoingFrameQueue = [];
this.outputPaused = false;
this.constructorStep = 7;
this.outgoingFrameQueueHandler = this.processOutgoingFrameQueue.bind(this);
this.constructorStep = 8;
this.bytesWaitingToFlush = 0;
...
When error is triggered constructorStep is set to 2 !!! Node.js is not multithreaded so it must be imo that its getting into max recursive nextTick and going back to event loop forcefully... then triggers socket's data event and voila mystery solved ?
reading through https://github.com/Worlize/WebSocket-Node/issues/91 it looks like its a child issue but requires rsv bits to trigger
tried putting socket bindings inside next tick and socket resume/pause in WebsocketRequest but then I always get error. I think the problem is actually that we are trying to process handshake data that shouldn't be there anymore ?
Turned out important bit is to have it all working on ssl as with unsecure connection nextTick or pause/resume does not seem to trigger it anymore. I'll try to find simplest reproducible server/client for it
To summarize: It happens occasionally in production that binding on socket's data event it will trigger straight away with handshake data. Since handshake data starts with "GET / HTTP/1.1..." GE is read as frame data and translated to frame opcode 7. Reserved bits check triggers connection drop which in the end passes undefined outgoingFrameQueueHandler to nextTick that crashes node without stack trace.
Since its still unknown to me how to trigger this particular scenario I have setup code that makes opcode 7 happen every time: issueServer.js
//issueServer.js
var WebSocketServer = require('websocket').server;
var fs = require( 'fs' );
var http = require('http');
var https = require('https');
var config = {
key : fs.readFileSync( "conf/privatekey.pem" ) ,
cert : fs.readFileSync( "conf/certificate.pem" )
};
var httpsServer = https.createServer( config );
var httpServer = http.createServer();
var wsServer = new WebSocketServer({
httpServer: httpsServer,
autoAcceptConnections: false
});
var unsecureWsServer = new WebSocketServer({
httpServer: httpServer,
autoAcceptConnections: false
});
var onRequest = function(request) {
request.accept( null, request.origin );
console.log((new Date()) + ' Connection accepted.');
}
unsecureWsServer.on( 'request', onRequest );
wsServer.on( 'request', onRequest );
httpServer.listen(8008, function() {
console.log((new Date()) + ' Unsecure server is listening on port 8008' );
});
httpsServer.listen(8009, function() {
console.log((new Date()) + ' Secure server is listening on port 8009' );
});
issueClient.js:
//issueClient.js
var WebSocketClient = require('websocket').client;
var fs = require( 'fs' );
var Client = function( infSecure ) {
this.connect( infSecure ? true : false );
};
var p = Client.prototype;
p.connect = function( infSecure ) {
var options = {
tlsOptions : {
key : fs.readFileSync( "conf/privatekey.pem" ) ,
cert : fs.readFileSync( "conf/certificate.pem" )
}
}
var wsClient = new WebSocketClient( options );
wsClient.on('connectFailed', this.onFail );
wsClient.on( 'connect', function( connection ) {
console.log( "connected" );
});
if ( infSecure )
wsClient.connect( 'wss://localhost:8009' );
else
wsClient.connect( 'ws://localhost:8008' );
}
p.onFail = function(error) {
console.log('Connect Error: ' + error.toString() );
}
var fSecure = process.argv[2] ? true : false;
var oClientTest = new Client( fSecure );
WebsocketRequest.js
...
WebSocketRequest.prototype.accept = function(acceptedProtocol, allowedOrigin, cookies) {
// TODO: Handle extensions
+ this.socket.pause();
var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);
+ this.socket.resume();
...
NOTE: you need to setup keys to make it work start server: node issueServer.js test with ws: node issueClient.js test with wss (opcode 7): node issueClient.js 1
additional log/error in WebsocketConnection.js proves its still handshake data being processed:
...
if (this.currentFrame.rsv1 || this.currentFrame.rsv2 || this.currentFrame.rsv3) {
+ var sError = this.currentFrame.toString() + ", \n\npayload : " + this.currentFrame.binaryPayload.toString('utf8') + "\n\n";
+ throw new Error( sError );
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
"Unsupported usage of rsv bits without negotiated extension.");
}
Error thrown:
Error: Opcode: 7, fin: false, length: 69, hasPayload: true, masked: false,
payload : T / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-
at {somewhere}\node_modules\websocket\lib\WebSocketConnection.js:232:10)
at CleartextStream.EventEmitter.emit (events.js:95:17)
at CleartextStream.<anonymous> (_stream_readable.js:720:14)
at CleartextStream.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:737:16
at process._tickCallback (node.js:415:13)
Wow there's a lot here. Thanks for taking so much time to dig into this! Let me mull over what you've got here. Do you have a theory about what the fix should be?
Well, I've spent some more time to minify reproducible example. Give me couple hours to post it - I got the case of using plain upgrade requests without use of Websocket lib so I think now its something internal within node...
edit: no I'm not sure about how to fix it yet as I don't fully understand why it happens. I consider moving function definition above event binds or not triggering nextTick if function is undefined - its all temporary though until we get to the bottom of it.... (by 'we' I mean community really as I think I reached dead end with my current knowledge)
apparently re-reading handshake data has now been fixed in Node 0.10.19 (https://github.com/joyent/node/pull/6209)
as to websocket library I would suggest:
- wrap event binding with nextTick to make sure WebsocketConnection initialization is complete before firing up data event handler (as suggested by @nilclass)
- use setImmediate rather than nextTick to trigger this.outgoingFrameQueueHandler (if its indeed recursive - how I understand it)
- return after drop if reserved bits set ( I noticed you made a commit already but its not part of 1.0.8, is it ?)
- call eventEmmiter constructor (the other bug I raised some time ago)
reopened referenced issue as still hapening in 0.10.20
I've experienced the same issue as @sajkog. I currently use Node v0.10.20 as well. Does there exist any way to deal with it?
Well I have an idea of how to make node intact but thats just temporary imo: go to WebsocketConnection.js and move event bindings to last line of constructor (with data as last one):
this.socket.on('error', this.handleSocketError.bind(this));
this.socket.on('end', this.handleSocketEnd.bind(this));
this.socket.on('close', this.handleSocketClose.bind(this));
this.socket.on('drain', this.handleSocketDrain.bind(this));
this.socket.on('data', this.handleSocketData.bind(this)); //this to be last line ?
you could also wrap them in nextTick I guess this will allow your node to survive through duplicated handshake - but you will also notce some connections being dropped due to reserved bits set.
EDIT: I call it event bindings but dunno if its proper eng ;) EDIT2: I personally haven't tried it yet so please let me know how it goes if you put it in. Also it might be worth to add return after if ( /reserved bit sets/) { drop ... RETURN !}
Thank You @sajkog for fast answer! I think, I can sacrifice couple of connections if it helps Node to survive :))
I'm going to try to get to this on Sunday. My apologies for taking so long here... My life has been crazy with other stuff, and I don't have as much time as I once did to maintain the library. My servers are still running Node 0.8.x.
If you have a pull request you can submit, that will help to expedite applying these fixes when I can get to it on Sunday.
Hi,
Sorry havent noticed your comment. I don't have any changes ready I was just considering them. Quite busy here as well so simply had no time. Best thing to do prob would be to change randomly reproducible code from https://github.com/joyent/node/issues/6277 and change it to use ws lib to test that changes dont make node dying anymore. I'll see if I can do anything in next few days. EDIT: it might be more than few days. current test suggest that for node >= 0.10.19 socket pause/resume should fix duplicated handshake read, for older though it would make issue appear on each connection - so imo its not something that could go to master/trunk
so i made 2 commits to my fork https://github.com/sajkog/WebSocket-Node/commit/618d37b3a7856771e88413cbb3d6dae58c6f410c - moves event bindings to the bottom of WebsocketConnection constructor. It seems to introduce some other issue on client's connect as running my tests I got "Parse Error" (very rare though - happened once in 100k connects). It helps to keep node alive when https://github.com/joyent/node/issues/6277 triggers but we then drop connection and try to send handshake back after its closed ... I just don't like it so don't think it should be merged
https://github.com/sajkog/WebSocket-Node/commit/fb83b42093f922eb4553444425f98679f3223bac - adds pause/resume around event bindings, requires node v0.10.19 to make the trick. This one should be considered temporary only as there is fix already in node v0.11.3 that makes whole handshake issue go away but ! ... that's not stable branch :|
Another way to make this issue go away is to use node v0.11.3 or anything higher that is stable (I think it might be v1.0 :/)
Considering above I don't think there is point to make pull request, especially that there are no tests around it...
bottom line issue fixed now and 0.10.22 released https://github.com/joyent/node/issues/6277
Awesome!
Sent from my iPhone
On Nov 13, 2013, at 1:40 AM, sajkog [email protected] wrote:
bottom line issue fixed now and 0.10.22 released joyent/node#6277
— Reply to this email directly or view it on GitHub.