ElasticBeanstalk Ruby PostDeploy Script Mission Impossible - ruby-on-rails

We have recently updated our ruby/elasticbeanstalk platform to AWS Linux 2 / Ruby (Ruby 2.7 running on 64bit Amazon Linux 2/3.2.0)
A part of our Ruby deployment is a delayed_job (daemon gem)
After many attempts to have a bash script from the .platform/hooks/postdeploy/ folder, I have offically declared I am stuck. Here is the error from eb-engine.log:
2020/12/08 04:18:44.162454 [INFO] Running platform hook: .platform/hooks/postdeploy/restart_delayed_job.sh
2020/12/08 04:18:44.191301 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPostDeployHooks]. Stop running the command. Error: Command .platform/hooks/postdeploy/restart_delayed_job.sh failed with error exit status 127
2020/12/08 04:18:44.191327 [INFO] Executing cleanup logic
2020/12/08 04:18:44.191448 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1607401124,"severity":"ERROR"}]}]}```
Here is one of many scripts I have attempted:
#!/bin/bash
#Using similar syntax as the appdeploy pre hooks that is managed by AWS
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>delayed_job_err.out 2>&1
# Loading environment data
# source /etc/profile.d/sh.local #created from other .ebextension file
EB_APP_USER=$(/opt/elasticbeanstalk/bin/get-config platformconfig -k AppUser)
EB_APP_CURRENT_DIR=$(/opt/elasticbeanstalk/bin/get-config platformconfig -k AppDeployDir)
#EB_APP_PIDS_DIR=/home/webapp/pids
/opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export \(.key)=\"\(.value)\""' > /tmp/envvars
source /tmp/envvars
cd /var/app
cd $EB_APP_CURRENT_DIR
su -s /bin/bash -c "bin/delayed_job restart" $EB_APP_USER```
Here is the delayed_job file:
#!/usr/bin/env ruby
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
require 'delayed/command'
Delayed::Command.new(ARGV).daemonize
As you can see I'm doing my best to load up the env variables. The delayed_job seems to run just fine as root from within the EB Linux 2 host with the env vars loaded.
total 12
-rwxrwxr-x 1 webapp webapp 179 Dec 8 04:15 001_load_envs.sh
-rw-r--r-- 1 root root 251 Dec 8 04:46 delayed_job_err.out
-rwxrwxr-x 1 webapp webapp 1144 Dec 8 04:15 restart_delayed_job.sh
[root#ip-172-16-100-178 postdeploy]# cat delayed_job_err.out
/var/app/current/vendor/bundle/ruby/2.7.0/gems/json-1.8.6/lib/json/common.rb:155: warning: Using the last argument as keyword parameters is deprecated
delayed_job: warning: no instances running. Starting...
delayed_job: process with pid 5292 started.
Any help would be appreciated..

I am also using elasticbeanstalk on Amazon Linux 2
I am using resque which needs a restart postdeploy. Following is my postdeploy hook which restarts resque workers
.platform/hooks/postdeploy/0020_restart_resque_workers.sh
#!/usr/bin/env bash
. /opt/elasticbeanstalk/deployment/env
cd /var/app/current/
su -c "RAILS_ENV=production bundle exec rake resque:restart_workers" webapp ||
echo "resque workers restarted."
true
Notice the environment variable setup. It simply executes /opt/elasticbeanstalk/deployment/env which will give you the environment.
Hope you are able to use above script by simply replcaing command to restart delayed job instead of resque workers.

Related

Why does this Rails app fails to deploy to GCLOUD?

While attempting to deploy a non-default service to gcloud application with the command:
$ gcloud app deploy
I get the error (right after all gems finish installing):
...
Step #1: /opt/rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/google-api-client-
0.36.4/lib/google/apis/core/http_command.rb:228:in `check_status': forbidden: The caller does
not have permission (Google::Apis::ClientError)
....
Step #1: from /opt/rbenv/versions/2.4.1/bin/rcloadenv:22:in `<main>'
Step #1: The command '/bin/sh -c gem install rcloadenv && rbenv rehash && rcloadenv flex-env-
config >> .env' returned a non-zero code: 1
Finished Step #1
ERROR
ERROR: build step 1 "gcr.io/cloud-
builders/docker#sha256:853164af9dfd5ea4613401df48ad77b61bcb2c101b4e5de261c8300ecdd6eb47"
failed: exit status 1
Note that I performed this process for another service (default) minutes before this one, which tells me my local configuration is working to some extent.
Could I be missing any extra step specific to a Rails Application ?
app.yaml
entrypoint: bundle exec rackup --port $PORT
env: flex
runtime: ruby
service: api
runtime_config:
dotenv_config: flex-env-config
automatic_scaling:
min_instances: 0
min_idle_instances: 0
env_variables:
SECRET_KEY_BASE: <redacted-key>
beta_settings:
cloud_sql_instances: <redacted-instance-info>
The error got fixed and deployment succeeded when removed this lines from app.yaml:
...
runtime_config:
dotenv_config: flex-env-config
...
Not sure why this lines were important in the first place, investigate further and update with more meaningful explanation.

uwsgi upgrade to python3.7 to fix ImportError: No module named 'encodings'

Honestly, I have no idea what I am doing, so be gentle with me. I am trying to use uwsgi to run my django application on a aws ubuntu instance. I have a virtual environment with python3.7 running, but when I try to run uwsgi. I get this in the logs:
*** Starting uWSGI 2.0.14 (64bit) on [Sun Jan 5 14:51:32 2020] ***
compiled with version: 5.4.0 20160609 on 20 October 2016 05:56:34
os: Linux-4.4.0-109-generic #132-Ubuntu SMP Tue Jan 9 19:52:39 UTC 2018
nodename: ip-172-31-41-139
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
chdir() to /home/ubuntu/web/graff
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3804
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /home/ubuntu/web/graffuwsgi.sock fd 3
Python version: 3.5.2 (default, Oct 8 2019, 13:06:37) [GCC 5.4.0 20160609]
Set PythonHome to /home/ubuntu/.virtualenvs/graff
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Here is my uwsgi.conf
# file: /etc/init/graffuwsgi.conf
description "uWSGI server for graff"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
exec /usr/local/bin/uwsgi --home /home/ubuntu/web/graff/ --socket /home/ubuntu/web/graffuwsgi.sock --chmod-socket=666 --module=graff.wsgi --pythonpath /home/ubuntu/web -H /home/ubuntu/.virtualenvs/graff --logto /home/ubuntu/web/logs/graffuwsgi.log --chdir=/home/ubuntu/web/graff --chmod-socket=666
It seems like python3.5 just doesn't work anymore. I feel like I've had to replace python3.5 with 3.7 in several places lately to fix various bugs, and I have it in my head that if I can get uwsgi to run python3.7 instead of 3.5 then that will solve this error too. Anyway, any help is much appreciated.
Looks like your uwsgi is compiled with different python version, make sure you compile with python 3.5
PYTHON=python3.5 uwsgi --build-plugin "/usr/src/uwsgi/plugins/python python35"
mv python35_plugin.so /usr/lib/uwsgi/plugins/python35_plugin.so
chmod 644 /usr/lib/uwsgi/plugins/python35_plugin.so
you can follow this guide:
https://www.paulox.net/2017/04/04/how-to-use-uwsgi-with-python3-6-in-ubuntu/
The source of error is PythonHome (pyhome, venv, home) setting.
See at the official Python docs on Environment variables
Is your path /home/ubuntu/.virtualenvs/graff suited for Python requirements?
In short:
Use pythonpath (pp) and let the system to find modules.
You can set several repeated options in your uwsgi config to custom modules search, eg:
pythonpath = /opt/web2py/
pythonpath = /opt/anaconda/lib/python3.9/site-packages/
So, I had the same error. And it was fixed by editing uwsgi vassal config.
I thing the core of problem that virtual envs are created with symlinks or have some inner relative paths, so an isolated process inside uwsgi could not find modules.

PhantomJS failed to load URL on Jetty running on Jenkins

I want to use the Siesta testing Framework with PhantomJS on a local server and there is no problem. I worked like in http://www.bryntum.com/forum/viewtopic.php?f=20&t=3068 and on my machine, there were nothing to complain about, so i want to combine it with Jenkins.
But using Jenkins an Error 403 appears.
What I do:
Copy the files of my project in the webapps folder of Jetty (incl.
Framework )
Start the jetty server (so far no problems)
Use the PhantomJs of the framwork on my
localhost:port/project/index.html
And there my Problem starts:
Failed to load URL: localhost:port/project/index.html(Status 403)
I searched for some results but didn't find anything that solves this problem.
Every hint is welcome
Thanks
To see what i've done:
My Jenkins Shell Script
JETTY="jetty-distribution-9.2.0.v20140526"
JETTYWEB="$JETTY/webapps"
DIR="$WORKSPACE/$JETTYWEB/myProject/src/test"
PHANTOM="$DIR/Siesta_Framework/bin"
rm -r "$JETTYWEB/myProject/"
mkdir "$JETTYWEB/myProject/"
cp -pr "src/" "$JETTYWEB/myProject/"
chmod u+x -R $JETTYWEB/
cd $WORKSPACE/$JETTY
# Start des Servers
java -DSTOP.PORT=11183 -jar start.jar -DSTOP.KEY=tadam &
sleep 5
#jenkins "$DIR/browse-autmation.html?phantom=true&enableCodeCoverage=false&hasPreviousReport=false&page=0
cd $PHANTOM
#curl http://localhost:11182/myProject/src/test/browse-automation.html
./phantomjs "http://127.0.0.1:11182/myProject/src/test/browse-automation.html"
#"http://.../ci/job/test-phatomJS/ws/src/test/browse-automation.html?phantom=true&enableCodeCoverage=false&hasPreviousReport=false&page=0"
#curl http://127.0.0.1:11182/myProject/src/test/Siesta_Framework/bin/phantomjs
sleep 15
# Stop des Servers -DSTOP.KEY=tadam
cd $WORKSPACE/$JETTY
java -DSTOP.PORT=11183 -DSTOP.KEY=tadam -jar start.jar --stop
And the Result was:
[EnvInject] - Loading node environment variables.
Building remotely on ja_lin01 in workspace /var/opt/coinop/data/workspace/test-phatomJS
Fetching changes from the remote Git repository
Fetching upstream changes from gitlab#moso-ci-srv.novalocal:b.rohn/myProject.git
Checking out Revision a056b4ac6a7b47a4e77f3f80c5b7cbc51167cefc (origin/master)
[test-phatomJS] $ /bin/bash -xe /tmp/hudson8419984949815797813.sh
+ JETTY=jetty-distribution-9.2.0.v20140526
+ JETTYWEB=jetty-distribution-9.2.0.v20140526/webapps
+ DIR=/var/opt/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/myProject/src/test
+ PHANTOM=/var/opt/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/myProject/src/test/Siesta_Framework/bin
+ rm -r jetty-distribution-9.2.0.v20140526/webapps/myProject/
+ mkdir jetty-distribution-9.2.0.v20140526/webapps/myProject/
+ cp -pr src/ jetty-distribution-9.2.0.v20140526/webapps/myProject/
+ chmod u+x -R jetty-distribution-9.2.0.v20140526/webapps/
+ cd /var/opt/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526
+ sleep 5
+ java -DSTOP.PORT=11183 -jar start.jar -DSTOP.KEY=tadam
WARNING: System properties and/or JVM args set. Consider using --dry-run or --exec
2014-07-01 15:37:10.895:INFO::main: Logging initialized #1014ms
2014-07-01 15:37:12.451:INFO:oejs.Server:main: jetty-9.2.0.v20140526
2014-07-01 15:37:12.480:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/data/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/] at interval 1
2014-07-01 15:37:13.232:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext#57cd102a{/myProject,file:/data/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/myProject/,AVAILABLE}{/myProject}
2014-07-01 15:37:13.255:INFO:oejs.ServerConnector:main: Started ServerConnector#6d622548{HTTP/1.1}{0.0.0.0:11182}
2014-07-01 15:37:13.255:INFO:oejs.Server:main: Started #3388ms
+ cd /var/opt/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/myProject/src/test/Siesta_Framework/bin
+ ./phantomjs http://127.0.0.1:11182/myProject/src/test/browse-automation.html
/var/opt/coinop/data/workspace/test-phatomJS/jetty-distribution-9.2.0.v20140526/webapps/myProject/src/test/Siesta_Framework/bin
Launching PhantomJS 1.6.0 at http://127.0.0.1:11182/myProject/src/test/browse-automation.html
Failed to load URL: http://127.0.0.1:11182/myProject/src/test/browse-automation.html?phantom=true&enableCodeCoverage=false&hasPreviousReport=false&page=0(status: 403)
Process leaked file descriptors. See http://wiki.jenkins-ci.org/display/JENKINS/Spawning+processes+from+build for more information
Build step 'Execute shell' marked build as failure
2014-07-01 15:37:24.931:INFO:oejs.ServerConnector:Thread-0: Stopped ServerConnector#6d622548{HTTP/1.1}{0.0.0.0:11182}
Finished: FAILURE
after long searching i noticed, that the phantomjs call doesn't have all the informations it need. It needs the directory itself. So my resolution was: install phantomjs on the linux server and use this phantomjs, including the directory and the phantom script of the framework: now it works.
my actually call is:
./phantomjs "$DIR/phantomjs-launcher.js" $DIR http://127.0.0.1:11182/myProject/browse-automation.html
Situation: i cd in my phtomjs directory on the linux machine and give it the "DIR" of my framework/bin

Crontab in Amazon Elastic Beanstalk

I am doing a cron tab in AWS - Elastic Beanstalk with Ruby on Rails 3, but I don't know what is wrong.
I have this code in my .ebextensions/default.config
container_commands:
01remove_old_cron_jobs:
command: "crontab -r || exit 0"
02send_test_email:
command: crontab */2 * * * * rake send_email:test
leader_only: true
I receive this error:
Failed on instance with return code: 1 Output: Error occurred during build: Command 02send_test_email failed .
UPDATE 1
I tried next:
crontab.txt
*/2 * * * * rake send_email:test > /dev/null 2>&1
default.config
02_crontab:
command: "cat .ebextensions/crontab.txt | crontab"
leader_only: true
RESULT: No errors, but it does not work.
UPDATE 2
crontab.sh
crontab -l > /tmp/cronjob
#CRONJOB RULES
echo "*/2 * * * * /usr/bin/wget http://localhost/crontabs/send_test_email > /dev/null 2>&1" >> /tmp/cronjob
#echo "*/2 * * * * rake send_email:test > /dev/null 2>&1" >> /tmp/cronjob
crontab /tmp/cronjob
rm /tmp/cronjob
echo 'Script successful executed, crontab updated.'
default.config
02_crontab:
command: "/bin/bash .ebextensions/crontab.sh"
leader_only: true
RESULT: Works with url, but not with rake task.
Updated for 2018
In order to get this to work on the latest version of Elastic Beanstalk, I added the following to my .ebextensions:
.ebextensions/0005_cron.config
files:
"/etc/cron.d/mycron":
mode: "000644"
owner: root
group: root
content: |
56 11 * * * root . /opt/elasticbeanstalk/support/envvars && cd /var/app/current && /opt/rubies/ruby-2.3.4/bin/bundle exec /opt/rubies/ruby-2.3.4/bin/rake send_email:test >> /var/app/current/log/cron.log 2>&1
commands:
remove_old_cron:
command: "rm -f /etc/cron.d/*.bak"
How I got there:
There are four main issues to confront when trying to cron a rake task in AWS EB:
The first hurdle is making sure all of your EB and Rails environment variables are loaded. I beat my head against the wall a while on this one, but then I discovered this AWS forum post (login may be required). Running . /opt/elasticbeanstalk/support/envvars loads all of your environment variables.
Then we need to make sure we cd into the current app directory using cd /var/app/current.
Next we need to know where to find the bundle and rake executables. They are not installed in the normal bin directories, but are located in a directory specific to your ruby version. To find out where your executables are located, ssh into your EB server (eb ssh) and then type the following:
$ cd /var/app/current
$ which bundle
/opt/rubies/ruby-2.3.4/bin/bundle
$ which rake
/opt/rubies/ruby-2.3.4/bin/rake
You could probably guess the directory based on your ruby version, but the above commands will let you know for sure. Based on the above, your can build your rake command as:
/opt/rubies/ruby-2.3.4/bin/bundle exec /opt/rubies/ruby-2.3.4/bin/rake send_email:test
NOTE: If you update your ruby version, you will likely need to update your cron config as well. This is a little brittle. I'd recommend making a note in your README on this. Trust me, six months from now, you will forget.
The fourth thing to consider is logging. I'd recommend logging to the same location as your other rails logs. We do this by tacking on >> /var/app/current/log/cron.log 2>&1 to the end of our command string.
Putting all of this together leads to a cron command string of:
. /opt/elasticbeanstalk/support/envvars && cd /var/app/current && /opt/rubies/ruby-2.3.4/bin/bundle exec /opt/rubies/ruby-2.3.4/bin/rake send_email:test >> /var/app/current/log/cron.log 2>&1
Finally, I referenced the latest AWS documentation to build an .ebextensions config file for my cron command. The result was the .ebextensions/0005_cron.config file displayed at the top of this answer.
I am having the same issue. Though I figured out that the reason that rake task doesn't run correctly on eb is because of RACK_ENV, RAILS_ENV and BUNDLE_WITHOUT
Defaults of eb:
RACK_ENV: production
RAILS_ENV: production
BUNDLE_WITHOUT: test:development
When the cron runs rake task, it runs in development mode, and gives gem not found error, as gems grouped in development are not installed.
you can see this by changing your cron a bitfrom:
*/2 * * * * rake send_email:test > /dev/null 2>&1
to:
*/2 * * * * cd /var/app/current/ && /usr/bin/bundle exec /usr/bin/rake send_email:test > /tmp/cron_log 2>&1
and then checking the /tmp/cron_log file
To know the location of bundle and rake, run
which bundle
which rake
I tried setting RAILS_ENV in command in cron, but that didn't work aswell
One quick fix is to set
BUNDLE_WITHOUT to null
EDIT:
Finally I got it to work,
.ebextensions/.config
files:
"/tmp/cron_jobs" :
mode: "000777"
content: |
1 10 * * * cd /var/app/current/ && RACK_ENV=production rake some:task >> /var/app/current/log/cron_log 2>&1
encoding: plain
container_commands:
01_delete_cron_jobs:
command: "crontab -r -u webapp || exit 0"
02_add_cron_jobs:
command: "crontab /tmp/cron_jobs -u webapp"
leader_only: true
option_settings:
- option_name: RAILS_ENV
value: production
- option_name: RACK_ENV
value: production
Notice the '-u webapp' when removing and adding cron, this will run this cron under user webapp. The above will also run in production mode. And the output will be dumped in log/cron_log file.
If the above wont work then adding 'Bundle exec' before 'rake some:task' might work.
I've seen these used with separate files in .ebextensions, such as:
02send_test_email:
command: "cat .ebextensions/crontab | crontab"
leader_only: true
I haven't gotten around to it yet, but I took note of this along the way. Let us know if this works.
This stackoverflow post has much more information
After Update 1/2:
Cron doesn't know where rake is. Your application runs from /var/app/current, and you need to be running bundle exec rake from that directory.
Elastic beanstalk is horrible with logging errors, to get this right, ssh to the machine and experiment until you have the commands right, then put this back into your cron script. You can even try and re-run some of the eb scripts as found in the logs, then reverse that into your ebextensions files.

whenever gem: I set :output but the logfile doesn't show up where I'd expect it to

In my schedule.rb file I have the following lines:
set :output, '/log/cron_log.log'
every 5.minutes do
command 'echo "hello"'
end
I ran whenever -w as suggested in this question Rails, using whenever gem in development, and I assume the cronfile is written and running. (I tried restarting the Rails server as well.)
And when I run $ crontab -l I see the following:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash
-l -c 'echo "hello" >> /log/cron_log.log 2>&1'
But I can't find the log file. I checked in rails_project/log, ~/log and /log to no avail. On OSX btw.
How can I get the log file to be written to the rails project log folder?
Where is your log?
You're putting the output file at the highest directory level:
$ cd /log
To see if the file exists and if it has data in it:
$ ls -la cron_log.log
To create the log file if needed:
$ touch cron_log.log
To open up permissions for your own local debugging (do NOT do this in production!)
$ chmod +rw cron_log.log
Is your command running?
To run the command manually to find out if it works as you expect:
$ /bin/bash -l -c 'echo "hello" >> /log/cron_log.log 2>&1'
To improve your security and protect your path, use full paths:
wrong: command 'echo "hello"'
right: command '/bin/echo "hello"'
To find the command full path:
$ which echo
To verify the cron is running as you expect:
$ sudo grep CRON /var/log/syslog
The grep result should have lines that something like this:
Jan 1 12:00:00 example.com CRON[123]: (root) CMD (... your command here ...)
Are you on a Mac?
If you're not seeing output in the syslog, and you're on a Mac, you may want to read about the Mac OSX switching from cron to launchd.
See the cron plist (/System/Library/LaunchDaemons/com.vix.cron.plist) and use a stdout/stderr path to debug cron itself. I don't recall if launchctl unloading and launchctl loading the plist is sufficient, or since it's a system daemon if you'd have to restart entirely. (see where is the cron log file in lion)
How to log relative to Rails?
To put the log relative to a Rails app, omit the leading slash (and typically call it cron.log)
set :output, "log/cron.log"
To put the log in a specific fully-qualified directory:
set :output, '/abc/def/ghi/log/cron.log'
The Whenever wiki has some good examples about redirecting output:
https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs
Examples:
every 3.hours do
runner "MyModel.some_process", :output => 'cron.log'
rake "my:rake:task", :output => {:error => 'error.log', :standard => 'cron.log'}
command "/usr/bin/cmd"
end

Resources