• Stars
    star
    229
  • Rank 174,666 (Top 4 %)
  • Language
    JavaScript
  • Created about 13 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatic and decentralized discovery and monitoring of nodejs instances with built in support for a variable number of master processes, service advertising and channel messaging.

node-discover

npm version

Automatic and decentralized discovery and monitoring of nodejs instances with built in support for a variable number of master processes, service advertising and channel messaging.

Why?

So, you have a whole bunch of node processes running but you have no way within each process to determine where the other processes are or what they can do. This module aims to make discovery of new processes as simple as possible. Additionally, what if you want one process to be in charge of a cluster of processes? This module also has automatic master process selection.

Compatibility

This module uses broadcast and multicast features from node's dgram module. All required features of the dgram module are implemented in the following versions of node

- v0.4.x
- v0.6.9+

Example

Be sure to look in the examples folder, especially at the distributed event emitter

var Discover = require('node-discover');

var d = Discover();

d.on("promotion", function () {
	/* 
		* Launch things this master process should do.
		* 
		* For example:
		*	- Monitior your redis servers and handle failover by issuing slaveof
		*    commands then notify other node instances to use the new master
		*	- Make sure there are a certain number of nodes in the cluster and 
		*    launch new ones if there are not enough
		*	- whatever
		* 
		*/
		
	console.log("I was promoted to a master.");
});

d.on("demotion", function () {
	/*
		* End all master specific functions or whatever you might like. 
		*
		*/
	
	console.log("I was demoted from being a master.");
});

d.on("added", function (obj) {
	console.log("A new node has been added.");
});

d.on("removed", function (obj) {
	console.log("A node has been removed.");
});

d.on("master", function (obj) {
	/*
		* A new master process has been selected
		* 
		* Things we might want to do:
		* 	- Review what the new master is advertising use its services
		*	- Kill all connections to the old master
		*/
		
	console.log("A new master is in control");
});

Installing

npm

npm install node-discover

git

git clone git://github.com/wankdanker/node-discover.git

API

Constructor

Discover(opts, callback)
  • opts - object
    • helloInterval : How often to broadcast a hello packet in milliseconds
      • Default: 1000
    • checkInterval : How often to to check for missing nodes in milliseconds
      • Default: 2000
    • nodeTimeout : Consider a node dead if not seen in this many milliseconds
      • Default: 2000
    • masterTimeout : Consider a master node dead if not seen in this many milliseconds
      • Default: 2000
    • address : Address to bind to
      • Default: '0.0.0.0'
    • port : Port on which to bind and communicate with other node-discover processes
      • Default: 12345
    • broadcast : Broadcast address if using broadcast
      • Default: '255.255.255.255'
    • multicast : Multicast address if using multicast
      • Default: null (don't use multicast, use broadcast)
    • mulitcastTTL : Multicast TTL for when using multicast
      • Default: 1
    • unicast : Comma separated String or Array of Unicast addresses of known nodes
      • It is advised to specify the address of the local interface when using unicast and expecting local discovery to work
    • key : Encryption key if your broadcast packets should be encrypted
      • Default: null (that means no encryption)
    • mastersRequired : The count of master processes that should always be available
    • weight : A number used to determine the preference for a specific process to become master
      • Default : Discover.weight()
      • Higher numbers win.
    • client : When true operate in client only mode (don't broadcast existence of node, just listen and discover)
      • Default : false
    • reuseAddr : Allow multiple processes on the same host to bind to the same address and port.
      • Default: true
      • Only applies to node v0.12+
    • ignoreProcess : If set to false, will not ignore messages from other Discover instances within the same process (on non-reserved channels), join() will receive them.
      • Default: true
    • ignoreInstance : If set to false, will not ignore messages from self (on non-reserved channels), join() will receive them.
      • Default: true
    • advertisement : The initial advertisement object which is sent with each hello packet.
    • hostname : Override the OS hostname with a custom value.
      • Default: null (use DISCOVERY_HOSTNAME env var or the OS hostname)
  • callback - function that is called when everything is up and running
    • signature : callback(err, success)

Attributes

  • nodes

Methods

promote()

Promote the instance to master.

This causes the old master to demote.

var Discover = require('node-discover');
var d = Discover();

d.promote();

demote(permanent=false)

Demote the instance from being a master. Optionally pass true to demote to specify that this node should not automatically become master again.

This causes another node to become master

var Discover = require('node-discover');
var d = Discover();

d.demote(); //this node is still eligible to become a master node.

//or

d.demote(true); //this node is no longer eligible to become a master node.

join(channel, messageCallback)

Join a channel on which to receive messages/objects

var Discover = require('node-discover');
var d = Discover();

//Pass the channel and the callback function for handling received data from that channel
var success = d.join("config-updates", function (data) {
	if (data.redisMaster) {
		//connect to the new redis master
	}
});

if (!success) {
	//could not join that channel; probably because it is reserved
}

Reserved channels

  • promotion
  • demotion
  • added
  • removed
  • master
  • hello

leave(channel)

Leave a channel

var Discover = require('node-discover');
var d = Discover();

//Pass the channel which we want to leave
var success = d.leave("config-updates");

if (!success) {
	//could leave channel; who cares?
}

send(channel, objectToSend)

Send a message/object on a specific channel

var Discover = require('node-discover');
var d = Discover();

var success = d.send("config-updates", { redisMaster : "10.0.1.4" });

if (!succes) {
	//could not send on that channel; probably because it is reserved
}

advertise(objectToAdvertise)

Advertise an object or message with each hello packet; this is completely arbitrary. Make this object/message whatever applies to your application that you want your nodes to know about the other nodes.

var Discover = require('node-discover');
var d = Discover();

d.advertise({
	localServices : [
		{ type : 'http', port : '9911', description : 'my awesome http server' },
		{ type : 'smtp', port : '25', description : 'smtp server' },
	]
});

//or

d.advertise("i love nodejs");

//or

d.advertise({ something : "something" });

start()

Start broadcasting hello packets and checking for missing nodes (start is called automatically in the constructor)

var Discover = require('node-discover');
var d = Discover();

d.start();

stop()

Stop broadcasting hello packets and checking for missing nodes

var Discover = require('node-discover');
var d = Discover();

d.stop();

eachNode(fn)

For each node execute fn, passing fn the node fn(node)

var Discover = require('node-discover');
var d = Discover();

d.eachNode(function (node) {
	if (node.advertisement == "i love nodejs") {
		console.log("nodejs loves this node too");
	}
});

Events

Each event is passed the Node Object for which the event is occuring.

promotion

Triggered when the node has been promoted to a master.

  • Could happen by calling the promote() method
  • Could happen by the current master instance being demoted and this instance automatically being promoted
  • Could happen by the current master instance dying and this instance automatically being promoted

demotion

Triggered when the node is no longer a master.

  • Could happen by calling the demote() method
  • Could happen by another node promoting itself to master

added

Triggered when a new node is discovered

removed

Triggered when a new node is not heard from within nodeTimeout

master

Triggered when a new master has been selected

helloReceived

Triggered when the node has received a hello from given one

helloEmitted

Triggered when the node sends a hello packet

Node Object

{ 
	isMaster: true,
	isMasterEligible: true,
	advertisement: null,
	lastSeen: 1317323922551,
	address: '10.0.0.1',
	port: 12345,
	id: '31d39c91d4dfd7cdaa56738de8240bc4',
	hostName : 'myMachine'
}

TODO

I have not tested large packets. The current version does not handle recombining split messages.

LICENSE

(MIT License)

Copyright (c) 2011 Dan VerWeire [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

node-object-mapper

Copy properties from one object to another.
JavaScript
276
star
2

node-function-rate-limit

Rate Limit any Function in node
JavaScript
68
star
3

node-redis-jsonify

Save JSON representation of objects to redis when using node_redis
JavaScript
58
star
4

node-tableify

Create HTML tables from JavaScript Objects
JavaScript
38
star
5

node-datagram-stream

Streaming UDP with bcast, mcast or direct options
JavaScript
32
star
6

node-object-to-xml

Convert any JavaScript object to XML
JavaScript
19
star
7

node-google-checkout

A Google Checkout API implementation for node.js
JavaScript
13
star
8

node-epl

An EPL printer library for nodejs
JavaScript
12
star
9

node-automesh

Automatically discover, connect to and accept TCP connections from other nodes on a subnet.
JavaScript
9
star
10

node-dns-express

An Express style DNS server
JavaScript
9
star
11

node-tracking-url

Get the carrier name and web url for a given tracking number
JavaScript
8
star
12

node-zsync

Synchronize/Replicate ZFS datasets - CLI and API
JavaScript
8
star
13

node-youtube-dl-server

A nodejs based front-end server to youtube-dl
JavaScript
8
star
14

node-usey

Generic middleware/plugin framework inspired by express.js's .use()
JavaScript
7
star
15

node-sftpjs

sftp api similar to mscdex/node-ftp using ssh2
JavaScript
6
star
16

gs1

gs1 checkdigit generation and validation in javascript
JavaScript
6
star
17

node-domain-name-parser

Parse domain name into tld, sld, domain, domainName, host
JavaScript
5
star
18

node-channeladvisor

API wrapper for ChannelAdvisor's SOAP service for node.js
JavaScript
4
star
19

connect-proxy

A simple Connect/Express middleware which proxies a request to another server.
JavaScript
4
star
20

node-unixodbc-isql-json

A hacky solution for querying ODBC data sources (including MS SQL) with nodejs.
C
4
star
21

node-object-mask

Copy an object based on a mask of allowed or denied properties
JavaScript
3
star
22

node-redis-gzip

Magical gzip/gunzip on calls to setz(), getz(), mgetz()
JavaScript
3
star
23

node-write-file-queue

A writeFile queue which reattempts to write after errors occur
JavaScript
3
star
24

symdb

A JSON database that uses symbolic links for indexing
JavaScript
3
star
25

haproxy-upstart-wrapper

A wrapper for haproxy to be used with Upstart
JavaScript
3
star
26

node-redis-index

Index and query arbitrary objects with Redis.
JavaScript
3
star
27

node-odbc-pool

A connection pool for node's ODBC module
JavaScript
3
star
28

web-object

Generic object collections wrapping drag/drop, sorting, filtering, toggle, show, hide functions.
JavaScript
3
star
29

approved-browser

Specify minimum versions of browsers and get accept/reject callbacks on approved/disapproved browsers
JavaScript
3
star
30

simple-vcard

A module to transform simple javascript objects into vCards and vLists
JavaScript
3
star
31

node-trimpath-template

trimpath-template templating language
JavaScript
3
star
32

node-transaction-group

Collect [optionally unique] objects over a period of time and then act on them
JavaScript
2
star
33

node-render-sender

On-demand image resizer/minfier/cacher
JavaScript
2
star
34

node-haproxy-log-parse

Parse haproxy log lines to JavaScript objects
JavaScript
2
star
35

node-proc-pid

Read select "files" from /proc/:pid/*
JavaScript
2
star
36

jquery-scrollify

Make HTML tables scrollable across browsers with jQuery
JavaScript
2
star
37

automesh-dnode

dnode plugin for automesh
JavaScript
2
star
38

webcolumns

A columns/content manipuliation API with drag and drop capability
JavaScript
2
star
39

node-dank-cast

Cast values to more specific types with default values if they can't be casted
JavaScript
2
star
40

node-token-collector

Collect string tokens if they match filters
JavaScript
2
star
41

node-print-url

JavaScript
2
star
42

node-inotify-run

Run scripts on inotify events
JavaScript
2
star
43

node-dank-moveFile

Pure JavaScript moveFile function for node.js
JavaScript
2
star
44

node-array-page

Get a page worth of records from an array
JavaScript
2
star
45

ofapi

Open Forum API for phpBB (XML/JSON-RPC)
PHP
2
star
46

node-layered-hash-table

A hash table made of layers where lower numbered layers over-ride the value of higher layers
JavaScript
2
star
47

node-templater

Template engine abstraction layer
JavaScript
2
star
48

node-find-alternate-file

Given a file path and a list of file extensions, find a file that exists
JavaScript
2
star
49

jquerytablehelper

Automatically exported from code.google.com/p/jquerytablehelper
JavaScript
1
star
50

symdb-rest

A rest interface to multiple symdb databases
JavaScript
1
star
51

greenhorn

A simple server that renders HTML using various engines and a configuration file with test data
JavaScript
1
star
52

node-is-object-empty

Check to see if an object is empty (has or does not have keys)
JavaScript
1
star
53

node-dank-csv

A simple CSV file parser
JavaScript
1
star
54

node-find-alternate-index

Find an index file if path is a directory
JavaScript
1
star
55

node-mutable-array

Mutable Array Functions
JavaScript
1
star
56

sortkeys

Sort the keys of a Javascript Object
JavaScript
1
star
57

node-redis-key

JavaScript
1
star
58

node-dank-do-while

An asynchronous do-while-like function for node.
JavaScript
1
star
59

nnfs

my progress through nnfs.io
JavaScript
1
star
60

node-dank-fileEmitter

Walk a directory and emit events for each object encountered
JavaScript
1
star
61

node-dank-queue

A versatile async flow control module for node
JavaScript
1
star
62

node-dank-copyFile

Pure JavaScript copyFile function for node.js
JavaScript
1
star
63

node-prefetch-cache

A cache store for node that can optionally prefill the cache store
JavaScript
1
star
64

node-image-serve

An HTTP image server that resizes, trims and caches
JavaScript
1
star
65

node-replace-empty-objects

Recursively replace empty objects with null
JavaScript
1
star
66

node-dank-map

A map function for node which can map over anything.
JavaScript
1
star
67

jsinclude

Load js and css files programatically in the browser at run-time.
JavaScript
1
star
68

freetds

C
1
star
69

node-object-array

Add array-like functionality to objects while using unique ids instead of numeric indexes
JavaScript
1
star
70

node-array-index

Create indexes based on arrays of objects
JavaScript
1
star
71

node-cachier

Caching with various backends
JavaScript
1
star
72

node-experiments

This is a repository of random node experiments I have done.
JavaScript
1
star
73

node-postal-io

A nodejs client for Postal
JavaScript
1
star
74

node-depresol

An asynchronous dependency resolver for node
JavaScript
1
star
75

node-dank-amap

An asynchronous map function which can map over anything for node.
JavaScript
1
star
76

node-usey-http

An express clone with usey at its core
JavaScript
1
star
77

node-cross-mash

Create a single object from an array of objects based on specified usage keys
JavaScript
1
star
78

event-pipeline

A simple event emitter which processes events in order
JavaScript
1
star
79

node-aloof

Filter Arrays of Objects
JavaScript
1
star
80

node-dropkey

From each object in an array, delete keys specified
JavaScript
1
star