Skip to content

Instantly share code, notes, and snippets.

@wallyqs
Created February 4, 2012 17:34
Show Gist options
  • Save wallyqs/1739102 to your computer and use it in GitHub Desktop.
Save wallyqs/1739102 to your computer and use it in GitHub Desktop.
Sample Fibers+EventMachine usage with NATS
require 'thin'
require 'sinatra/base'
require 'nats/client'
require 'fiber'
require 'json'
class App < Sinatra::Base
def initialize
@nats = NATS.start(:uri => "nats://localhost:4222")
super
end
# Expected number of components that should be running
# It fails if we underestimate the number of components
# with a "resume dead fiber called" error
# Taken from NATS#timed_request in cloud_controller
def get_components_info
expected = 20 # e.g. Max number of components running at once
timeout = 1
f = Fiber.current
results = []
sid = @nats.request("vcap.component.discover") do |msg|
results << msg
begin
f.resume if results.length >= expected
rescue
puts "More components running than expected"
end
end
@nats.timeout(sid, timeout, :expected => expected) { f.resume }
Fiber.yield
return results.slice(0, expected)
end
def start_monitoring_task
EM.next_tick do
Fiber.new do
components_info = get_components_info
components = []
components_info.each do |c|
components << JSON.parse(c)
end
puts "Number of components:"
p components.count
end.resume
end
end
get '/' do
EM.add_periodic_timer(1) { start_monitoring_task }
"Started the timer"
end
end
# Sample run:
#
# >> Thin web server (v1.3.1 codename Triple Espresso)
# >> Maximum connections set to 1024
# >> Listening on 0.0.0.0:9292, CTRL+C to stop
# 127.0.0.1 - - [04/Feb/2012 09:13:38] "GET / HTTP/1.1" 200 22 5.7494
#
# Number of components:
# 6
# Number of components:
# 7
# Number of components:
# 6
# Number of components:
# 0
# Number of components:
# 8
# Occasional error during dev:
#
# [2012-02-04 09:18:58] hm - 11126 3776 fe29 ERROR -- Eventmachine problem, SQLite3::BusyException: database is locked: SELECT "apps".* FROM "apps" WHERE "apps"."id" = 33 LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment