Skip to content

Instantly share code, notes, and snippets.

@johnae
Created July 1, 2010 11:57

Revisions

  1. johnae created this gist Jul 1, 2010.
    80 changes: 80 additions & 0 deletions gistfile1.builder
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    require 'nanite'
    require 'eventmachine'

    include Nanite::CommonConfig

    options = {}
    # config should be put in config/nanite.yml
    config_file = File.expand_path(File.join(Rails.root, 'config', 'nanite.yml'))

    custom_config = File.exists?(config_file) ? (YAML.load(IO.read(config_file)) || {}) : {}
    options.update(custom_config.merge(options))

    options[:identity]=options[:identity]+"-#{UUIDTools::UUID.random_create.to_s}"

    def start_mapper_on_passenger
    logger = RAILS_DEFAULT_LOGGER

    th = Thread.current
    Thread.new do
    logger.info "Starting Nanite mapper on Passenger... identity: #{options[:identity]}"
    EM.run do
    begin
    Nanite.start_mapper(options)
    rescue => e
    logger.error e.to_s
    logger.error e.backtrace.join("\n ")
    ensure
    th.wakeup
    end
    end
    end
    Thread.stop
    end

    if ENV["NO_NM"].nil? || RAILS_ENV != "test" || dont_start_mapper
    if defined?(PhusionPassenger)
    PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
    start_mapper_on_passenger
    else
    if !EM.reactor_running?
    start_mapper_on_passenger
    end
    end
    end
    else
    Thread.new do
    is_thin = false
    if defined?(Thin)
    10.times do
    if EM.reactor_running?
    is_thin = true
    break
    end
    sleep 0.5
    end
    end

    if is_thin
    begin
    $stderr.puts "Starting Nanite mapper on Thin... identity: #{options[:identity]}"
    Nanite.start_mapper(options)
    rescue
    $stderr.puts "** Could not start Nanite mapper... probably the rabbit-mq-server is unreachable **"
    $stderr.puts " could mean the config/nanite.yml is missing, contains wrong values or just no way to make a connection"
    end
    else
    begin
    EM.run do
    $stderr.puts "Starting Nanite mapper... identity: #{options[:identity]}"
    Nanite.start_mapper(options)
    end
    rescue
    $stderr.puts "** Could not start Nanite mapper... probably the rabbit-mq-server is unreachable **"
    $stderr.puts " could mean the config/nanite.yml is missing, contains wrong values or just no way to make a connection"
    end
    end
    end
    end
    end