diff --git a/lib/cartodb/varnish.js b/lib/cartodb/varnish.js index 977f5bdc..439ee46e 100644 --- a/lib/cartodb/varnish.js +++ b/lib/cartodb/varnish.js @@ -12,12 +12,27 @@ function VarnishClient(host, port, ready_callback) { var ready = false; var cmd_callback = null; var client = null; + var connected = false; + var connecting = false; function connect() { + if(connecting) return; + connecting = true; + console.log("VARNISH: connection"); ready = false; - client = net.createConnection(port, host); + if(!client) { + client = net.createConnection(port, host); + client.on('connect', function () { + console.log("VARNISH: connected"); + connected = true; + connecting = false; + }); + } else { + client.connect(port, host); + } } + connect(); client.on('data', function(data) { @@ -45,19 +60,27 @@ function VarnishClient(host, port, ready_callback) { }); client.on('close', function() { + console.log("[INFO] closed varnish connection"); self.close(); + connected = false; + connecting = false; }); // sends the command to the server function _send(cmd, callback) { cmd_callback = callback; - client.write(cmd + '\n'); + if(connected) { + client.write(cmd + '\n'); + } else { + connect(); + } } // run command if there is no peding response // fist param of the callback are the error, null // if all went ok this.run_cmd = function(cmd, callback) { + if(!connected) connect(); if(!cmd_callback) { _send(cmd, callback); } else {