Server Bug Fix: Host multiple Rack apps on one server with multiple ports (using Apache and Passenger)

Original Source Link

I’ve search online and been reading documentation for Apache, Passenger, Rack, etc, but have yet to find a solution to my problem.

I have several Rack (ruby)-based apps, located in

/home/web/sites/app1
/home/web/sites/app2
/home/web/sites/app3

app1 is a Sintra app, app2 is Padrino and app3 is Rails.

I would like to run these apps under different ports (assuming server IP is 50.60.70.101):

50.60.70.101:4567 -> app1
50.60.70.101:3000 -> app2
50.60.70.101:80   -> app3

What is the correct way to configure Apache’s virtual host file to achieve this?

I have 3 files in /etc/apache2/sites-available/ with this type of configuration (with changed IPs):

<VirtualHost *:4567>
    RackEnv         production

    DocumentRoot    /home/web/sites/app1/public
    <Directory      /home/web/sites/app1/public>
        Order   allow,deny
        Allow   from all
        Options -MultiViews
        #AllowOverride All
    </Directory>
</VirtualHost>

But I cannot access app1 at 50.60.70.101:4567 (app3 does work on port 80, though).

You’ll need to explicitly tell Apache to listen on those ports with the Listen directive; have a look at Binding to Addresses and Ports.

Tagged : / / / /

Code Bug Fix: On third page not getting next page token google place api?

Original Source Link

On third page not getting next page token google place api?

I am using Google place text search API in my Ruby on rails application, everything is working fine but after third page I am not getting any next page token so for every text search I am getting only 60 result. Is I am missing something please suggest any help would be appreciable. This happen for every text.

  • My request for first page :-

    https://maps.googleapis.com/maps/api/place/textsearch/json?key=#{my_key}&query=#{my_query}
    
  • My request for other page with token:-

    https://maps.googleapis.com/maps/api/place/textsearch/json?key=#{my_key}&pagetoken=#{next_page_token}
    

And usually I am searching on google it show 100’s of result for same place text. How can I get result more than 60.

This is intended behavior for Google’s Places API, as you can only get up to 60 places, split across 3 pages (3 queries). This is why there is no next_page_token on the third page.

By default, each Nearby Search or Text Search returns up to 20
establishment results per query; however, each search can return as
many as 60 results, split across three pages. If your search will
return more than 20, then the search response will include an
additional value — next_page_token.

Reference here. Hope this helps!

Tagged : / / /

Code Bug Fix: How to fix minimum date in date_select field in rails?

Original Source Link

I’ve this app on rails, where one of the form has a date_select field for a model and I’m trying to set a minimum date of today in that date_select field such that a user won’t be able to select a date before today.

I’m able to fix start_year of the date_select field using this but unable to fix start month and start day for the field because there’s not any start_month and start_day attributes available.
Also what if I want to freeze some dates like user cannot select sundays then what to do?

Here’s my form field looks like-

<%= form.label :Date %>
<%= form.date_select( :daterequired, start_year: Date.current.year,
                                          order: [:day, :month, :year],
                                          :class=>'form-control mb-1', id: :order_daterequired)%>

One more question-

If I’ve this form under the path appviewsorder_form.html.erb
and there are many other views in my app for example- appviewsservicesindex.html.erb, appviewspageshome.html.erb all of these have many html.erb files. So my question is exactly where should I put a Javascript code if i’m using Javascript in any of these files under different views? Should I create different JS files for each html.erb file or just put all JS code in application.js file?

I know I’m asking for a lot but I’m learning this new framework and facing difficulties, Can anyone please help?

For the first question, there is this another question, I think is the same answer for yours, min value in select.

For second question, you should use the app/assets/javascripts folder, you should follow the namespace, for example:

  • controllers/admin/users_controller.rb
  • assests/javascripts/admin/users.js
Tagged : / / / /

Code Bug Fix: Rails 5.2 server hangs when not precompiling assets

Original Source Link

We have an issue since we upgraded our project’s dependency from rails 4.2 to rails 5.2

We use both Sprockets assets and Webpacker. When booting the server for the first time, and loading the first page (any page), it hangs right before serving the content of the page.

It usually hangs on a line like this, with no other output:

I, [2020-05-15T10:28:20.828146 #66077]  INFO -- : [fd7f1413-7d72-402f-92f9-95688e7fa50e]   Rendered partials/_front_page_featured_items.html.haml (172.4ms)

The ruby process seems idle, not using the CPU.

I realized that by running rails assets:precompile before running the server, then it doesn’t hang anymore, even if I delete the precompiled assets in the public/assets and public/packs directory.

I can reproduce it by:

  • Deleting contents of tmp/cache

We can reproduce this on at least 3 development machines and also on CI server.

In the rails 4.2 branch, we don’t have this issue, and we have the same version of Webpacker (4.2.2).

The main difference between the rails 4.2 branch and 5.2 in terms of assets is the upgrade from sprockets 3.7 to 4.0, alongside all the other dependency changes.

I am stuck debugging this and would appreciate some help in how I can further debug this issue, getting more output to the log, etc.

UPDATE: I disabled webpacker in the gemfile and it still freezes

UPDATE #2: Found a related issue on Sprockets: https://github.com/rails/sprockets/issues/640 . I believe it is the same issue as I have.

The issue seems to get fixed after adding:

if Rails.env.development? || Rails.env.test?
  Sprockets.export_concurrent = false
end

to application.rb

According to https://github.com/rails/sprockets/issues/640, there is a bug in Sprockets where a deadlock can happen, and this is a workaround fix.

Tagged : / / /

Server Bug Fix: Passenger could not spawn process for application. Rails, ubuntu, passenger and apache

Original Source Link

My application is crashing again and again. I am using the hosting services of digital ocean the status of the server are also displayed in the image
(It start working when I restart the server but that is not the solution. After sometime it again crashes.)
Apache log.error shows:

[ 2016-07-05 16:40:39.2615 1768/7ff87c09b700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application /home/abc/kbs: An er$
  Error ID: b1aaad3d
  Error details saved to: /tmp/passenger-error-ygdDZS.html
  Message from application: An error occurred while starting the web application. It exited before signalling successful startup back to Phusion$
<h2>Raw process output:</h2>
(empty)

App 21534 stdout:   ^[[1m^[[35mCategoryProduct Load (23.0ms)^[[0m  SELECT "category_products".* FROM "category_products" WHERE "category_product$
App 21534 stdout:   ^[[1m^[[36m (0.5ms)^[[0m  ^[[1mSELECT "category_products"."name" FROM "category_products" WHERE "category_products"."product$
terminate called after throwing an instance of 'Passenger::SystemException'
App 21534 stdout:   ^[[1m^[[35mCACHE (0.3ms)^[[0m  SELECT  "countries".* FROM "countries" WHERE "countries"."id" = $1  ORDER BY name LIMIT 1  [[$
  what():  Cannot fork a new process: Cannot allocate memory (errno=12)
ERROR: cannot fork a process for executing 'tee'
[ pid=1768, timestamp=1467751239 ] Process aborted! signo=SIGABRT(6), reason=SI_TKILL, signal sent by PID 1768 with UID 0, si_addr=0x6e8, random$
[ pid=1768 ] Could not create crash log file, so dumping to stderr only.
[ pid=1768 ] Could fork a child process for dumping diagnostics: fork() failed with errno=12

Content of the file /tmp/passenger-error-ygdDZS.html are below.

An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger. Please read this article for more information about this problem.
Raw process output:

(empty)
Error ID
b1aaad3d
Application root
/home/abc_user/app_name
Environment (value of RAILS_ENV, RACK_ENV, WSGI_ENV, NODE_ENV and PASSENGER_APP_ENV)
production
Ruby interpreter command
/usr/bin/passenger_free_ruby
User and groups
uid=1000(abc_user) gid=1000(abc_user) groups=1000(abc_user),27(sudo)
Environment variables
APACHE_PID_FILE=/var/run/apache2/apache2.pid
SHELL=/bin/bash
APACHE_RUN_USER=www-data
PASSENGER_DEBUG_DIR=/tmp/passenger.spawn-debug.XXXXijaXyT
USER=abc_user
PASSENGER_USE_FEEDBACK_FD=true
APACHE_LOG_DIR=/var/log/apache2
PATH=/home/abc_user/.rbenv/plugins/ruby-build/bin:/home/abc_user/.rbenv/shims:/home/abc_user/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/home/abc_user/app_name
APACHE_RUN_GROUP=www-data
LANG=C
NODE_PATH=/usr/share/passenger/node
RBENV_SHELL=bash
SHLVL=0
HOME=/home/abc_user
LOGNAME=abc_user
SERVER_SOFTWARE=Apache/2.4.7 (Ubuntu) Phusion_Passenger/5.0.26
APACHE_LOCK_DIR=/var/lock/apache2
APACHE_RUN_DIR=/var/run/apache2
IN_PASSENGER=1
PYTHONUNBUFFERED=1
RAILS_ENV=production
RACK_ENV=production
WSGI_ENV=production
NODE_ENV=production
PASSENGER_APP_ENV=production
SCRIPT_URL=/products/spray-paints-hand-tools
SCRIPT_URI=https://www.domain.com/products/name_of_brand
HTTPS=on
SSL_TLS_SNI=www.domain.com
Ulimits
Unknown
System metrics
------------- General -------------
Kernel version    : 3.13.0-79-generic
Uptime            : 8h 41m 28s
Load averages     : 4.03%, 2.24%, 0.96%
Fork rate         : unknown

------------- CPU -------------
Number of CPUs    :    2
Average CPU usage : 100%  -- 100% user,   0% nice,   0% system,   0% idle
  CPU 1           : 100%  -- 100% user,   0% nice,   0% system,   0% idle
  CPU 2           : 100%  -- 100% user,   0% nice,   0% system,   0% idle
I/O pressure      :   0%
  CPU 1           :   0%
  CPU 2           :   0%
Interference from other VMs:   0%
  CPU 1                    :   0%
  CPU 2                    :   0%

------------- Memory -------------
RAM total         :   2001 MB
RAM used          :   1879 MB (94%)
RAM free          :    122 MB
Swap total        :      0 MB
Swap used         :      0 MB (-nan%)
Swap free         :      0 MB
Swap in           : unknown
Swap out          : unknown

Some information about my server is

Server version: Apache/2.4.7 (Ubuntu)

Server built: Jan 14 2016 17:45:23

Phusion Passenger 5.0.26

Memory(Ram) 2GB
Disc Space 40Gb

Please post the following from your httpd.conf or other configuration file for the given apache server:::

StartServers          ?
MinSpareServers       ?
MaxSpareServers      ?

Could be you are starting way more spare servers than the server can handle for your load of simple web application. Passenger runs inside apache and forks from it.

Tagged : / / /

Code Bug Fix: devise_token_auth forget password API shows Use POST /sign_in to sign in. GET is not supported error

Original Source Link

Following this solution https://stackoverflow.com/a/47761138/7818637 I am designing forgot password flow APIs on rails where I am using devise_token_auth gem for authentication.

1. A POST call to send a Password Reset Email

URL: http://localhost:3000/client/auth/password

form-data: {email: '[email protected]', redirect_url: 'http://localhost:3000/client/auth/sign_in'}

post call to send a password reset email

2. A GET call to verify the password reset token (clicked in email)

I am receiving the the following URL on my console containing redirect_url and reset_password_token:

http://localhost:3000/client/auth/password/edit?config=default&redirect_url=http%3A%2F%2Flocalhost%3A3000%2Fclient%2Fauth%2Fsign_in&reset_password_token=ZBsx64Gk1VBraM3THZTn

When I call on this URL, I am receiving the following error:

Use POST /sign_in to sign in. GET is not supported.

call to verify the password reset token

What I have already tried:

Following the issue here I have found that I am already using include DeviseTokenAuth::Concerns::SetUserByToken in my controller.

Console Logs:

console logs

When the users clicks the url in your email you redirect them to /password/edit path. In this action you verify the user. If everything goes right the user will be redirected in redirect_url which is the sign_in path in your case.

You should change the redirect_url in your email and create an action and a view in which the user will be redirected. In this new view you will have the fields so the user can reset the password. Make sure that the new url will use ‘GET’. On form submission redirect user to sign_in path so he/she can log in with their new password.

Please read https://devise-token-auth.gitbook.io/devise-token-auth/usage/reset_password for more info.

Tagged : / /

Code Bug Fix: Rails: wkhtmltopdf executable in the wkhtmltopdf-binary-edge gem is being loaded

Original Source Link

I am working on a Rails application on Ubuntu 18.04.

I used the wkhtmltopdf-binary-edge, wkhtmltopdf, wkhtmltopdf-binary, wkhtmltopdf-heroku gems to convert HTML to PDF.

I defined it this way in my Gemfile:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.5.0'
gem 'rails', '~> 5.2.1'
gem 'pg'
gem 'puma', '~> 3.11'
gem 'wicked_pdf'

group :development, :test do
  gem 'wkhtmltopdf-binary-edge'
end 

group :production do
  gem 'wkhtmltopdf-heroku'
  gem 'wkhtmltopdf-binary'
end 

Everything was working fine until recently when I started encountering this error whenever I try to run bundle install:

Error: The wkhtmltopdfexecutable in thewkhtmltopdf-binary-edge gem is being loaded, but it’s also present in other gems (wkhtmltopdf-binary). If you meant to run the executable for another gem, make sure you use a project specific binstub (bundle binstub ). If you plan to use multiple conflicting executables, generate binstubs for them and disambiguate their names.

I have tried a couple of solutions, but none seems to work.

Here’s how I solved:

It seemed like gems wkhtmltopdf-binary-edge and wkhtmltopdf-binary have conflicting executables.

I simply had to remove the wkhtmltopdf-binary-edge gem and re-ordered the Gemfile this way:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.5.0'
gem 'rails', '~> 5.2.1'
gem 'pg'
gem 'puma', '~> 3.11'
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'


group :production do
  gem 'wkhtmltopdf-heroku'
end 

That’s all.

I hope this helps

Tagged : / / /

Server Bug Fix: Uninstall Ruby on Rails on CentOS 6

Original Source Link

How can I remove Ruby on Rails and all associated gems?

I tried yum remove ruby but get this response:

yum remove ruby
Loaded plugins: fastestmirror, security
Setting up Remove Process
No Match for argument: ruby
Loading mirror speeds from cached hostfile
 * base: mirror01.th.ifl.net
 * extras: mirror01.th.ifl.net
 * updates: mirror01.th.ifl.net
No Packages marked for removal

If I write $rails -v, $ruby -v or $gem -v I still get their versions returned to me, which indicates that they’re installed.

try the following,

# yum provides ruby

or

# rpm -qa | grep -i ruby

This will display the RPMs that is currently installed that provides the ruby binary.

Once you have the name of the rpm you can then run the follow to remove the RPM from your system

# yum erase <package_name>

It might be possible that

  1. the ruby rpm was installed with a custom named rpm package
  2. that ruby was compiled with gcc on the current host

If so, then you will need to manually remove ruby libs and binaries from your system path.

You can locate binary by

# which ruby 

Then you can proceed to remove it from your path.

Else search with find

# find / -name "*ruby*"

then proceed to remove the directories from you server.

I guess below command would be useful for you to uninstall RVM packages. Please execute one by one.

Commands:

  1. rvm list

    (it will give you what ruby packages are presently installed on your server)

  2. rvm remove ruby_pkg_name

then once successfully executed above commands then check whether ruby uninstalls or not like ruby -v, gem -v, rails -v or which ruby

hope this will helpful for you!

removing ruby from the server i.e CentOs depends upon how you have installed it.
If it was install directly without rvm or rbenv then

yum remove ruby

or

   sudo yum remove ruby 

if it is installed using rvm

rvm remove 1.9.3-p551

or

 rvm remove <ruby-version>

if its is installed using rbenv
like:

rbenv uninstall 2.1.0

or

rbenv uninstall <ruby-version> 

Tagged : / / /

Server Bug Fix: Unable to run sidekiq as service in CentOS 8

Original Source Link

I have following service file.

[Unit]
Description=xxx_sidekiq
After=syslog.target network.target


[Service]
Type=notify
WatchdogSec=10

WorkingDirectory=/home/xxx/project/matchspace/appointment-ms
ExecStart=/home/xxx/.rvm/wrappers/ruby-2.6.4/bundle exec sidekiq -e production
User=developer
Group=developer
UMask=0002

Environment=MALLOC_ARENA_MAX=2

RestartSec=1
Restart=on-failure

StandardOutput=syslog
StandardError=syslog

SyslogIdentifier=xxx_sidekiq

[Install]
WantedBy=multi-user.target

When I start the service as sudo systemctl start xxx_sidekiq.service I get following error

Jun  4 05:55:23 cnctest systemd[23391]: xxx_sidekiq.service: Failed to execute command: Permission denied
Jun  4 05:55:23 cnctest systemd[23391]: xxx_sidekiq.service: Failed at step EXEC spawning /home/xxx/.rvm/wrappers/ruby-2.6.4/bundle: Permission denied

The reason for Permission denied is given as

Jun  4 05:55:23 cnctest platform-python[23362]: SELinux is preventing /usr/lib/systemd/systemd from read access on the lnk_file ruby-2.6.4.#012#012*****  Plugin catchall (100. confidence) suggests   **************************#012#012If you believe that systemd should be allowed read access on the ruby-2.6.4 lnk_file by default.#012Then you should report this as a bug.#012You can generate a local policy module to allow this access.#012Do#012allow this access for now by executing:#012# ausearch -c '(bundle)' --raw | audit2allow -M my-bundle#012# semodule -X 300 -i my-bundle.pp#012

How can I solve this problem.

Tagged : /

Code Bug Fix: How to maintain information in a simple_form_for instance until a correct answer is passed

Original Source Link

I am trying to create a simple rails website that I can use to practice my mental math. The idea is that I create a random question using a randomly selected ruby question_creator function I defined. This function returns two numbers, along with their answer.

If a user types in an answer that is incorrect, I want to display a quick error message and display the same question again. While redisplaying the question I would like to keep track of the number of attempts required to find the correct answer, as well as the total time taken to do so.

Where I am stuck now is that I can not figure out how to maintain the randomly generated question, along with the number of try’s while reloading the simple_form_for after an incorrect input.

In order to do this I have created a model named Questions which holds the number of trys and time taken for each question. Ideally I would like to create an instance of this object whenever a question is answered correctly. The idea of having a single Question instance for every question answered is that I can then later use this to track my progression and improvements.

Right now the Questions Schema looks like this:

 create_table "questions", force: :cascade do |t|
    t.integer "trys"
    t.integer "time"
    t.bigint "user_id"
    t.bigint "question_type_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_questions_on_user_id"
  end

My Questions class method to generate random questions looks like this. I am not sure if this is even the correct place this method, so please feel free to feedback on this as well. My idea is that in the end I have several different questions e.g. add_two_numbers(), multiply_two_numbers(), subtract_three_numbers() etc… from which I can randomly pick one each time.

 def random_two_digit_number()
    return rand(10..99)
  end

  def add_two_numbers()
    num1 = random_two_digit_number()
    num2 = random_two_digit_number()
    answ = num1 + num2
    return num1, num2, answ
  end

In order to pass the users answer, along with the actual answer answ to the create method I have added them as hidden fields in my simple_form_for.My Question/New page looks like this:

<% @question = Question.new() %>

<% num1, num2, answ = @question.add_two_numbers %>
<h3>  <%= num1 %> + <%= num2 %></h3>

<p>Trys: <%= @question.trys %></p>

<%= simple_form_for @question do |f| %>
  <%= f.hidden_field :trys, :value => @question.trys || 1 %>
  <%= f.hidden_field :answ, :value => answ %>
  <%= f.input :user_answ, input_html: {value: ''}  %>
  <%= f.button :submit %>
<% end %>

The create method in the questions controller:

def create
    @question = Question.new(trys: question_params["trys"], time: question_params["time"])
    @question.user_id = current_user.id
    respond_to do |format|
      if @question.save && (question_params["answ"] == question_params["user_answ"])
        format.html { render :new, notice: 'Correct!' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new, notice: 'Thats wrong' }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

Whenever I hit the point where question_params["answ"] == question_params["user_answ"], meaning that the user gave a wrong answer, I would like to increment the trys count by one and redirect him to the same question. As of right now, I can not get this to work however.

I have already build a quick prototype of this in python, if that is of any help: https://codeshare.io/arlrX7

I would be super glad I somebody could point me in the right direction, as I would really love to get this to work 🙂

There are many things wrong with this code, but let’s tackle the ones preventing you from making it work.

  1. In your new.html.erb you have two problematic lines –
<% @question = Question.new() %>
<% num1, num2, answ = @question.add_two_numbers %>

Having logic in your view is a bad idea, and it prevents you from reaching your goal, too. Define them inside new action in your controller.

  1. Next stop – submitting the form. You now assign @question and @num1 and its friends in the new action, and your form still works. But alas, that didn’t fixed the problem yet. What you need now if to have those same variables inside your create action, because when you render :new, notice: 'Thats wrong', it’s being done inside the context of create, with local variables available in that context.

So, add num1 and fiends as hidden fields in to your form, and assign those values inside the create action.

@num1 = question_params[:num1]

This way, when you render :new, you still have those @question and @num1 and whatever else you passed along

  1. Lastly, this line in your controller:
 if @question.save && (question_params["answ"] == question_params["user_answ"])

What it does is saving the question and then checking the answer. Instead, try:

 @question.save if (question_params["answ"] == question_params["user_answ"])

if @question.persisted? # rest of your code

This way you only save the question if the answer is correct, and then check if it was saved to determine what to do next.

Tagged : /