• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 2 years ago

Reviews

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

Repository Details

Turn your single process code into a fault-resilient, multi-process service with built-in REST & CLI support. Restart or hot upgrade your web servers with zero downtime or impact to clients.

cluster-service

Build Status NPM version Dependency Status Bitdeli Badge

NPM NPM

Install

npm install cluster-service

https://npmjs.org/package/cluster-service

About

Turn your single process code into a fault-resilient, multi-process service with
built-in REST & CLI support. Restart or hot upgrade your web servers with zero
downtime or impact to clients.

Presentation:

http://x.co/bpnode

Video:

http://x.co/bpnodevid

Getting Started

Your existing application, be it console app or service of some kind:

// server.js
console.log("Hello World");

Leveraging cluster-service without adding a line of code:

npm install -g cluster-service
cservice "server.js" --accessKey "lksjdf982734"
// cserviced "server.js" --accessKey "lksjdf982734" // daemon

This can be done without a global install as well, by updating your package.json:

"scripts": {
	"start": "cservice server.js --accessKey lksjdf982734"
},
"dependencies": {
	"cluster-service": ">=0.5.0"
}

Now we can leverage npm to find our local install of cluster-service:

npm start

Or, if you prefer to control cluster-service within your code, we've got you covered:

// server.js
require("cluster-service").start({ workers: "./worker.js", accessKey: "lksjdf982734" });

// worker.js
console.log("Hello World"); // notice we moved our original app logic to the worker

Talk to it

Now that your service is resilient to worker failure, and utilizing all cores of your machine, lets talk to it. With your service running, type into the command-line:

restart all

or for a full list of commands...

help

or for help on a specific command:

help {command}

We can also issue commands from a seperate process, or even a remote machine (assuming proper access):

npm install -g cluster-service
cservice "restart all" --accessKey "my_access_key"

You can even pipe raw JSON for processing:

cservice "restart all" --accessKey "my_access_key" --json

Check out Cluster Commands for more.

Start Options

When initializing your service, you have a number of options available:

cservice "server.js" --accessKey "123"

Or via JSON config:

cservice "config.json"

Or within your node app:

// server.js
// inline options
require("cluster-service").start({ workers: "worker.js", accessKey: "123" });
// or via config
require("cluster-service").start({ config: "config.json" });

Options:

  • workers - Path of worker to start. A string indicates a single worker, forked based on value of workerCount. An object indicates one or more worker objects: { "worker1": { worker: "worker1.js", cwd: process.cwd(), count: 2, restart: true } }. This option is automatically set if run via command-line cservice "worker.js" if the .js extension is detected.
  • accessKey - A secret key that must be specified if you wish to invoke commands from outside your process. Allows CLI & REST interfaces.
  • config - A filename to the configuration to load. Useful to keep options from having to be inline. This option is automatically set if run via command-line cservice "config.json" if the .json extension is detected.
  • host (default: "localhost") - Host to bind to for REST interface. (Will only bind if accessKey is provided)
  • port (default: 11987) - Port to bind to. If you leverage more than one cluster-service on a machine, you'll want to assign unique ports. (Will only bind if accessKey is provided)
  • workerCount (default: os.cpus().length) - Gives you control over the number of processes to run the same worker concurrently. Recommended to be 2 or more to improve availability. But some workers do not impact availability, such as task queues, and can be run as a single instance.
  • cli (default: true) - Enable the command line interface. Can be disabled for background services, or test cases. Running cserviced will automatically disable the CLI.
  • ssl - If provided, will bind using HTTPS by passing this object as the TLS options.
  • run - Ability to run a command, output result, and exit. This option is automatically set if run via command-line cservice "restart all" and no extension is detected.
  • json (default: false) - If specified in conjunction with run, will only output the result in JSON for consumption from other tasks/services. No other data will be output.
  • silent (default: false) - If true, forked workers will not send their output to parent's stdio.
  • allowHttpGet (default: false) - For development purposes, can be enabled for testing, but is not recommended otherwise.
  • restartOnMemUsage (default: disabled) - If a worker process exceeds the specified memory threshold (in bytes), the process will be restarted gracefully. Only one worker will be restarted at a time.
  • restartOnUpTime (default: disabled) - If a worker process exceeds the specified uptime threshold (in seconds), the process will be restarted gracefully. Only one worker will be restarted at a time.
  • restartConcurrencyRatio (default 0.33) - The ratio of workers that can be restarted concurrently during a restart or upgrade process. This can greatly improve the speed of restarts for applications with many concurrent workers and/or slow initializing workers.
  • commands - A single directory, an array of directories, or a comma-delimited list of directories may be provided to auto-register commands found in the provided folders that match the ".js" extension. If the module exposes the "id" property, that will be the name of the command, otherwise the filename (minus the extension) will be used as the name of the command. If relative paths are provided, they will be resolved from process.cwd().
  • master - An optional module to execute for the master process only, once start has been completed.
  • proxy - Optional path to a JSON config file to enable Proxy Support.
  • workerGid - Group ID to assign to child worker processes (recommended nobody).
  • workerUid - User ID to assign to child worker processes (recommended nobody).

Console & REST API

A DPS Cluster Service has two interfaces, the console (stdio), and an HTTP REST API. The two interfaces are treated identical, as console input/output is piped over the REST API. The reason for the piping is that a DPS Cluster Service is intentionally designed to only support one instance of the given service running at any one time, and the port binding is the resource constraint. This allows secondary services to act as console-only interfaces as they pipe all input/output over HTTP to the already running service that owns the port. This flow enables the CLI to background processes. The REST API is locked to a "accessKey" expected in the query string. The console automatically passes this key to the REST API, but for external REST API access, the key will need to be known.

{ host: "localhost", port: 11987, accessKey: "lksjdf982734" }

Invoking the REST interface directly would look something like:

curl -d "" "http://localhost:11987/cli?cmd=help&accessKey=lksjdf982734"

Or better yet, use the run option to do the work for you:

cservice "help" --accessKey "lksjdf982734"
// same as
cservice --run "help" --accessKey "lksjdf982734"

Cluster Commands

While a Cluster Service may provide its own custom commands, below are provided out-of-the-box. Commands may be disabled by overriding them.

  • start workerPath [cwd] { [timeout:60000] } - Gracefully start service, one worker at a time.
  • restart all|pid { [timeout:60000] } - Gracefully restart service, waiting up to timeout before terminating workers.
  • shutdown all|pid { [timeout:60000] } - Gracefully shutdown service, waiting up to timeout before terminating workers.
  • exit now - Forcefully exits the service.
  • help [cmd] - Get help.
  • upgrade all|pid workerPath { [cwd] [timeout:60000] } - Gracefully upgrade service, one worker at a time. (continuous deployment support).
  • workers - Returns list of active worker processes.
  • health - Returns health of service. Can be overidden by service to expose app-specific data.
  • info - Returns summary of process & workers.

Commands & Events

Creating custom, or overriding commands and events is as simple as:

cservice "server.js" --commands "./commands,../some_more_commands"

Or if you prefer to manually do so via code:

var cservice = require("cluster-service");
cservice.on("custom", function(evt, cb, arg1, arg2) { // "custom" command
	// can also fire custom events
	cservice.trigger("on.custom.complete", 1, 2, 3);
};

cservice.on("test", function(evt, cb, testScript, timeout) { // we're overriding the "test" command
	// arguments
	// do something, no callback required (events may optionally be triggered)
};

// can also issue commands programatically
cservice.trigger("custom", function(err) { /* my callback */ }, "arg1value", "arg2value");

Cluster Events

Events are emitted to interested parties.

  • workerStart (pid, reason) - Upon exit of any worker process, the process id of the exited worker. Reasons include: "start", "restart", "failure", and "upgrade".
  • workerExit (pid, reason) - Upon start of any worker process. Reasons include: "start", "restart", "failure", and "upgrade".

Async Support

While web servers are automatically wired up and do not require async logic (as of v1.0), if your service requires any other asynchronous initialization code before being ready, this is how it can be done.

Have the worker inform the master once it is actually ready:

// worker.js
require("cluster-service").workerReady(false); // we're NOT ready!
setTimeout(funtion() {
	// dumb example of async support
	require("cluster-service").workerReady(); // we're ready!
}, 1000);

Additionally, a worker may optionally perform cleanup tasks prior to exit, via:

// worker.js
require("cluster-service").workerReady({
	onWorkerStop: function() {
		// lets clean this place up
		process.exit(); // we're responsible for exiting if we register this cb
	}
});

Access Control

Commands may be granted "inproc" (high risk), "local" (low risk), or "remote" (no risk). Setting access control can be done within the command, like so:

// exit.js
module.exports.control = function(){
	return "local";
};

Or may be overriden at runtime via:

// server.js
require("cluster-service").control({ "exit": "local" });

Proxy Support

Proxy mode specifically caters to Web Servers that you want to enable automatic versioning of your service. Any version requested (via versionHeader) that is not yet loaded will automatically have a worker process spun up with the new version, and after ready, the proxy will route to that worker.

Every version of your app must adhere to the PROXY_PORT environment variable like so:

require("http").createServer(function(req, res) {
  res.writeHead(200);
  res.end("Hello world!");
}).listen(process.env.PROXY_PORT || 3000 /* port to use when not running in proxy mode */);

Proxy Options

  • versionPath (default: same directory as proxy JSON config) - Can override to point to a new version folder.
  • defaultVersion - The version (folder name) that is currently active/live. If you do not initially set this option, making a request to the Proxy without a versionHeader will result in a 404 (Not Found) since there is no active/live version. Upgrades will automatically update this option to the latest upgraded version.
  • versionHeader (default: x-version) - HTTP Header to use when determining non-default version to route to.
  • workerFilename (default: worker.js) - Filename of worker file.
  • bindings (default: [{ port: 80, workerCount: 2 }]) - An array of Proxy Bindings.
  • versionPorts (default: 11000-12000) - Reserved port range that can be used to assign ports to different App versions via PROXY_PORT.
  • nonDefaultWorkerCount (default: 1) - If a version is requested that is not a default version, this will be the number of worker processes dedicated to that version.
  • nonDefaultWorkerIdleTime (default: 3600) - The number of seconds of inactivity before a non-default version will have its workers shut down.

Proxy Bindings

Binding options:

  • port - Proxy port to bind to.
  • workerCount (default: 2) - Number of worker processes to use for this binding. Typically more than 2 is unnecessary for a proxy, and less than 2 is a potential failure point if a proxy worker ever goes down.
  • tlsOptions - TLS Options if binding for HTTPS.
    • key - Filename that contains the Certificate Key.
      • cert - Filename that contains the Certificate.
      • pem - Filename that contains the Certificate PEM if applicable.

A full list of TLS Options: https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

Proxy Commands

Work like any other Cluster Commands.

  • proxy start configPath - Start the proxy using the provided JSON config file.
  • proxy stop - Shutdown the proxy service.
  • proxy version workerVersion workerCount - Set a given App version to the desired number of worker processes. If the version is not already running, it will be started. If 2 workers for the version are already running, and you request 4, 2 more will be started. If 4 workers for the version are already running, and you request 2, 2 will be stopped.
  • proxy promote workerVersion workerCount - Works identical to the proxy version command, except this will flag the version as active/live, resulting in the Proxy Config file being updated with the new defaultVersion.
  • proxy info - Fetch information about the proxy service.

Tests & Code Coverage

Download and install:

git clone https://github.com/godaddy/node-cluster-service.git
cd node-cluster-service
npm install

Now test:

npm test

View code coverage in any browser:

coverage/lcov-report/index.html

Change Log

Change Log

License

MIT

More Repositories

1

terminus

Graceful shutdown and Kubernetes readiness / liveness checks for any Node.js HTTP applications
JavaScript
1,831
star
2

kubernetes-client

Simplified Kubernetes API client for Node.js.
JavaScript
961
star
3

tartufo

Searches through git repositories for high entropy strings and secrets, digging deep into commit history
Python
457
star
4

procfilter

A YARA-integrated process denial framework for Windows
C++
397
star
5

compose-color-picker

Jetpack Compose Android Color Picker 🎨
Kotlin
375
star
6

svgs

svgs is a compatiblity layer between svg and react-native-svg
JavaScript
191
star
7

eslint-plugin-i18n-json

Fully extendable eslint plugin for JSON i18n translation files.
JavaScript
177
star
8

godaddy.github.io

Deprecated version of GoDaddy blog. See https://github.com/godaddy/engineering.
HTML
163
star
9

smart-private-npm

An intelligent routing proxy for npm with support for: private, whitelisted, and blacklisted packaged
JavaScript
139
star
10

ekke

Ekke is a test runner for React-Native, it allows you to execute your test code directly on the device enabling you to test in the same environment as your production users.
JavaScript
133
star
11

gasket

Framework Maker for JavaScript Applications
JavaScript
130
star
12

kubernetes-gated-deployments

Kubernetes Gated Deployments
JavaScript
123
star
13

activerecord-delay_touching

Batch up your ActiveRecord "touch" operations for better performance. ActiveRecord::Base.delay_touching do ... end. When "end" is reached, all accumulated "touch" calls will be consolidated into as few database round trips as possible.
Ruby
111
star
14

engineering

Jekyll website and blog showcasing open source projects by GoDaddy employees
HTML
84
star
15

yara-rules

YARA rules for use with ProcFilter
83
star
16

aws-okta-processor

Okta credential processor for AWS CLI
Python
82
star
17

warehouse.ai

A storage and developer workflow engine for enforcing arbitrary checks on ontologies of npm packages.
JavaScript
82
star
18

javascript

The official GoDaddy JavaScript styleguide.
JavaScript
76
star
19

asherah

Asherah is a multi-language, cross-platform application encryption SDK
C#
75
star
20

wp-reseller-store

Resell hosting, domains, and more right from your WordPress site.
PHP
62
star
21

react-img-carousel

A flexible image carousel built with React.js
JavaScript
60
star
22

jiractl

A command-line tool for managing Jira
JavaScript
56
star
23

lighthouse4u

LH4U provides Google Lighthouse as a service, surfaced by both a friendly UI+API, and backed by various storage clients (S3, ElasticSearch, etc) for all your query and visualization needs
EJS
56
star
24

slay

Rock-solid structured application layout for building APIs and web apps in Node.js.
JavaScript
49
star
25

next-rum

RUM Component for Next.js
JavaScript
48
star
26

timings

NodeJS/Express API to assert performance results during functional testing
JavaScript
45
star
27

addhoc

Handy little helper to create proper React HOC functions complete with hoisted statics and forwarded refs
JavaScript
41
star
28

datastar

A robust and feature rich ODM for Cassandra.
JavaScript
40
star
29

openstack-logstash

Logstash and Kibana configs for OpenStack Havana
JavaScript
37
star
30

node-openstack-wrapper

An OpenStack client for Node.js
JavaScript
33
star
31

gdapi-php

A PHP client for Go Daddy® REST APIs
PHP
31
star
32

opa-lambda-extension-plugin

A plugin for running Open Policy Agent (OPA) in AWS Lambda as a Lambda Extension.
Go
28
star
33

reduxful

Manage request data in Redux state by generating actions, reducers, and selectors automatically.
JavaScript
27
star
34

lazy-social-buttons

A JavaScript plugin to place social buttons on a page on user interaction (mouseover) to spare the initial page load from the 300kb+ download requests for social APIs.
JavaScript
25
star
35

serverless-aws-servicecatalog

An AWS Service Catalog enabling plugin for the popular Serverless project
JavaScript
24
star
36

react-safe-src-doc-iframe

A component which applies guards to srcdoc iframes in order to provide a predictable and safe experience to the user. Complements the sandbox native iframe attribute.
JavaScript
23
star
37

react-markdown-github

React component that renders Markdown similarly to Github's formatting
JavaScript
22
star
38

node-flipr

Feature flipping and configuration using yaml files.
JavaScript
21
star
39

domain-search

React-based domain search widget used for designing and building custom GoDaddy reseller storefronts
JavaScript
21
star
40

pullie

A GitHub bot that makes your PRs better
JavaScript
20
star
41

asset-system

asset-system is a cross platform SVG based asset system for React and React-Native. This mono-repo is the home for all asset-* packages.
JavaScript
20
star
42

docker-machine-godaddy

A Docker Machine driver plugin for GoDaddy Cloud Servers.
Go
19
star
43

carpenterd

Build and compile npm packages to run in the browser.
JavaScript
19
star
44

node-priam

A simple Cassandra driver for NodeJS. It wraps node-cassandra-cql with additional error/retry handling, external .cql file support, and connection option resolution from an external source.
JavaScript
19
star
45

external

Fitting for load React components from an external BigPipe server.
JavaScript
18
star
46

kibana4-backup

JavaScript
17
star
47

django-snow

ServiceNow Ticket Management App for Django based projects
Python
16
star
48

node-redis-ha

Redis high-availability client library for node
JavaScript
15
star
49

sample-size

This python project is a helper package that uses power analysis to calculate required sample size for any experiment
Python
14
star
50

node-config-shield

Safe and easy way for storing and retrieving sensitive data
JavaScript
13
star
51

bucket-service

A service to tag your tests to enable/disable without a code change
JavaScript
10
star
52

breakdancer

A breakpoint tracking utility
JavaScript
10
star
53

centos7-upgrade-scripts

Ansible playbook and supporting scripts for upgrading OpenStack compute/hypervisor hosts from CentOS 6 to 7
Shell
10
star
54

openstack-traffic-shaping

Python
9
star
55

tartufo-action

Searches through git repositories for high entropy strings and secrets, digging deep into commit history
Python
9
star
56

radpack

JavaScript
8
star
57

appetizer-bundle

Creates an uploadable bundle of your React-Native application so it can run on the appetize.io platform.
JavaScript
8
star
58

docker-node

Debian Docker images for Node.js with best practices in mind
Dockerfile
8
star
59

GDRouting

Objective-C
8
star
60

gdapi-python

A Python client for Go Daddy® REST APIs
Python
8
star
61

netmet

NetMet is networking tool that allows you to track and analyze network uptime of multi data centers installations
Python
7
star
62

godaddy-test-tools

gulp tools for testing node libraries with mocha and istanbul as well as linting using godaddy-style.
JavaScript
7
star
63

react-validation-context

Components for providing validation via React context.
JavaScript
7
star
64

openstack-ansible

Ansible playbooks for managing OpenStack infrastructure
7
star
65

out-of-band-cache

A generic cache for API clients with out-of-band refreshing
JavaScript
7
star
66

node-redirect-rules

JavaScript
7
star
67

exemplar

Deprecated: storybook rocket fuel to launch structured examples of React & React Native components
JavaScript
7
star
68

asherah-cobhan

Cobhan bindings for Asherah
Go
7
star
69

vault-cert-finder

Finds, parse and output X509 certificates stored in Hashicorp Vault
TypeScript
7
star
70

eslint-plugin-react-intl

Validation of locale ids used with react-intl functions/components like <FormattedMessage />, formatMessage and defineMessages.
JavaScript
7
star
71

gdapi-csharp

A C# client for Go Daddy® REST APIs
C#
6
star
72

tartufo-node

npm package shim for https://github.com/godaddy/tartufo
JavaScript
6
star
73

aws-liveness

AWS Liveness tools.
JavaScript
6
star
74

cobhan-go

Cobhan FFI is a system for enabling shared code to be written in Rust or Go and consumed from all major languages/platforms in a safe and effective way.
Go
6
star
75

cijtemplate

A template for continuous integration with Jenkins
Shell
6
star
76

lighthouse4u-lambda

Running Lighthouse4u in AWS Lambda
JavaScript
6
star
77

asherah-ruby

Application-layer encryption SDK
Ruby
6
star
78

node-http-cache

An extensible caching interface for HTTP traffic.
JavaScript
6
star
79

abstract-npm-registry

An test suite and interface for you can use to test various functional areas of an npm registry
JavaScript
6
star
80

asherah-python

Python
5
star
81

appetizer

A Node.js REST based API client for Appetize.io.
JavaScript
5
star
82

transform-url

Build URLs by transforming a template with params.
JavaScript
5
star
83

cobhan-python

Python wrapper library for the Cobhan FFI system
Python
5
star
84

node-connect-qos

Connect middleware that helps maintain a high quality of service during heavy traffic
TypeScript
5
star
85

timings-client-py

Python client for the timings API
Python
5
star
86

http-interception

Dumps requests and responses as newline delimited JSON that a browser performs when visiting a web page.
JavaScript
4
star
87

feedsme

Triggers appropriate rebuilds in the warehouse.ai system
JavaScript
4
star
88

mssql-pool-party

Extension of node mssql client providing failover, retry, stats, and more
JavaScript
4
star
89

cobhan-rust

Cobhan FFI is a system for enabling shared code to be written in Rust and consumed from all major languages/platforms in a safe and effective way.
Rust
4
star
90

short-css-vars

Optimize CSS variable names
JavaScript
4
star
91

spree_weight_based_shipping_calculator

Spree extension for weight-based shipping calculation
Ruby
4
star
92

joi-of-cql

Create cql type definitions from joi schema validations
JavaScript
4
star
93

hostwriter

API and CLI for querying and manipulating host files.
JavaScript
4
star
94

orglinter

A GitHub organization linting tool
JavaScript
3
star
95

gdapi-ui

An in-browser client for Go Daddy® REST APIs
JavaScript
3
star
96

carpenterd-worker

the worker process for carpenterd
JavaScript
3
star
97

node-gd-assets

CSS, JS, and Handlebars combiner, compressor, and server
JavaScript
3
star
98

node-http-cache-cassandra

A Cassandra provider for the extensible HTTP caching library http-cache.
JavaScript
3
star
99

cobhan-ruby

Ruby wrapper library for the Cobhan FFI system
Ruby
3
star
100

.github

Default community health files for GoDaddy Open Source
3
star