rails renders fast but view slow - ruby-on-rails-4

Using rails 4.1 & 4.1.0rc2
We're having this weird issue with rendering:
I, [2014-04-13T07:45:28.856574 #5695] INFO -- : Started GET "/xpto" for xxx.xxx.xxx.xxx at 2014-04-13 07:45:28 +0000
I, [2014-04-13T07:45:28.916947 #5695] INFO -- : Processing by XptoController#index as HTML
D, [2014-04-13T07:45:28.952666 #5695] DEBUG -- : Cart Load (2.5ms) sql
D, [2014-04-13T07:45:29.000582 #5695] DEBUG -- : SQL (2.5ms) sql
D, [2014-04-13T07:45:29.004601 #5695] DEBUG -- : SQL (2.6ms) sql
I, [2014-04-13T07:45:29.026042 #5695] INFO -- : Rendered xpto/index.html.erb within layouts/application (58.4ms)
I, [2014-04-13T07:45:29.719445 #5695] INFO -- : Completed 200 OK in 802ms (Views: 735.2ms | ActiveRecord: 31.4ms)
As you can see in the log the render took 58.4ms but the "View" took 735.2ms. Every data is being preloaded and the view consists only of:
<h1>xptos</h1>
<% #xptos.each do |xpto| %>
<p>link: <%= link_to xpto.name, xptos_path(xpto) %> (ID: <%= xpto.id %>)</p>
<% end %>
The configurations used:
Rails.application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = true
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.assets.version = '1.0'
config.force_ssl = false
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.paperclip_defaults = {
storage: :fog,
fog_credentials: { provider: 'aws',
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
},
fog_directory: 'xpto-bucket'
}
end
Requests are being served directly by Unicorn with config:
log_path = 'log/unicorn.log'
pid_path = 'tmp/pids/unicorn.pid'
pid pid_path
worker_processes 8
timeout 15
preload_app true
listen 3000, backlog: 1025
stderr_path log_path
stdout_path log_path
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord)
end
after_fork do |server, worker|
ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
end
Is there any way to debug what is taking so long after render but before returning the response?

Related

uwsgi does not show 2xx and 3xx responses in the log

For testing purposes I need to see all the requests that come to my uwsgi application (and Django behind it), but I only see 4xx and 5xx, here is my uwsgi.ini config:
[uwsgi]
http-socket = :8080
;chdir = /code/
module = app.wsgi:application
master = true
processes = 2
logto = ./uwsgi.log
logdate = %%d/%%m/%%Y %%H:%%M:%%S
vacuum = true
buffer-size = 65535
stats = 0.0.0.0:1717
stats-http = true
max-requests = 5000
memory-report = true
;touch-reload = /code/config/touch_for_uwsgi_reload
pidfile = /tmp/project-master.pid
enable-threads = true
single-interpreter = true
log-format = [%(ctime)] [%(proto) %(status)] %(method) %(host)%(uri) => %(rsize) bytes in %(msecs) msecs, referer - "%(referer)", user agent - "%(uagent)"
disable-logging = true ; Disable built-in logging
log-4xx = true ; but log 4xx's anyway
log-5xx = true ; and 5xx's
log-3xx = true
log-2xx = true
ignore-sigpipe = true
ignore-write-errors = true
disable-write-exception = true
;chown-socket=www-data:www-data
Django itself produces 2xx logs perfectly in the same env (uwsgi logs are written to ./uwsgi.log file so not visible here)

error in fetching mail using griddler(mandrill)

I am implementing griddler(using Mandrill) to fetch e-mail in my app.
This is my class to receive mail
#app/email_receivers/incoming.rb
class EmailReceiver < Incoming::Strategies::Mandrill
def receive(mail)
%(Got message from #{mail.to.first} with subject "#{mail.subject}")
end
end
req = Rack::Request.new(Rails.env)
result = EmailReceiver.receive(req)
This is my rails controller that calls receive method of EmailReceiver class.
#emails_controller.rb
class EmailsController < ActionController::Base
def create
if EmailReceiver.receive(request)
render :json => { :status => 'ok' }
else
render :json => { :status => 'rejected' }, :status => 403
end
end
end
Routes for calling create method of EmailsController
#routes.rb
Rails.application.routes.draw do
post '/emails' => 'emails#create'
end
Note:- After running server in production environment
rails s -e production
I got this error
/home/bvc-2/.rvm/gems/ruby-2.2.1/gems/rack-1.6.4/lib/rack/request.rb:192:in `[]=': string not matched (IndexError)
Where "puts req" in
req = Rack::Request.new(Rails.env)
turns out to be:
#<Rack::Request:0xc3bace8 #env="production">
And my config/application.rb file is:-
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
ActionMailer::Base.smtp_settings = {
:address =>"smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "***#gmail.com",
:password => "pass*******",
:authentication => 'plain',
:enable_starttls_auto => true
}
module ComplaintSystem
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.active_job.queue_adapter = :delayed_job
config.time_zone = 'Mumbai'
config.active_record.default_timezone = :local
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
This type of error happens when you try to access a string variable as a Hash by mistake.
s = "hello world"
s["position"] = "programming is fun"
# > IndexError: string not matched
# > from (irb):5:in `[]='
# > from (irb):5
Look at your full stack trace and see where you are trying to do such operation.

Asset_Sync not pushing to S3

I am building a rails app on heroku, and want to deploy the js, css, and image files to a bucket on Amazon. I haven't found many resources for this, but I am using this (2012) tutorial for guidance; https://firmhouse.com/blog/complete-guide-to-serving-your-rails-assets-over-s3-with-asset_sync
The site is mainly css and js at the moment. Here is my code so far;
production.rb
Rails.application.configure do
config.action_controller.asset_host = "http://localize.s3.amazonaws.com"
config.cache_classes = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = false
config.assets.compress = true
config.assets.compile = false
config.assets.digest = true
end
initializers/asset_sync.rb
if defined?(AssetSync)
AssetSync.configure do |config|
config.fog_provider = ENV['FOG_PROVIDER']
config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID']
config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
config.fog_directory = ENV['FOG_DIRECTORY']
config.fog_region = ENV['FOG_REGION']
# Don't delete files from the store
config.existing_remote_files = "delete"
# Automatically replace files with their equivalent gzip compressed version
config.gzip_compression = true
# Use the Rails generated 'manifest.yml' file to produce the list of files to
# upload instead of searching the assets directory.
config.manifest = true
config.custom_headers = { '.*' => { cache_control: 'max-age=31536000', expires: 1.year.from_now.httpdate } }
end
end
Heroku Vars
AWS_ACCESS_KEY_ID: *****************
AWS_SECRET_ACCESS_KEY: *****************************
FOG_DIRECTORY: localize
FOG_PROVIDER: AWS
FOG_REGION: us-west-2
gemfile
gem 'rails', '4.1.1'
gem 'uglifier', '>= 1.3.0'
gem 'jquery-rails'
gem 'sdoc', '~> 0.4.0', group: :doc
#aws
gem "fog", "~>1.20"
gem 'asset_sync'
group :development do
gem 'thin'
end
group :production do
gem 'newrelic_rpm'
gem 'rails_12factor'
gem 'pg'
end
I also ran:
heroku config:add FOG_PROVIDER=AWS AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy
Along with
heroku config:add FOG_DIRECTORY=localize
And then when I run
bundle exec rake assets:precompile
Or
RAILS_ENV=production bundle exec rake assets:precompile
I get this output;
rake aborted!
AssetSync::Config::Invalid: Fog directory can't be blank, Aws access key can't be blank, Aws secret access key can't be blank
Anyone who has experience with rails, heroku, and S3 who could guide me in the right direction would be much appreciated. Thanks in advance.
Ok looking at your settings there seems to be a few things wrong, Ill add what i normally use and hopefully it will help you
Production.rb
ExampleApp::Application.configure do
config.action_controller.asset_host = "http://exampleapp.s3.amazonaws.com"
config.cache_classes = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = true
config.assets.compress = true
config.assets.compile = true
config.assets.digest = true
end
asset_sync.rb
if defined?(AssetSync)
AssetSync.configure do |config|
config.fog_provider = ENV['FOG_PROVIDER']
config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID']
config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
config.fog_directory = ENV['FOG_DIRECTORY']
config.fog_region = ENV['FOG_REGION']
# Don't delete files from the store
config.existing_remote_files = "delete"
# Automatically replace files with their equivalent gzip compressed version
config.gzip_compression = true
# Use the Rails generated 'manifest.yml' file to produce the list of files to
# upload instead of searching the assets directory.
config.manifest = true
config.custom_headers = { '.*' => { cache_control: 'max-age=31536000', expires: 1.year.from_now.httpdate } }
end
end

Vagrant permissions issue with NFS - files owned by unknown user

I have an NFS share on my Vagrant VM. It works but it can't write files (Symfony2 app, needs to write to app/cache/prod/sessions).
If I use "non-NFS" shares it works, but is dog slow!
From within the guest VM, /var/www/fh-admin is owned by user 501 group root, which I assume is a user on my host OS (OSX)?
Here is my Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = '2'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = 'precise64'
config.vm.box_url = 'http://files.vagrantup.com/precise64.box'
#config.vm.network :private_network, ip: '192.168.33.12'
config.vm.network :private_network, ip: "101.0.0.101", :netmask => "255.255.0.0"
config.vm.boot_timeout = 60
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.provision :ansible do |ansible|
ansible.limit = 'all'
ansible.sudo = true
ansible.playbook = '../fh-ansible/fh.yml'
ansible.inventory_path = 'inventory.ini'
ansible.verbose = "v"
end
config.vm.synced_folder '.', '/var/www/fh-admin', :nfs => { :mount_options => ["dmode=777","fmode=666"] }
config.vm.synced_folder '/var/www/surveyor-cordova/assets/www', '/var/www/fhapp', :nfs => { :mount_options => ["dmode=777","fmode=666"] }
config.vm.provider :vmware do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
end
config.vm.provider "vmware_fusion" do |v|
v.vmx["memsize"] = "2048"
v.vmx["numvcpus"] = "2"
end
end
One option would be to not store session data within the NFS share. There's details on how to move it on this blog post by Benjamin Eberlei: http://www.whitewashing.de/2013/08/19/speedup_symfony2_on_vagrant_boxes.html. I think you can also specify the Symfony2 session dir independently though config if you don't want to go down that involved route.
Adapt this to your requirements:
config.vm.synced_folder "./", "/var/www/fh-admin", id: "unique-id", type: nil,
group: 'www-data', owner: 'www-data', mount_options: ["dmode=775", "fmode=764"]
This assumes the group/user www-data exists within the box you are using.
This will work for non-NFS, and as far as I am aware NFS does not accept those extra flags (per mitchellh)

rails 4 flash not persisting across redirect "ActionDispatch::Request::Session -- not yet loaded"

I am having a weird issue where a flash message is not persisting across redirects in a Rails 4.0.2 application. I suspect that the problem has something to do with the session not yet being loaded when I try to access the flash hash as I am logging the session and getting the following output:
#<ActionDispatch::Request::Session:0x7ffda10835a8 not yet loaded>
I am trying to update an asset in the 'assets_controller' and then redirect to the 'home' action of the 'dashboard_controller' if the asset was successfully updated. My code is as follows:
AssetsController:
def update
#asset = Asset.update_asset(asset_parameters, params[:id])
if #asset.errors.any?
flash.now[:error] = "There were some errors"
render 'edit'
else
flash[:success] = "Asset updated!"
logger.debug("flash in assets: #{flash.inspect}")
redirect_to root_path()
end
end
DashboardController:
def home
logger.debug("session #{session.inspect}")
logger.debug("flash in home #{flash.inspect}")
res = Bid.bids_query({:generation => 'current'})
#bids = []
#staging_jobs = []
res.each do |bid|
bid.staging_job_id ? #staging_jobs << bid : #bids << bid
end
end
Log Output:
Started PATCH "/assets/19" for 127.0.0.1 at 2014-03-16 21:45:53 -0700
Processing by AssetsController#update as HTML
flash in assets: #<ActionDispatch::Flash::FlashHash:0x007ff7abdcfc30 #discard=#<Set:
{}>, #flashes={:success=>"Asset updated!"}, #now=nil>
Redirected by /Users/louism2/rails_projects/rosebank-
b/app/controllers/assets_controller.rb:31:in `update'
Redirected to http://localhost:3000/
Completed 302 Found in 14ms (ActiveRecord: 2.4ms)
Started GET "/" for 127.0.0.1 at 2014-03-16 21:45:53 -0700
Processing by DashboardController#home as HTML
session #<ActionDispatch::Request::Session:0x7ffda10835a8 not yet loaded>
flash in home #<ActionDispatch::Flash::FlashHash:0x007ff7abe743e8 #discard=#<Set: {}>,
#flashes={}, #now=nil>
Completed 200 OK in 81ms (Views: 53.7ms | ActiveRecord: 2.6ms)
The issue had to do with the fact that my model was named "assets" and that was somehow conflicting with the asset pipeline. The trick was to prefix the asset pipeline with an identifier other than assets which you can specify in your application.rb file with the following line:
config.assets.prefix = '/new_name_for_asset_pipeline'