Custom Daemon with Rails 3 - ruby-on-rails

I'm trying to create a custom daemon that loads up the Rails environment.
My environment is as follows:
ruby-1.9.2-p180
rails 3.0.5
I did the following:
-Installed the daemons gem
-Installed daemon_generator plugin found here:
https://github.com/dougal/daemon_generator
-Generated a daemon: rails generate daemon listener
All this worked fine. When I run the daemon, it works.
However, as soon as I try to access an active record object like trying to retrieve a user, it blows up.
*** below you find the most recent exception thrown, this will be likely (but not certainly) the exception that made the application exit abnormally ***
#<NameError: method `recognize' not defined in Rack::Mount::RouteSet>
*** below you find all exception objects found in memory, some of them may have been thrown in your application, others may just be in memory because they are standard exceptions ***
#<NoMemoryError: failed to allocate memory>
#<SystemStackError: stack level too deep>
#<fatal: exception reentered>
#<NoMethodError: undefined method `eq' for nil:NilClass>
#<NameError: method `recognize' not defined in Rack::Mount::RouteSet>
Any thoughts on how to create a Daemon that loads up Rails 3.0.5?

I prefer to roll my own rails daemon controllers. Here is a simple example that works for most cases:
script/daemon
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
ENV["APP_ROOT"] ||= File.expand_path("#{File.dirname(__FILE__)}/..")
ENV["RAILS_ENV_PATH"] ||= "#{ENV["APP_ROOT"]}/config/environment.rb"
script = "#{ENV["APP_ROOT"]}/daemons/#{ARGV[1]}"
Daemons.run(script, dir_mode: :normal, dir: "#{ENV["APP_ROOT"]}/tmp/pids")
daemons/your_daemon_script.rb
require ENV["RAILS_ENV_PATH"]
loop {
... your code ...
}
You can control your deamons by using the following commands:
script/daemon run your_daemon_script.rb
script/daemon start your_daemon_script.rb
script/daemon stop your_daemon_script.rb
This enables me to easily add new daemons and I can easily load rails in each script if necessary.

I had a lot of problems trying get daemon_generator working. I got my daemon working by skipping the daemon_generator all together and just using the daemons gem (v1.1.3).
in urserver_control.rb (in root ruby app directory):
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
require 'TweetMsg'
Daemons.run('urserver.rb')
in urserver.rb:
#!/usr/bin/env ruby
require File.expand_path(File.join(File.dirname(__FILE__), 'config', 'environmen
t'))
require "rubygems"
--- insert your code here ---
You can test by running your server directly ruby urserver.rb or ruby urserver_controller run
And then once that is working starting and stopping the controllerruby urserver_control.rb {start | stop | run }

Looking at the code in https://github.com/dougal/daemon_generator/blob/master/lib/generators/daemon/templates/script.rb it appears they load things in the wrong order...
Looking at my delayed_job daemon script and config.ru they load config/environment.rb (which in turn loads application.rb and initializes the app)
So a possible fix would be to edit the generated script and make it only require 'config/environment.rb'
I tried this:
#!/usr/bin/env ruby
# You might want to change this
ENV["RAILS_ENV"] ||= "development"
require File.dirname(__FILE__) + "/../config/environment"
$running = true
Signal.trap("TERM") do
$running = false
end
while($running) do
# Replace this with your code
Rails.logger.auto_flushing = true
o = Order.last
Rails.logger.info "The latest order is #{o.id}"
sleep 10
end
and it yielded no errors... (Tried both Rails 3.0.3 and 3.0.5)

I had problems running daemon as is on my staging server (Rails 3.0.7, ruby 1.8.7, passenger 3.0.0). Neither
require File.dirname(FILE) + "/../../config/application"
Rails.application.require_environment!
nor
require File.dirname(FILE) + "/../config/environment"
Worked.
I fixed it by re-installing the standard config.ru in rails root (which I had de-installed to integrate w passenger... not sure now how I will get daemons & passenger to work together now ...)

Related

jruby no such file to load application.rb

I have a project in jRuby that I try to run.
So I'm installling jruby using rvm like this
rvm install jruby-9.1.15.0 (bc thats the version required by the project)
then im making sure that im actually using jruby by typing
ruby -v which shows me that I have jruby
next thing, I want to run the rails server so I'm typing
bundle exec rails server
and unfortunately I get an error:
/Users/foouser/Documents/Projects/fooproject/bin/config/application
LoadError: no such file to load -- /Users/foouser/Documents/Projects/fooproject/bin/config/application
require at org/jruby/RubyKernel.java:955
block in server at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:78
tap at org/jruby/RubyKernel.java:1741
server at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:75
run_command! at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:39
<main> at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands.rb:17
require at org/jruby/RubyKernel.java:955
<main> at bin/rails:5
I've tried googling that but to no avail. People seem to not encounter this issue at all. I'm sure it's got something to do with my setup because other people are successfully using said project.
Any ideas?
rails version - 4.2
jruby version - 9.1.15.0
EDIT:
after some digging, in bin/rails file the line defining the APP_PATH was like that:
APP_PATH = File.expand_path('../config/application', __FILE__)
which somehow made it looking for application.rb inside fooproject/bin/config instead of fooproject/config
but when I changed the line to
APP_PATH = File.expand_path('../../config/application', __FILE__)
it goes to the correct path where application.rb exist but still reports it as not existing.
the error is nearly the same (apart for path)
LoadError: no such file to load -- /Users/foouser/Documents/Projects/fooproject/config/application
require at org/jruby/RubyKernel.java:955
block in server at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:78
tap at org/jruby/RubyKernel.java:1741
server at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:75
run_command! at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:39
<main> at /Users/foouser/.rvm/gems/jruby-9.1.15.0-jrubu/gems/railties-4.2.10/lib/rails/commands.rb:17
require at org/jruby/RubyKernel.java:955
<main> at bin/rails:4
EDIT 2:
requested permissions for application.rb:
-rw-r--r-- 1 foouser staff 5818 20 Jun 15:12 config/application.rb
config.ru:
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
environment.rb
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
So, the solution I have is the "have you tried to turn it off and on again?" type.
I have deleted the whole project and cloned it again from the repo.
Everything is working now, it must have been something with my local env but I can't tell what.
Anyway, if you ever encounter something similar - purge and clone is definitely something you can try.

Turn a ruby script into an always running job

I have created a program that I need to run constantly. It currently lives at scripts/mailman. I start it by doing this:
sudo bundle exec rails runner script/mailman &
It seams to stop after I logout of the server. Here is the contents of my mailman program:
#!/usr/bin/env ruby
require "rubygems"
require "bundler/setup"
require "mailman"
require "rb-inotify"
Mailman.config.logger = Logger.new("/var/log/mailman.log")
Mailman.config.maildir = '/var/mail'
require File.dirname(__FILE__) + "/../../config/application"
Rails.application.require_environment!
Mailman::Application.run do
default do
begin
Bin.receive_mail(message)
end
end
end
What is a good way to start this program automatically and keep it running always? I am running this on Ubuntu.
Use the 'daemons' gem as suggested here:
Make a Ruby program a daemon?
Seems also to be very popular on RubyToolbox
https://www.ruby-toolbox.com/categories/daemonizing
I've found that the daemons gem works well for this.
Assuming your posted code lives in script/mailman.rb, you can make a file script/mailman_ctl:
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
Daemons.run('mailman.rb')
I typically give the options {:backtrace => true, :monitor => true} to the Daemons.run call, so that I have a better idea of what happened if the process ever dies.

Change default server for Rails

I installed the mongrel gem because I need it on my workstation for rare occasions, and now it's my default Rails (2) server. I know I could specify script/server webrick on the command line, but the fact is that I'd like to have my system (or app) default to webrick, and only use mongrel when specified.
Anybody know how to arrange that?
Specs: WinXP, Rails 2.3.12, Ruby 1.8.7
Ok here are a few options:
Option one - One off: Always add webrick as a command line arg
Open script/server and insert a line between the two requires
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
ARGV.unshift "webrick"
require 'commands/server'
Option two - Global: Edit the commands/server.rb file that launches rails
gem which railties -> tells you where the startup code is
Open the file at lib/commands/server.rb
Around line 45 edit the logic so that webrick is always launched by default.
server = Rack::Handler.get(ARGV.first) rescue nil
unless server
begin
server = Rack::Handler::WEBrick # was Mongrel
rescue LoadError => e
server = Rack::Handler::WEBrick
end
end
Option 3 - Cleanest but most involved:
Switch to Bundler and manage your dependencies directly. This is more work but positions you for switching to rails 3 at some point which might be nice depending on the life cycle of the application.
There's a tutorial for rails 2.3 here

Rails daemon do not start

I have Rails 3.0.3 project and I trying to create daemon by this steps:
http://railscasts.com/episodes/129-custom-daemon
I've installed gem daemons
sudo gem install daemons
Then I've install daemon_generator
rails plugin install https://github.com/dougal/daemon_generator.git
Then created daemon
rails generate daemon game_processor
When I try to run daemon
./lib/daemons/game_processor_ctl start
I got error:
./lib/daemons/game_processor_ctl:2:in `require': no such file to load -- rubygems (LoadError)
from ./lib/daemons/game_processor_ctl:2
Code of daemon:
#!/usr/bin/env ruby
require 'rubygems'
require "daemons"
require 'yaml'
require 'erb'
gem 'activesupport', '>=3.0.0.beta4'
require 'active_support'
# For some reason, ActiveSupport 3.0.0 doesn't load.
# Load needed extension directly for now.
require "active_support/core_ext/object"
require "active_support/core_ext/hash"
options = YAML.load(
ERB.new(
IO.read(
File.dirname(FILE) + "/../../config/daemons.yml"
)).result).with_indifferent_access
options[:dir_mode] = options[:dir_mode].to_sym
Daemons.run File.dirname(FILE) + "/game_processor.rb", options
So, What's wrong? Why it dies, when trying to require rubygems?
Are you on Windows or *nix system - on Windows you should use ruby game_processor.rb start instead of _ctl.
Also as you are using it with Rails - then i think Rails server should be started in required mode as well to make Daemon run properly.

Rails tests can't find test_helper

I'm trying to run individual tests through ruby test/unit/mytest.rb, but I always get a "no such file to load - test_helper" error. Google brought up a few suggestions, but none of them worked for me. I'm running Rails 3.0, Ruby 1.9.2 (through RVM) on Ubuntu 10.10
Here's what I've tried so far - any suggestions really appreciated
Changed the "require test_helper" to "require File.dirname(FILE) + "/../test_helper"
" in test/unit/mytest_test.rb. It brings back " no such file to load -- test/unit/../test_helper"
Tried running rvm test/unit/mytest_test.rb Same as above
Tried running ruby -I test/unit/mytest_test.rb. No messages to the terminal. After about 5 minutes waiting for something to happen, ctrl+c'd out of it
Any suggestions very appreciated - I'm stumped.
ruby 1.9.2 removed ".", the current directory, from the load path. I have to do this to get it to work:
require 'test_helper'
and call it like:
ruby -I. unit/person_test.rb
I was fighting this thing myself today and i dislike the big require with whole path to file and stuff...
In my case it was fault of Rakefile..
so now it looks like this:
require "bundler/gem_tasks"
require "rake/testtask"
Rake::TestTask.new do |t|
t.libs << "lib"
t.libs << "test" # here is the test_helper
t.pattern = "test/**/*_test.rb"
end
task default: :test
I know its old and has answer marked accepted, but maybe this will also help someone :)
have a nice day
I've added the following to the top of my test files.
require File.expand_path("../../test_helper", __FILE__)
This restores the previous behavior and allows the call to be simply:
ruby test/unit/person_test.rb
Maybe you should run your test cases in this way:
$ rake test
There is no need to change the "require" statement from generated code if you use rake.
Tested with Ruby 1.9.3 and Rails 3.2.8
If you are creating a gem or engine, running rake test in the test dummy application directory will cause this error. Running rake test in the root of the gem will avoid this.
Rails 1.9 no longer includes the current directory in the LOAD_PATH, which causes this problem. You have a few options.
call the test with the -I option from the app dir:
ruby -I test test/functional/test_foo.rb
and use a require with no path:
require "test_helper.rb"
use a full path in the require.  Either
require 'pathname'
require Pathname.new(FILE).realpath.dirname.join('/../test_helper.rb')
or
require (File.dirname(File.realdirpath(__FILE__)) + '/../test_helper.rb')

Resources