self assembling fabric of ruby daemons
= Nanite : A self-assembling fabric of Ruby daemons
Google Group: http://groups.google.com/group/nanite irc.freenode.net: #nanite
== Intro
Nanite is a new way of thinking about building cloud ready web applications. Having a scalable message queueing back-end with all the discovery and dynamic load based dispatch that Nanite has is a very scalable way to construct web application back-ends.
A Nanite system has two types of components. There are nanite agents, these are the daemons where you implement your code functionality as actors. And then there are mappers.
Mappers are the control nodes of the system. There can be any number of mappers, these typically run inside of your merb or rails app running on the thin webserver (eventmachine is needed) but you can also run command line mappers from the shell.
Each Nanite agent sends a ping to the mapper exchange every @ping_time seconds. All of the mappers are subscribed to this exchange and they all get a copy of the ping with your status update. If the mappers do not get a ping from a certain agent within a timeout @ping_time the mappers will remove that agent from any dispatch. When the agent comes back online or gets less busy it will re-advertise itself to the mapper exchange therefore adding itself back to the dispatch. This makes for a very nice self-healing cluster of worker processes and a cluster of front-end mapper processes.
In your Nanites you can have any number of actor classes. These actors are like controllers in Rails or Merb and this is where you implement your own custom functionality. An actor looks like:
class Foo include Nanite::Actor expose :bar def bar(payload) "got payload: #{payload}" end end Nanite::Dispatcher.register(Foo.new)
The methods that you 'expose' on the actors are advertised to the mappers like:
Foo#bar => /foo/bar Mock#list => /mock/list
Every agent advertises its status every time it pings the mapper cluster. The default status that is advertised is the load average as a float. This is used for the default request dispatching based on least loaded server.
You can change what is advertised as status to anything you want that is comparable() by doing something like this in your agent's init.rb file:
status_proc = lambda { MyApp.some_statistic_indicating_load }
This proc will be recalled every @ping_time and sent to the mappers.
This is the 'fitness function' for selecting the least loaded Nanite. You can dream up any scheme of populating this function so the mappers can select the right Nanites based on their status.
== A quick note about security:
Nanite security is based upon RabbitMQ vhosts so anything attached to one vhost can talk to anything else on the same vhost. So you generally want one vhost per app space.
== Installation
Nanite has a lot of moving parts. Follow the directions below and we'll get you up and running in no-time.
=== Install Erlang (OS X)
See the Erlang website for the latest info : http://www.erlang.org/download.html
In your chosen source dir which we'll refer to as :
cd wget http://www.erlang.org/download/otp_src_R12B-5.tar.gz tar -zxvf otp_src_R12B-5.tar.gz cd otp_src_R12B-5 ./configure --enable-hipe --enable-darwin-universal make sudo make install
=== Install Erlang (Linux .deb)
sudo apt-get install erlang-nox
=== Install Nanite Ruby Gem
Installing the gem gives us access to the various Nanite commands in the default binary path.
cd git clone git://github.com/ezmobius/nanite.git cd nanite rake gem sudo gem install pkg/nanite-.gem
=== Install EventMachine Ruby Gem
sudo gem install eventmachine
=== Install AMQP Ruby Gem
sudo gem install amqp
cd git clone git://github.com/tmm1/amqp.git cd amqp && rake gem && sudo gem install amqp-.gem
=== Install RabbitMQ from source tarball (OS X and generic Linux)
In short, you'll need a working erlang installation, python, and simplejson. If your python ("python -V") is 2.6, simplejson is included in your distribution. Otherwise, install simplejson:
easy_install simplejson
If you don't have easy_install, install setuptools from http://pypi.python.org/pypi/setuptools:
wget http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c9-py2.5.egg sh setuptools-0.6c9-py2.5.egg
and install simplejson, which is needed for the "make" step below.
These instructions assume the latest RabbitMQ release 1.5.3:
cd /root wget http://www.rabbitmq.com/releases/rabbitmq-server/v1.5.3/rabbitmq-server-1.5.3.tar.gz
cd /usr/local/lib/erlang/lib
tar -zxf ~/rabbitmq-server-1.5.3.tar.gz cd rabbitmq-server-1.5.3 make
Be sure to add the /usr/local/lib/erlang/lib/rabbitmq-server-1.5.3/scripts to your $PATH.
The following websites may also be useful:
=== Install RabbitMQ (Linux .deb)
wget http://www.rabbitmq.com/releases/rabbitmq-server/v1.5.3/rabbitmq-server_1.5.3-1_all.deb sudo apt-get install logrotate sudo dpkg -i rabbitmq-server_1.5.3-1_all.deb
== Test your installation
=== Test your Erlang install
Start an Erlang shell
erl
Enter the following commands in the Erlang shell (When installed correctly each should print a great deal of erlang config info):
rabbit:module_info().
Exit the Erlang shell with the following command (or Ctrl-c):
q().
=== Start RabbitMQ
All directories will be automatically set up on first run.
To run RabbitMQ in the foreground: sudo rabbitmq-server
To run RabbitMQ in the background: sudo rabbitmq-server -detached
To check status: rabbitmqctl status
To stop server: rabbitmqctl stop
You can learn more about RabbitMQ admin here: http://www.rabbitmq.com/admin-guide.html
=== Test Ruby/EventMachine/AMQP end-to-end with a running RabbitMQ instance
You can test that all the moving parts are working end-to-end by running one of the AMQP example programs. There are a number of example tests provided with AMQP but the one we will try simply queues and prints two messages immediately, and another one five seconds later.
cd /amqp ruby examples/mq/simple-get.rb
=== Test Nanite (finally)
First we'll do a little setup and run a script which adds an agent account (nanite), a mapper account (mapper) and a '/nanite' vhost to RabbitMQ. RabbitMQ broker must of course be running before you run this script.
cd nanite ./examples/rabbitconf.rb
Now lets run a few agents. Each of these is a long running process and needs to run in its own shell. Each agent also needs its own unique identity, or token to differentiate it from the other running agents. You can try opening a couple of them now if you like. The agents will generally provide no output when running. You can always get more help about the nanite command with 'nanite --help'.
First shell
cd examples/simpleagent nanite-agent --token fred
Second shell
cd examples/simpleagent nanite-agent --token bob
Now run a mapper. Mappers can be run from within your Merb or Rails app, from an interactive irb shell, or from the command line. For this example we'll run it from the command line so open a third shell window and run the following:
cd examples/simpleagent ./cli.rb
Which should soon return something like the following.
{"bob"=>"hello nanite"} # where the '--token bob' parameter was passed {"55a7f300c454203eacc218b6fbd2edc6"=>"hello nanite"} # where no '--token' was passed. auto-generated identity.
Now if you want to make this interesting, you can issue a Ctrl-c in one of the agent's windows to kill it. And then run cli.rb again. You should see that you still get a result back since the mapper is finding the remaining agent to do its work.
If you want to try requesting work to be done by an agent from an interactive command shell try the following. This assumes that you have the agents running as indicated in the example above ('>>' is the nanite shell prompt).
cd nanite ./bin/nanite-mapper -i -u mapper -p testing -v /nanite Starting mapper console
request('/simple/echo') {|res| p res }
By default this will dispatch to the agent with the lowest reported load average.
There are a few other selectors as well:
request('/foo/bar', 'hi', :selector => :all) {|res| p res }
request('/whatever/hello', 42, :selector => :random) {|res| p res }
You can create your own selectors based on arbitrary stuff you put in status from your agents see cluster.rb for examples of how least_loaded, all and random are implemented.
You can run as many mappers as you want, they will all be hot masters.
The calls are asynchronous. This means the block you pass to Nanite::Agent#request is not run until the response from the agent(s) have returned. So keep that in mind. Should you need to poll from an ajax web app for results you should have your block stuff the results in the database for any web front end to pick up with the next poll.
Another option to test your agents is to use nanite-admin
$ nanite-admin starting nanite-admin
Thin web server (v1.0.1 codename ?) Maximum connections set to 1024 Listening on 0.0.0.0:4000, CTRL+C to stop
and bring up the Nanite Control Tower at http://localhost:4000 .
Have fun!
== Web Framework Integration
The integration of Nanite into web frameworks depends on the web server running our application and, more importantly, if it uses EventMachine or not.
Thin is EventMachine-based, so we only need to make sure that the EventMachine reactor is already 'heated' up
Thread.new do until EM.reactor_running? sleep 1 end Nanite.start_mapper(:host => 'localhost', :user => 'mapper', :pass => 'testing', :vhost => '/nanite', :log_level => 'info') end
Mongrel on the other hand does not use EventMachine and therefore requires to wrap the start of our mapper
Thread.new do EM.run do Nanite.start_mapper(:host => 'localhost', :user => 'mapper', :pass => 'testing', :vhost => '/nanite', :log_level => 'info') end end
Using nanite with Passenger:
if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked if EM.reactor_running? EM.stop_event_loop EM.release_machine EM.instance_variable_set( '@reactor_running', false ) end Thread.current[:mq] = nil AMQP.instance_variable_set('@conn', nil) end
th = Thread.current Thread.new{ Nanite.start_mapper(:host => 'localhost', :user => 'mapper', :pass => 'testing', :vhost => '/nanite', :log_level => 'info') } Thread.stop end end
======= Where to put the mapper initialization code depends on the framework and our preference. For Rails the canonical place to start our mapper is within nanite.rb (or any other filename you prefer) in config/initalizers. In Merb we can use init.rb in config.
== Security
Nanite implements a secure serializer which can be used in place of the other serializers to encrypt the AMQP messages exchanged between the mappers and the agents
No open issues yet, or sync has not completed.