Rails 3.1 / mysql2 error : "MySQL server has gone away" - ruby-on-rails-3

I'm experiencing trouble upgrading my rails 2.3.14 / ruby 1.8.7 app to 3.1.1/1.9.2 : I have some
(ActiveRecord::StatementInvalid) "Mysql2::Error: MySQL server has gone away"
errors happening sporadically. It's important to precise that I never had such issues with the 'mysql' gem on 2.3.14 and the exactly same db (so the bug shouldn't come from mysql (v5.5.10)).
Example :
$ rails c production
Loading production environment (Rails 3.1.1)
ruby-1.9.2-p290 :001 > ActiveRecord::Base.connection.active?
=> false
ruby-1.9.2-p290 :002 > exit
$ rails c production
Loading production environment (Rails 3.1.1)
ruby-1.9.2-p290 :001 > ActiveRecord::Base.connection.active?
=> true
This happens only with my (remote) production database, no problem with my local development db. I've tried to set "reconnect: true" in my database.yml but it led to a
Mysql2::Error: Host '****' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts':...
I've tried to isolate the problem with a little rb script only loading mysql2 and activerecord but I didn't manage to reproduce the bug that way (so it may be linked to the rails stack).
I can't go back from the 'mysql2' to the 'mysql' gem because of encoding issues ( http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/ ). As a consequence, I had to rollback my production to my rails 2.3.14 app, which saddens me very much...
Do you see what I can do to debug this ? I can't even find a sure way to reproduce the error... Have anyone met the same bug ?
I just found few people mentionning this bug (ex : https://github.com/brianmario/mysql2/issues/213) but not a solution.
Thanks for your help.

Ok, I think I solved my problem. I didn't notice it when I posted my question, but it seemed that the error was timeout related : after about 20s, activerecord losts its connection.
$ rails runner "sleep 23; puts ActiveRecord::Base.connection.active?"
=> true
$ rails runner "sleep 25; puts ActiveRecord::Base.connection.active?"
=> false
So I dug further and I realized that mysql and mysql2 gems didn't deal with the MySQL 'wait_timeout' param the same way : mysql gem doesn't set it thus uses the MySQL default value 28800, whereas mysql2 gem sets it at 2592000 if not defined in the database.yml.
But I have the impression that the value 2592000 is over the max value for this param : 2147483 ! Which could lead to the unexpected behavior I described...
I build a script test showing the bug : https://gist.github.com/1514154
And if I had some apparently random disconnect while loading rails console (cf my question), I think it's because of my app taking a long time to load and me sometimes waiting a few seconds before typing my command.
I can't explain why we are so few to encounter this problem. Perhaps it's specific to my conf (remote database, MySQL version ?). I've tried with another remote staging database : the bug didn't reproduce...
So as a conclusion, I will set wait_timeout: 2147483 in my database.yml. And maybe pull request rails...

Had a lot of lost connections - but I couldn't say if they went away due to the following tweak or elsewise :/
Had to throw the following script into initializers and add a line of configuration to each of my databases in my database.yml like this:
...
flags: <%= 65536 | 131072 %>
...
The script looks like this:
/config/initializers/mysql2.rb
module ActiveRecord
class Base
# Overriding ActiveRecord::Base.mysql2_connection
# method to allow passing options from database.yml
#
# Example of database.yml
#
# login: &login
# socket: /tmp/mysql.sock
# adapter: mysql2
# host: localhost
# encoding: utf8
# flags: 131072
#
# #param [Hash] config hash that you define in your
# database.yml
# #return [Mysql2Adapter] new MySQL adapter object
#
def self.mysql2_connection(config)
config[:username] = 'root' if config[:username].nil?
if Mysql2::Client.const_defined? :FOUND_ROWS
config[:flags] = config[:flags] ? config[:flags] | Mysql2::Client::FOUND_ROWS : Mysql2::Client::FOUND_ROWS
end
client = Mysql2::Client.new(config.symbolize_keys)
options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
end
end
end

Related

ruby-ldap gem not work in rails3 app, but work in rails console

I want to build a rails3 website authed with LDAP, so I chose ruby-ldap gem (not net/ldap) which we used in our old rails2 apps and works very well.
But I keep on getting weird error in rails3 app, See the codes below:
require 'ldap'
class WelcomeController < ApplicationController
def index
begin
#test = LDAP::Conn.new('10.72.64.11', 389)
rescue LDAP::Error
p LDAP::Error
end
render :text => "ok"
end
end
welcome#index is my root route. Most time, the app crashes when going to LDAP::Conn.new('10.72.64.11', 389), even I tried to use "pry" to debug and track, throwing
[1] 24797 trace trap rails s
and the WEBrick server will be terminated right that time.
Sometimes it throws another type error when I use "pry" to step,
#<NameError: uninitialized constant WelcomeController::LDAP>
While try it in the console, everything goes well.
1.9.3-p194 :001 > require 'ldap'
=> true
1.9.3-p194 :002 > #test = LDAP::Conn.new('10.72.64.11', 389)
=> #<LDAP::Conn:0x00000101289568>
1.9.3-p194 :003 >
Can you guide me out of this crazy stuff? I am using ruby 1.9.3p194 and rails 3.2.8
A few months later, I kind of figure out what the problem is...
The ruby-ldap gem has problem on running on the rails default server: Webrick.
Try Pow or Passenger, it works perfect!
After reading this page: http://www.ruby-forum.com/topic/62920
I tried moving the require 'ldap' from the controller or model file, and into the very top line of my environment file (xxxlocal.rb)
After I did that, I was able to run it ok in webrick also.

Javascript file is not updated in development with Rails

I changed a JS file under app/assets/javascripts but it is still the same. I deleted the file and re-created but the content is still the old one. This is my development.rb file:
App::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
config.serve_static_assets = false
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.default_url_options = { :host => "lvh.me:3000" }
# Raise exception on mass assignment protection for Active Record models
# config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
config.log_tags = [:uuid, :remote_ip]
end
The JS file is loaded inside the header tag with this code:
<script src="/assets/deals.js?body=1" type="text/javascript"></script>
which is the normal way JS is loaded in development
Try to clear precompiled assets:
bundle exec rake assets:clean
Try to delete the tmp folder and then restart the server - rails s.
That will do it.
bundle exec rake assets:clean and then bundle exec rake assets:precompile
Or delete the public/assets folder, and restart the app
Check for sprockets-rails gem
In my case I upgraded to Rails 7, and for some reason, the javascript files were not updated. Spent many hours trying to work out why.
I finally discovered the culprit - in my case - somehow, I had removed the sprockets-rails gem. I could have easily lost many months trying to figure this out.
I have similar issue in my app running Rails 6 and 7. When I add console.log into one of the javascript controllers there won't be any log in the browser console, and it looks like the console.log is not even there.
I have been having issue for quite some time and have not been able to pinpoint the exact reason, it might be due to bundler installed globally, conflict between rvm and asdf, config for overmind, yarn or npm. But I found the 3 commands that resolve this problem for some time and I usually run them one after another
rails assets:clobber
rake tmp:cache:clear
rake assets:precompile

"database configuration does not specify adapter" error with PG gem in Rails 3.2

Upon running "rake db:migrate", I'm getting an "database configuration does not specify adapter" error.
Here's my database.yml:
development:
 adapter: postgresql
 database: development
 username: ##########
 password: ##########
 host: localhost
 pool: 5
 timeout: 5000
My Gemfile lists:
gem 'pg'
Figured out what it was. I skyped the database.yml to myself, and it inserted a ton of invisible characters which prevented the YAML from being read.
In my case
RAILS_ENV=development rake db:migrate
did the trick.
Have you made sure you set the environment to development?
It's export RAILS_ENV=development on my mac.
I was also getting this error after some recent changes to my Rails app. First the error showed up in the unicorn logs, so I tried running rake db:setup, and got the error there too.
In my case, I somehow got an extra space placed in front of the test database definition. So my database.yml looked like this:
...
test:
adapter: postgresql
...
production:
adapter: postgresql
...
instead of this:
...
test:
adapter: postgresql
...
production:
adapter: postgresql
...
I removed the space and that fixed the issue.

Rails 3 - Error after deploying to Heroku

I have an application working in localhost and also heroku. The last time that I pushed the new version to heroku I got an error during heroku db:migrate and did heroku db:push and everything was ok.
I get the following error when executing the App.
/app/.bundle/gems/ruby/1.9.1/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:206:in `const_missing_from_s3_library': uninitialized constant AnswersController::Authentication (NameError)
Here is the relevant code
class AnswersController < ApplicationController
include Authentication
...
Authentication is a module defined in lib:
# encoding: utf-8
require 'base64'
require 'openssl'
module Authentication
...
It is working in localhost but not in heroku.
Any help??
Thanks
Try adding the lib folder to your the config.auto_load path in application.rb
config.autoload_paths += %W(#{config.root}/lib)
Also, take a look at this link.

Rails 3 console always starts in test environment

My rails 3 app always is stuck in the Test environment. When I call
rake db:reset
it resets the test database, but not the development one.
When I run the following code, it loads the test environment in the console:
rails c
Trying to specify the development environment also does not work:
jon#jon-laptop:~/id$ RAILS_ENV=development rails console
Loading test environment (Rails 3.0.8)
ruby-1.8.7-p334 :001 >
Starting the server does work normally:
rails s
This is very annoying. Any ideas on where I should look to resolve this?
Thanks in advance,
EDIT
I also tried going back in history to earlier commit to before the problem existed (I think) and it does not fix the problem...
The easiest way is to set the environment is probably by using the RAILS_ENV environment variable, e.g.:
RAILS_ENV=test rails console
Edit: Which version of Rails are you using? This works fine for me on 3.0.7:
rails c [environment]
E.g.
rails c development
I found the problem. I had the following lines in one of my initializers:
ActionMailer::Base.default_url_options[:host] = "localhost:3000" if Rails.env == "development"
ActionMailer::Base.default_url_options[:host] = "localhost:3000" if Rails.env = "test"
Can you spot the mistake???