Unitech / pm2-interface

Deprecated
Other
90 stars 14 forks source link

Add disconnect method #2

Closed bretcope closed 10 years ago

bretcope commented 10 years ago

I was writing some test scripts with pm2-interface and found it frustrating that the scripts had to be terminated manually. I wanted a way to indicate I was done interacting with PM2, and allow my script to terminate automatically whenever the event loop became empty.

So I added a disconnect method which simply closes the two internally opened sockets.

this.disconnect = function () {
  self.sub_sock.close();
  self.rpc_sock.close();
};

Usage:

ipm2.on('ready', function() {

  // ...

  ipm2.disconnect();
});

This could have be done already outside this module by making those calls externally:

ipm2.on('ready', function() {

  // ...

  ipm2.sub_sock.close();
  ipm2.rpc_sock.close();
});

But this was non-obvious, seems like bad practice, and a easy way to break compatibility in the future.

I called it disconnect instead of close so that there would be less confusion about whether you're closing a connection to PM2, closing PM2 itself, or closing processes that PM2 is monitoring.

README is updated to reflect this addition.

I think this will help others. Let me know if you have any differing opinions.

bretcope commented 10 years ago

The scenario is specifically for when you do _not_ want a persistent connection. Once you call disconnect you are done. If you want a new connection to PM2, you would have to start over by calling ipm2 = require('pm2-interface')();, and then ipm2.on('ready') again. Perhaps this should be more explicitly spelled out in the README.

I'm working on a Node.js project here at Stack Exchange and I really like PM2, but we want to be able to interact with it better programmatically. The primary use case is definitely test scripts. It would be easier to build a test suite which uses PM2 for setup and teardown if pm2-interface didn't always keep connections alive.

But also, for short scripts, it just seems like better practice to me to disconnect the sockets and let node exit when it's ready, rather than forcing it to end at a specific time with process.exit.

jmingov commented 10 years ago

^^ thanks for the explanation.

Hey @bretcope some questions:

The scenario:

Im developing a realtime pm2-manager, as i understand the sockets are designed for persistent conection, then i call the ipm2.on('ready', function() {} one time, and then start listening the bus.socket and sending rpc calls to pm2.

If i call ipm2.disconnect(); , ill need to call the ipm2.on('ready', function() {} each time i need a ipm2.rpc method? Ill lose the realtime notifications provided by the ipm2.bus too?

If these both are true, these method only should be used in the tests?

Thanks

these should be merged tho.

The ipm2.disconnect(); can be useful