Showing posts with label heroku. Show all posts
Showing posts with label heroku. Show all posts

Monday, September 17, 2018

Launch concurrent one-off Heroku dynos from PHP

Leave a Comment

I am running a (detached) PHP script from the command line, which itself uses shell_exec() to launch other PHP scripts. I had expected that each of these scripts would be launched almost immediately, but instead it appears to be waiting for one to complete before the code continues to the next one.

This is essentially what I'm running. How can I allow my script to continue through the foreach loop without waiting for each shell_exec() to terminate?

foreach ($rows as $row) {     $output = shell_exec("php path/to/file.php $estab_code") ; } 

Really, my expected outcome here is that each shell_exec() should trigger a new one-off Heroku dyno to be launched, with all of them running concurrently. However, that doesn't appear to be happening: the executed script seems to be running from the original dyno.

Any ideas?

1 Answers

Answers 1

shell_exec waits for the command to return something. In order to make that something happen immediately and be empty, you could tack the following onto each command:

> /dev/null 2>/dev/null & 

Something like this:

foreach ($rows as $row) {     $output = shell_exec("php path/to/file.php $estab_code > /dev/null 2>/dev/null &"); } 
Read More

Wednesday, August 1, 2018

Deploying django app to heroku - can't find file

Leave a Comment

I have a problem running my django app on heroku. It has been deployed successfully but it has some problems finding various files.

in news.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) url_path = BASE_DIR + '/marketdata/news/' 

which works locally but when I deploy it on heroku it says it can't find the file

Exception Value: [Errno 2] No such file or directory: '/app/artemis/static/marketdata/news/bloomberg_news.csv' Exception Location: /app/artemis/static/marketdata/news.py in save_to_csv, line 16

and this is my project structure

enter image description here

Any idea how this would be solved? Any tip would be greatly appreciated!

EDIT: if i check my project structure on heroku the news folder is not there at all. Does this have to do with the fact that it only has .csv files in it?

2 Answers

Answers 1

I found the solution to the issue I was having:

  • I didn't run python manage.py collectstatic before committing to heroku
  • The other problem was with my procfile. Changing it to: web: gunicorn myproject.wsgi solved my issue

Answers 2

If you haven't already done this, give this a read and follow the steps https://devcenter.heroku.com/articles/deploying-python

You probably have, but posting for reference just in case. So, those files are located within your static area. Heroku is a little interesting when it comes to static files. Another question I answered is most likely related to your issue https://stackoverflow.com/a/51373830/4954874.

The problem you are having is it can't find the file, because it is located in your static directory which in turn is found by using /static/ which allows heroku to find it. I believe if you do something like this /static/marketdata/news/ it should work.

Read More

Friday, July 20, 2018

Rails NoMethodError for Blog#create on Heroku, but not Localhost

Leave a Comment

I have an app with a basic blog structure. Creating new blogs works perfectly on localhost, but when I try to create a new blog on Heroku I get the following error in my logs:

2018-07-11T21:20:01.863867+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] Command :: file -b --mime '/tmp/819c55b783715f61a2656207b4852b5c20180711-4-140ohfr.jpg' 2018-07-11T21:20:01.872443+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] Completed 500 Internal Server Error in 38ms (ActiveRecord: 0.0ms) 2018-07-11T21:20:01.873180+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] 2018-07-11T21:20:01.873253+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] NoMethodError (undefined method `[]=' for nil:NilClass): 2018-07-11T21:20:01.873285+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] 2018-07-11T21:20:01.873329+00:00 app[web.1]: [2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0] app/controllers/blogs_controller.rb:48:in `create' 2018-07-11T21:20:01.874027+00:00 app[web.1]: 10.101.219.132 - - [11/Jul/2018:21:19:56 UTC] "POST /blogs HTTP/1.1" 500 1958 2018-07-11T21:20:01.874063+00:00 app[web.1]: http://www.linchpinrealty.com/blogs/new -> /blogs 2018-07-11T21:20:01.874816+00:00 heroku[router]: at=info method=POST path="/blogs" host=www.linchpinrealty.com request_id=2f20a9d7-e0f6-4ab9-b2ac-d6b3a08e8ed0 fwd="68.225.227.137" dyno=web.1 connect=0ms service=5463ms status=500 bytes=2235 protocol=http 

My blogs#create method is decently simple:

 def create     @pillars = Pillar.all     @blog = Blog.new(blog_params)     if current_user.id = 1       @blog.user_id = 2     else       @blog.user = current_user     end      if @blog.save       redirect_to @blog, notice: 'Blog was successfully created.'     else       render :new     end   end 

And I have the following permissions:

 private     # Use callbacks to share common setup or constraints between actions.     def set_blog       @blog = Blog.friendly.find(params[:id])     end      # Only allow a trusted parameter "white list" through.     def blog_params       params.require(:blog).permit(:title, :teaser, :body, :user_id, :image, :tag_list, :link_text, :link_filename, :pillars_id)     end 

I'm not sure where things are going off the rails (no pun intended). I did see this question where the issue was a database issue. In which case, the only recent change I've made would be in my blogs#show method...even though I have no idea how that would prevent a blog from even saving in the database (which it doesn't):

  def show     @pillars = Pillar.all     @pillar = Pillar.find_by(id: @blog.pillars_id)     @related = Blog.where(pillars_id: @blog.pillars_id).where.not(id: @blog.id).limit(4)     @comment = @blog.comments.build     @comments = Comment.where(blog_id: @blog.id, approved: true)     if current_user       @user = current_user     end   end 

Can anyone see where I'm going wrong?

2 Answers

Answers 1

From the logs and the fact it's working fine on your localhost, it's probably an error to host your tmp image file.

You should take a look at these articles:

Edit:

I just saw you get the same error without an image, but don't you set any default image ?

-> Could you post error logs without uploaded image ?

Edit2:

I went on your website, I updated an image on an existing blog post and it works so it's probably not linked to the image system.

Edit3:

After some tests on your websites, it's the tag_list field which is wrong: you can create some new blog post without tags but as soon as you insert some tags an error is raised.

Ps: Sorry I did not managed to get my tests deleted without routes

Answers 2

Have you checked your migrations on Heroku?

Read More

Monday, June 18, 2018

Heroku hangs during migrate with strange pg_advisory_unlock

Leave a Comment

I'm using Rails 5.1 hosted on Heroku, and I use the following command to migrate my database:

heroku run rake db:migrate -a [my app name]

All the migrations themselves complete correctly:

SQL (1.6ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180504164326"]]    (2.1ms)  COMMIT Migrating to AddPinToStaff (20180519024721)    (1.5ms)  BEGIN == 20180519024721 AddPinToStaff: migrating ==================================== -- add_column(:staff, :pin_number, :string)    (4.2ms)  ALTER TABLE "staff" ADD "pin_number" character varying    -> 0.0045s == 20180519024721 AddPinToStaff: migrated (0.0046s) =========================== 

That's the last migration file I created, so it all seems to work. Then, this runs:

SQL (1.6ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180519024721"]] (2.4ms)  COMMIT ActiveRecord::InternalMetadata Load (1.7ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]] (1.3ms)  BEGIN SQL (1.6ms)  INSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "key"  [["key", "environment"], ["value", "beta"], ["created_at", "2018-06-04 18:54:24.766405"], ["updated_at", "2018-06-04 18:54:24.766405"]] (2.1ms)  COMMIT (1.4ms)  SELECT pg_advisory_unlock(5988010931190918735) 

And it hangs there at that last SELECT statement. What is pg_advisory_unlock and why is it running? Reading this blog post it seems like those should be called from my application somewhere, but I can't find any similar text in my application anywhere. Please help!

1 Answers

Answers 1

pg_advisory_unlock is nothing but a postgresql lock that Heroku is using to obtain a transaction level lock on your database. It is not necessary that if Heroku is unable to obtain the lock the migration itself was unsuccessful. Please check if your schema contains the migrated tables, if yes, you don't need to do anything more. Edit: Your logs say the migrations were commited, which is a strong indication that the migration was indeed successful.

Otherwise, you can try dropping your database and re-creating it, then running the migrations again. If it contains important data already, use heroku pg:backups:capture --app <name-of-app> to backup your database, then run rails db:drop, rails db:create, and finally, rails db:migrate in order to run the migration again. You can restore the database using heroku pg:backups:restore <name-of-backup> --app <name-of-app>

Read More

Thursday, May 3, 2018

rails_admin keep giving me undefined local variable or method `rails_admin' when access dashboard

Leave a Comment

I've followed this:

https://github.com/sferik/rails_admin

And I think I've done everything needed, bundle install, rake db:migrate etc but I can't get rid of:

undefined local variable or method "rails_admin" for #<#<Class:0x0055e4c3e49c30>:0x0055e4c2e61db8>

enter image description here ` Any ideas?

3 Answers

Answers 1

Make sure you follow the setup instructions

rails g rails_admin:install 

Also can you post the helper method code which is raising the error?

Try changing this in your haml file

#change rails_admin.url  #to  rails_admin_url 

Answers 2

try using href as below. I think it should work if other things are proper.

href="#{main_app.url_for(action: action.action_name, controller: 'rails_admin/main',  model_name: abstract_model.try(:to_param). id: (object.try(:persisted?) && object.try(:id) || nil))}" 

Answers 3

You need to add the dashboard to the list of actions on your initializers/rails_admin.rb like this

RailsAdmin.config do |config|   config.actions do     dashboard   end end 
Read More

Tuesday, March 27, 2018

How to Configure Heroku to host files using gzip compression

Leave a Comment

I am trying to deploy a node.js app on heroku , which is serving unity webGL exported game to clients. After Unity3d 5+ release , WebGL exports by Unity uses gzip compression by default .

Well ,

heroku server [Node.js] dont serves gzip compressed files , which is causing my Game to throw error in console on load , main unity loading window wont update (just blank) till files dont get completely download & a slight delay while browser manually decompresses it.

enter image description hereThese are the file types Unity WebGL Export provides = || . datagz || . jsgz || . memgz ||

So what i need is , a way to configure heroku node.js server for serving the gzip compression .

1 Answers

Answers 1

It doesn't look like you are having issues serving gzipped files. The messages in the console could be a separate issue altogether.

What is more likely is that your node app is not serving the right folder or files. If you can provide a list of files that is in your build folder (I assume that this is where Unity places its files), I can take a look.

Also, do review your Heroku configuration, namely the command used by the web process. If it is npm start or something, then look at the script it points to (see in your package.json file), and see if it is serving files out of the build folder.

Read More

Monday, February 19, 2018

React Flask Heroku App is not displaying frontend

Leave a Comment

Summary of the issue

I've recently tried to deploy my local application to Heroku. It's built with a Flask backend and a React/Redux frontend. After working through the intricacies of Heroku (procfiles, where it reads package.json, etc.) I'm able to get the backend to show (example: the flask-admin section is working as well as my database), but I'm still unable to reach the frontend (react) portion of my site. There are no errors that I can spot in the Heroku logs and on local version my application works perfectly fine when I start up my python server and do NPM start in the static directory.

Any idea why the front end wouldn't be showing or how to access it?


Logs:

I've removed some sensitive information from the details, but here's what heroku logs --tail gives me when I try to refresh the app.

2018-02-11T01:18:01.000000+00:00 app[api]: Build succeeded 2018-02-11T01:21:12.305017+00:00 heroku[web.1]: Starting process with command `gunicorn main:app` 2018-02-11T01:21:16.374150+00:00 heroku[web.1]: State changed from starting to up 2018-02-11T01:21:15.948707+00:00 app[web.1]: [2018-02-11 01:21:15 +0000] [4] [INFO] Starting gunicorn 19.6.0 2018-02-11T01:21:15.949430+00:00 app[web.1]: [2018-02-11 01:21:15 +0000] [4] [INFO] Listening at: http://0.0.0.0:29162    2018-02-11T01:21:19.278810+00:00 heroku[router]: at=info method=GET path="/" host=removed.herokuapp.com request_id=bd74ea4c-3e3a-403b-8850-198b7dec20e2 fwd="104.152.1.62" dyno=web.1 connect=1ms service=2146ms status=200 bytes=2895 protocol=https 2018-02-11T01:21:19.650759+00:00 heroku[router]: at=info method=GET path="/dist/bundle.css" host=removed.herokuapp.com request_id=48183249-fb12-4c7a-9a53-2a57ab58d89b fwd="104.152.1.62" dyno=web.1 connect=0ms service=3ms status=200 bytes=2895 protocol=https 2018-02-11T01:21:19.816113+00:00 heroku[router]: at=info method=GET path="/dist/bundle.js" host=removed.herokuapp.com request_id=1c8b258b-4187-4df6-af35-784e62fb97e5 fwd="104.152.1.62" dyno=web.1 connect=1ms service=3ms status=200 bytes=2895 protocol=https 

When I view source I see the code from my index.html file (in the static folder, which is correct) and this particular line is highlighted red which makes me think it's missing bundle.js? <script src="/dist/bundle.js"></script>

When I try to visit the front end, none of it is showing. I'm really unsure where to look next.

Initial ideas:

  1. Is my server.js file actually starting on Heroku? I have a "start" script in my package.json, but if procfile is executing Python...does it actually start? How do I make it start without putting it into a postinstall or post-build step?

  2. Is webpack messing something up. My production webpack is slightly different from my development so maybe during build:production it's getting messed up? However, that doesn't explain why build is always succeeding.

  3. Is my server.js or webpack forcing formatting on the index.html file and so it can't parse properly? Perhaps this is why I'm seeing SyntaxError: expected expression, got '< bundle.js:1 in the console?

Update: I received a note from the Heroku support team letting me know that Heroku dynos are not built to support multi processes applications like mine. As a result, they feel like I'd need to make some signficant changes to have all the HTTP requests forwarding through one dyno. Perhaps this is my issue?


Here are files that may help debug:

Server.js

const http = require('http'); const express = require('express'); const httpProxy = require('http-proxy'); const path = require('path'); const apiPort = process.env.PORT || 8081;  const proxy = httpProxy.createProxyServer({});  const app = express();  app.use(require('morgan')('short'));  (function initWebpack() {     const webpack = require('webpack');     const webpackConfig = require('./webpack/common.config');      const compiler = webpack(webpackConfig);      app.use(require('webpack-dev-middleware')(compiler, {         noInfo: true, publicPath: webpackConfig.output.publicPath,     }));      app.use(require('webpack-hot-middleware')(compiler, {         log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000,     }));      app.use(express.static(path.join(__dirname, '/'))); }());    app.all(/^\/api\/(.*)/, (req, res) => {     proxy.web(req, res, { target: `http://0.0.0.0:${apiPort}` }); });  app.get(/.*/, (req, res) => {     res.sendFile(path.join(__dirname, '/index.html')); });   const server = http.createServer(app); server.listen(process.env.PORT || 8080, () => {     const address = server.address();     console.log('Listening on: %j', address);     console.log(' -> that probably means: http://0.0.0.0:%d', address.port); }); 

File Structure

ROOT ├──/application │   ├── models.py │   ├── app.py ├──/static │   ├──/bin │   ├──/dist │   │   ├──bundle.js │   ├──/node_modules │   ├──/src │   │   ├──/actions │   │   ├──/components │   │   │   ├──/examplecomponenthere │   │   │   │   ├──index.js (for example component) │   │   ├──/constants │   │   ├──/containers │   │   ├──/reducers │   │   ├──/store │   │   ├──/webpack │   ├──index.html │   ├──package.json (the true one) │   ├──server.js ├──/tests ├──config.py ├──index.py ├──main.py ├──package.json (one to help heroku start) ├──procfile ├──requirements.txt. ├──setup.py ├──tests.py 

Package.json in root This file exists because I'm running a multi build. Heroku doesn't seem to recognize the package.json in static until I use this one to push it over there.

    {  "name": "rmmd",  "version": "0.0.1",  "engines": {  "node": "6.11.1",  "npm": "3.10.10"  },  "scripts": {  "start": "node static/bin/server.js",  "heroku-postbuild": "cd static && npm install && npm run build:production"  }  } 

Package.json in static

{   "name": "redux-easy-boilerplate",   "version": "1.3.3",   "description": "",   "scripts": {     "clean": "rimraf dist",     "build": "webpack --progress --verbose --colors --display-error-details --config webpack/common.config.js",     "build:production": "npm run clean && npm run build",     "lint": "eslint src",     "start": "node bin/server.js",     "test": "karma start"   },   "repository": {     "type": "git",     "url": ""   },   "keywords": [     "react",     "reactjs",     "boilerplate",     "redux",     "hot",     "reload",     "hmr",     "live",     "edit",     "webpack"   ],   "author": "https://github.com/anorudes, https://github.com/keske",   "license": "MIT",   "devDependencies": {     "webpack-dev-middleware": "^1.5.0",     "webpack-dev-server": "^1.14.1",     "webpack-hot-middleware": "^2.6.0",   },   "dependencies": {     "ant-design-pro": "^0.3.1",     "antd": "^3.0.0",     "lodash": "^4.17.4",     "prop-types": "^15.6.0",     "react-bootstrap": "^0.31.0",     "redux-devtools-extension": "^2.13.2", "autoprefixer": "6.5.3",     "axios": "^0.15.3",     "babel-core": "^6.4.5",     "babel-eslint": "^7.1.1",     "babel-loader": "^6.2.1",     "babel-plugin-import": "^1.2.1",     "babel-plugin-react-transform": "^2.0.0",     "babel-plugin-transform-decorators-legacy": "^1.3.4",     "babel-polyfill": "^6.3.14",     "babel-preset-es2015": "^6.3.13",     "babel-preset-react": "^6.3.13",     "babel-preset-react-hmre": "^1.0.1",     "babel-preset-stage-0": "^6.3.13",     "bootstrap": "^3.3.5",     "bootstrap-loader": "^1.2.0-beta.1",     "bootstrap-sass": "^3.3.6",     "bootstrap-webpack": "0.0.5",     "classnames": "^2.2.3",     "css-loader": "^0.26.4",     "csswring": "^5.1.0",     "deep-equal": "^1.0.1",     "eslint": "^3.4.0",     "eslint-config-airbnb": "13.0.0",     "eslint-plugin-import": "^2.2.0",     "eslint-plugin-jsx-a11y": "^3.0.1",     "eslint-plugin-react": "^6.1.2",     "expect": "^1.13.4",     "exports-loader": "^0.6.2",     "expose-loader": "^0.7.1",     "express": "^4.13.4",     "express-open-in-editor": "^1.1.0",     "extract-text-webpack-plugin": "^1.0.1",     "file-loader": "^0.9.0",     "gapi": "0.0.3",     "history": "^4.4.1",     "http-proxy": "^1.12.0",     "imports-loader": "^0.6.5",     "jasmine-core": "^2.4.1",     "jquery": "^3.1.0",     "jwt-decode": "^2.1.0",     "karma": "^1.2.0",     "karma-chrome-launcher": "^2.0.0",     "karma-mocha": "^1.1.1",     "karma-webpack": "^1.7.0",     "less": "^2.7.2",     "less-loader": "^2.2.3",     "lodash": "^4.5.1",     "material-ui": "^0.16.4",     "mocha": "^3.0.2",     "morgan": "^1.6.1",     "node-sass": "^3.4.2",     "postcss-import": "^9.0.0",     "postcss-loader": "^1.1.1",     "q": "^1.4.1",     "qs": "^6.1.0",     "rc-datepicker": "^4.0.1",     "react": "^15.3.1",     "react-addons-css-transition-group": "^15.3.1",     "react-bootstrap": "^0.31.0",     "react-calendar-component": "^1.0.0",     "react-date-picker": "^5.3.28",     "react-datepicker": "^0.37.0",     "react-document-meta": "^2.0.0-rc2",     "react-dom": "^15.1.0",     "react-forms": "^2.0.0-beta33",     "react-hot-loader": "^1.3.0",     "react-loading-order-with-animation": "^1.0.0",     "react-onclickoutside": "^5.3.3",     "react-redux": "^4.3.0",     "react-router": "3.0.0",     "react-router-redux": "^4.0.0",     "react-tap-event-plugin": "^2.0.1",     "react-transform-hmr": "^1.0.1",     "redux": "^3.2.1",     "redux-form": "^6.0.1",     "redux-logger": "2.7.4",     "redux-thunk": "^2.1.0",     "resolve-url-loader": "^1.4.3",     "rimraf": "^2.5.0",     "sass-loader": "^4.0.0",     "style-loader": "^0.13.0",     "url-loader": "^0.5.7",     "webpack": "^1.12.11",     "webpack-merge": "^1.0.2",     "yargs": "^6.5.0"   } } 

Webpack Prod

const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin');  module.exports = {   devtool: 'source-map',    entry: ['bootstrap-loader/extractStyles', './src/index'],   output: {     publicPath: '/dist/',   },    module: {     loaders: [       {         test: /\.scss$/,         loader: 'style!css!postcss-loader!sass',       },     ],   },    plugins: [     new webpack.DefinePlugin({       'process.env': {         NODE_ENV: '"production"',       },       __DEVELOPMENT__: false,     }),     new ExtractTextPlugin('bundle.css'),     new webpack.optimize.DedupePlugin(),     new webpack.optimize.OccurenceOrderPlugin(),     new webpack.optimize.UglifyJsPlugin({       compress: {         warnings: false,       },     }),   ], }; 

Webpack common

const path = require('path'); const autoprefixer = require('autoprefixer'); const postcssImport = require('postcss-import'); const merge = require('webpack-merge');  const development = require('./dev.config'); const production = require('./prod.config');  require('babel-polyfill').default;  const TARGET = process.env.npm_lifecycle_event;  const PATHS = {     app: path.join(__dirname, '../src'),     build: path.join(__dirname, '../dist'), };  process.env.BABEL_ENV = TARGET;  const common = {     entry: [         PATHS.app,     ],      output: {         path: PATHS.build,         filename: 'bundle.js',     },      resolve: {         extensions: ['', '.jsx', '.js', '.json', '.scss'],         modulesDirectories: ['node_modules', PATHS.app],     },      module: {         loaders: [{             test: /bootstrap-sass\/assets\/javascripts\//,             loader: 'imports?jQuery=jquery',         }, {             test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,             loader: 'url?limit=10000&mimetype=application/font-woff',         }, {             test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,             loader: 'url?limit=10000&mimetype=application/font-woff2',         }, {             test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,             loader: 'url?limit=10000&mimetype=application/octet-stream',         }, {             test: /\.otf(\?v=\d+\.\d+\.\d+)?$/,             loader: 'url?limit=10000&mimetype=application/font-otf',         }, {             test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,             loader: 'file',         }, {             test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,             loader: 'url?limit=10000&mimetype=image/svg+xml',         }, {             test: /\.js$/,             loaders: ['babel-loader'],             exclude: /node_modules/,         }, {             test: /\.css$/,             include: /node_modules/,             loaders: ['style-loader', 'css-loader'],         }, {             test: /\.png$/,             loader: 'file?name=[name].[ext]',         }, {             test: /\.jpg$/,             loader: 'file?name=[name].[ext]',         }],     },      postcss: (webpack) => (         [             autoprefixer({                 browsers: ['last 2 versions'],             })         ]     ), };  if (TARGET === 'start' || !TARGET) {     module.exports = merge(development, common); }  if (TARGET === 'build' || !TARGET) {     module.exports = merge(production, common); } 

ProcFile

web: gunicorn main:app

Buildpacks in Heroku

heroku buildpacks:set heroku/python heroku buildpacks:add heroku/nodejs 

2 Answers

Answers 1

Your flask backend doesn't seem to be running on the same port as you forward your traffic too:

Starting gunicorn 19.6.0 Listening at: 0.0.0.0:13521 (4)   app.all(/^\/api\/(.*)/, (req, res) => {     proxy.web(req, res, { target: 'http://0.0.0.0:8081' }); }); 

Flask is listening on port 13521 (chosen randomly) but the /api/ routes are forwarded to port 8081. Instead, you should probably configure gunicorn to use a fixed port: http://docs.gunicorn.org/en/latest/settings.html#bind

Answers 2

So! It turns out Heroku support team was incorrect in their analysis of my application. My application is built in two different ways (one for production as well as for development). Using npm run start [see static/package.json] on local utilizes hot reloading and benefits from faster local changes via server.js. However, in a production environment, you want to use a compressed bundle.js file so my goal was to use npm run build:production [see static/package.json].

The issue I was running into was SyntaxError: expected expression, got '< bundle.js:1 in the console and it seemed to me that bundle.js wasn't loading at all. I listed a series of valid questions above on why I thought that might happen, but they all assumed that the main problem was an inability to run my react application at the same time as my flask application.

I was totally wrong. I didn't need to run server.js at all. The REAL reason that index.html and flask/python wasn't able to find my bundle.js and load the frontend on production was because of a mistake in the config.py file within flask which I never thought to post.

Flask has a very particular configuration that allows static_folder to be defined and template_folder. A while back I had swapped my static_folder for another directory while working on some image upload functionality. The reason I never caught it is because on local I run server.js for hot reloading so I never saw the compressed bundle.js file error out.

After fixing this mistake, I pushed to heroku and amazingly...it worked on the first try!

Here's the correct code that fixed it:

app = Flask(__name__, static_folder="./static/dist", template_folder="./static") 

In closing whilst running a flask/react application on Heroku:

  • Use multi buildpacks (one for node, one for python).
  • Use your procfile to load only the flask side.
  • You need a package.json file in your root directory...even if you have another in your static folder like me.
  • Use webpack to compress your react code and serve it up in a compressed way.
  • Use render_template with flask to render the index.html file that holds you root div for react.
  • make sure all your dependencies for React are listed inside of actual "dependencies" instead of "devdepencies" otherwise Heroku will ignore them.

I really hope this helps someone! I was slamming my head against the wall for 2 weeks and it turned out to be a small obscure problem....isn't it always?

Additional resources: https://codeburst.io/creating-a-full-stack-web-application-with-python-npm-webpack-and-react-8925800503d9 While this is very simplified...it's what lead me to finding my bug so I'll post it here.

Read More

Monday, February 12, 2018

Heroku - web.1: crashed in node.js app

1 comment

So I am trying to deploy my node.js app in heroku for the first time.

After deploying my code and getting to the 6th step in the heroku deployment guide: https://devcenter.heroku.com/articles/getting-started-with-nodejs#scale-the-app

It told me it had deployed fine so I opened up "Application error" - the browser console was 503

Next I added a Procfile to my project, re-deployed and then ran heroku ps top which it returns the following:

=== web (Free): yarn start:production (1) web.1: crashed 2018/01/30 13:17:05 +0000 (~ 5m ago) 

I'm not too sure where to go from here as the heroku guide carries on without explaining what to do if I hit this error.

here are the initial few pages for my node.js app:

package.json

{   "name": "",   "version": "2.5.1",   "description": "",   "main": "index.js",   "engines": {     "node": ">=6.0",     "npm": ">=3.0"   },   "repository": {     "type": "git",     "url": ""   }   "author": "",   "license": "",   "bugs": {     "url": ""   },   "homepage": "",   "scripts": {     "start": "better-npm-run start",     "start:production": "yarn build && yarn start:prod",     "start:prod": "better-npm-run start:prod",     "build": "yarn clean:build && better-npm-run build",     "lint": "yarn lint:js && yarn lint:style",     "lint:js": "better-npm-run lint:js",     "lint:style": "better-npm-run lint:style",     "flow": "better-npm-run flow",     "test": "better-npm-run test",     "test:watch": "yarn test --watch",     "clean:all": "yarn clean:build && yarn clean:test",     "clean:build": "better-npm-run clean:build",     "clean:test": "better-npm-run clean:test",     "coveralls": "better-npm-run coveralls && yarn clean:test"   },   "betterScripts": {     "start": {       "command": "nodemon ./index.js",       "env": {         "NODE_PATH": "./src",         "NODE_ENV": "development",         "PORT": 3000       }     },     "start:prod": {       "command": "node ./index.js",       "env": {         "NODE_PATH": "./src",         "NODE_ENV": "production",         "PORT": 8080       }     },     "build": {       "command": "webpack --progress --hide-modules --config ./tools/webpack/config.babel.js",       "env": {         "NODE_ENV": "production"       }     },     "lint:js": {       "command": "eslint ./src ./tools ./index.js"     },     "lint:style": {       "command": "stylelint \"./src/**/*.scss\" --syntax scss"     },     "flow": {       "command": "flow; test $? -eq 0 -o $? -eq 2"     },     "test": {       "command": "jest --coverage",       "env": {         "NODE_ENV": "test"       }     },     "clean:build": {       "command": "rimraf ./public/assets"     },     "clean:test": {       "command": "rimraf ./coverage"     },     "coveralls": {       "command": "cat ./coverage/lcov.info | coveralls"     }   },   "babel": {     "presets": [       "env",       "react",       "stage-0"     ],     "env": {       "production": {         "plugins": [           "transform-remove-console"         ]       }     }   },   "eslintConfig": {     "parser": "babel-eslint",     "extends": "airbnb",     "plugins": [       "react",       "jsx-a11y",       "import"     ],     "env": {       "browser": true,       "node": true,       "jest": true,       "es6": true     },     "rules": {       "linebreak-style": 0,       "global-require": 0,       "no-underscore-dangle": 0,       "no-console": 0,       "react/jsx-filename-extension": [         1,         {           "extensions": [             ".js",             ".jsx"           ]         }       ],       "import/no-extraneous-dependencies": [         "error",         {           "devDependencies": true         }       ],       "function-paren-newline": 0     },     "globals": {       "__CLIENT__": true,       "__SERVER__": true,       "__DISABLE_SSR__": true,       "__DEV__": true,       "webpackIsomorphicTools": true     }   },   "stylelint": {     "extends": "stylelint-config-standard",     "rules": {       "string-quotes": "single",       "selector-pseudo-class-no-unknown": [         true,         {           "ignorePseudoClasses": [             "global",             "local"           ]         }       ]     }   },   "browserslist": [     "last 2 versions",     "not ie <= 8"   ],   "jest": {     "setupFiles": [       "raf/polyfill",       "<rootDir>/tools/jest/setup.js"     ],     "collectCoverageFrom": [       "src/containers/**/*.js",       "src/components/**/*.js",       "!src/**/__tests__"     ],     "moduleNameMapper": {       ".*\\.(css|scss|sass)$": "<rootDir>/tools/jest/styleMock.js",       ".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/tools/jest/assetMock.js"     }   } } 

index.js

/* @flow */  // Use babel-register to precompile ES6 syntax require('babel-core/register');  const WebpackIsomorphicTools = require('webpack-isomorphic-tools');  // Setup global variables for server global.__CLIENT__ = false; global.__SERVER__ = true; global.__DISABLE_SSR__ = false; // Disable server side render here global.__DEV__ = process.env.NODE_ENV !== 'production';  // This should be the same with webpack context const dirRoot = require('path').join(process.cwd());  // Settings of webpack-isomorphic-tools global.webpackIsomorphicTools =   new WebpackIsomorphicTools(require('./tools/webpack/WIT.config')).server(dirRoot, () => require('./src/server')); 

WIT.config.js

const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');  module.exports = {   // debug: true,   // webpack_assets_file_path: 'webpack-assets.json',   // webpack_stats_file_path: 'webpack-stats.json',   assets: {     images: {       extensions: ['png', 'jpg', 'jpeg', 'gif'],       parser: WebpackIsomorphicToolsPlugin.url_loader_parser,     },     fonts: {       extensions: ['eot', 'ttf', 'woff', 'woff2'],       parser: WebpackIsomorphicToolsPlugin.url_loader_parser,     },     svg: {       extension: 'svg',       parser: WebpackIsomorphicToolsPlugin.url_loader_parser,     },     style_modules: {       extensions: ['css', 'scss'],       filter: (module, regex, options, log) => {         if (options.development) {           return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log);         }          return regex.test(module.name);       },       path: (module, options, log) => {         if (options.development) {           return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log);         }          return module.name;       },       parser: (module, options, log) => {         if (options.development) {           return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log);         }          return module.source;       },     },   }, }; 

server.js

   /* @flow */  import path from 'path'; import morgan from 'morgan'; import express from 'express'; import compression from 'compression'; import helmet from 'helmet'; import hpp from 'hpp'; import favicon from 'serve-favicon'; import React from 'react'; import { renderToString, renderToStaticMarkup } from 'react-dom/server'; import { StaticRouter, matchPath } from 'react-router-dom'; import { Provider } from 'react-redux'; import chalk from 'chalk';  import createHistory from 'history/createMemoryHistory'; import configureStore from './redux/store'; import Html from './utils/Html'; import App from './containers/App'; import routes from './routes'; import { port, host } from './config';  const app = express();  app.set('port', process.env.PORT || 3000);  // Using helmet to secure Express with various HTTP headers app.use(helmet()); // Prevent HTTP parameter pollution. app.use(hpp()); // Compress all requests app.use(compression());  // Use morgan for http request debug (only show error) app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 })); app.use(favicon(path.join(process.cwd(), './public/favicon.ico'))); app.use(express.static(path.join(process.cwd(), './public')));  // Run express as webpack dev server if (__DEV__) {   const webpack = require('webpack');   const webpackConfig = require('../tools/webpack/config.babel');    const compiler = webpack(webpackConfig);    app.use(require('webpack-dev-middleware')(compiler, {     publicPath: webpackConfig.output.publicPath,     hot: true,     noInfo: true,     stats: { colors: true },     serverSideRender: true,   }));    app.use(require('webpack-hot-middleware')(compiler)); }  //GET week app.get('/api/week', (req, res) => {     console.log('week');      var articles = [];      db.collection('articles')         .find()         .limit(2)         .sort("date", -1)         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET articles app.get('/api/articles', (req, res) => {     console.log('articles');      var articles = [];      db.collection('articles')         .find()         .limit(12)         .sort("date", -1)         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET authorArticles app.get('/api/authorArticles', (req, res) => {     console.log('authorArticles');      var articles = [];      var ObjectId = require('mongodb').ObjectID;     var author = {};     var param = req.query.authorQuery;     param = param.replace(/-/g, ' ');      db.collection('articles')         // .find()         .find({"author" : {$regex : ".*" + param + ".*"}})         .limit(12)         .sort("date", -1)         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET extra app.get('/api/extra', (req, res) => {     console.log('extra');      var articles = [];      db.collection('articles')         .aggregate([{ $sample: { size: 4 } }])         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET authors app.get('/api/authors', (req, res) => {     console.log('authors');      var authors = [];      db.collection('authors')         .find()         .limit(24)         .toArray()         .then(result => {             // console.log(result);             authors = authors.concat(result);         }).then(() => {             res.send(authors);         }).catch(e => {             console.error(e);         });  });  //GET search app.get('/api/search', (req, res) => {     console.log('/api/search');      var articles = [];      db.collection('articles')         .find({$or:[                 {title: {$regex : ".*" + req.query.searchQuery + ".*"}},                 {description: {$regex : ".*" + req.query.searchQuery + ".*"}},                 {author: {$regex : ".*" + req.query.searchQuery + ".*"}},                 {keywords: {$regex : ".*" + req.query.searchQuery + ".*"}}               ]})         .limit(24)         .sort("date", -1)         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET category app.get('/api/category', (req, res) => {     console.log('category');      var articles = [];      db.collection('articles')         .find({$or:[                 {category: {$regex : ".*" + req.query.categoryQuery + ".*"}}               ]})         .limit(12)         .sort("date", -1)         .toArray()         .then(result => {             articles = articles.concat(result);         }).then(() => {             // console.log(articles);             res.send(articles);         }).catch(e => {             console.error(e);         });  });  //GET article app.get('/api/article', (req, res) => {     console.log('article');      var ObjectId = require('mongodb').ObjectID;     var article = {};     var param = req.query.title;     param = param.replace(/-/g, ' ');      db.collection('articles')         .findOne({"title": param})         .then(result => {             article = result;         }).then(() => {             res.send(article);         }).catch(e => {             console.error(e);         });  });  //GET author app.get('/api/author', (req, res) => {     console.log('author');      var ObjectId = require('mongodb').ObjectID;     var article = {};     var param = req.query.title;     param = param.replace(/-/g, ' ');      db.collection('authors')         .findOne({"name": param})         .then(result => {             article = result;         }).then(() => {             res.send(article);         }).catch(e => {             console.error(e);         });  });  // Register server-side rendering middleware app.get('*', (req, res) => {   if (__DEV__) webpackIsomorphicTools.refresh();    const history = createHistory();   const store = configureStore(history);   const renderHtml = (store, htmlContent) => { // eslint-disable-line no-shadow     const html = renderToStaticMarkup(<Html store={store} htmlContent={htmlContent} />);      return `<!doctype html>${html}`;   };    // If __DISABLE_SSR__ = true, disable server side rendering   if (__DISABLE_SSR__) {     res.send(renderHtml(store));     return;   }    // Load data on server-side   const loadBranchData = () => {     const promises = [];      routes.some((route) => {       const match = matchPath(req.path, route);        // $FlowFixMe: the params of pre-load actions are dynamic       if (match && route.loadData) promises.push(route.loadData(store.dispatch, match.params));        return match;     });      return Promise.all(promises);   };    // Send response after all the action(s) are dispathed   loadBranchData()     .then(() => {       // Setup React-Router server-side rendering       const routerContext = {};       const htmlContent = renderToString(         <Provider store={store}>           <StaticRouter location={req.url} context={routerContext}>             <App />           </StaticRouter>         </Provider>,       );        // Check if the render result contains a redirect, if so we need to set       // the specific status and redirect header and end the response       if (routerContext.url) {         res.status(301).setHeader('Location', routerContext.url);         res.end();          return;       }        // Checking is page is 404       const status = routerContext.status === '404' ? 404 : 200;        // Pass the route and initial state into html template       res.status(status).send(renderHtml(store, htmlContent));     })     .catch((err) => {       res.status(404).send('Not Found :(');        console.error(`==> 😭  Rendering routes error: ${err}`);     }); });  // connect to mongo db var db const MongoClient = require('mongodb').MongoClient MongoClient.connect('mongodb://dannyjones360:test@ds123930.mlab.com:23930/halftimefront', (err, database) => {     if (err) return console.log(err);     db = database     console.log('db connected'); })  if (port) {   app.listen(port, host, (err) => {     const url = `http://${host}:${port}`;      if (err) console.error(`==> 😭  OMG!!! ${err}`);      console.info(chalk.green(`==> 🌎  Listening at ${url}`));      // Open Chrome     require('../tools/openBrowser')(url);   }); } else {   console.error(chalk.red('==> 😭  OMG!!! No PORT environment variable has been specified')); } 

config

module.exports = {   host: 3000 || 'localhost', // Define your host from 'package.json'   port: 3000,   app: {     htmlAttributes: { lang: 'en' },     title: 'Rendah',     titleTemplate: 'Rendah - %s',     meta: [       {         name: 'description',         content: 'Beats culture magazine',       },       {         name: 'apple-mobile-web-app-title',         content: 'Vernacare',       },       {         name: 'apple-mobile-web-app-capable',         content: 'yes',       },       {         name: 'apple-mobile-web-app-status-bar-style',         content: 'black',       },       {         name: 'theme-color',         content: '#ffffff',       },       {         name: 'mobile-web-app-capable',         content: 'yes',       },       {         name: 'theme-color',         content: '#fff',       },     ],   }, }; 

Any help or advice would be appreciated - thank you in advance.

After making ammends to Yoni Rabinovitch's answer, I deploy the site and now get:

2018-02-05T11:37:12.562907+00:00 heroku[web.1]: Process exited with status 1 2018-02-05T11:37:12.580445+00:00 heroku[web.1]: State changed from starting to crashed 2018-02-05T11:37:15.775044+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sleepy-scrubland-78530.herokuapp.com request_id=d7e4d005-d2f9-4c5f-89c8-14f2addc9ebf fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 2018-02-05T11:37:16.157734+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sleepy-scrubland-78530.herokuapp.com request_id=0f2a7123-f9bf-4ee0-bbc6-59894e21cc1b fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 2018-02-05T11:37:19.664289+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sleepy-scrubland-78530.herokuapp.com request_id=b3748306-5b3a-4dd6-be2c-58a171bafbd1 fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 2018-02-05T11:37:19.898230+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sleepy-scrubland-78530.herokuapp.com request_id=99b155b8-17e9-47da-a454-d3d4c6f45ef4 fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 2018-02-05T11:37:21.262972+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sleepy-scrubland-78530.herokuapp.com request_id=ca84a061-f834-476f-a269-7a9a8cd4adda fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 2018-02-05T11:37:21.537896+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sleepy-scrubland-78530.herokuapp.com request_id=9e6e9096-f6b4-4d73-b0c1-faf921ea8666 fwd="185.108.171.221" dyno= connect= service= status=503 bytes= protocol=https 

4 Answers

Answers 1

You seem to be setting the PORT env var in your package.json. You should not be doing that for Heroku. Heroku sets if for you automatically. Instead, add something like this in your server.js:

    app.set('port', process.env.PORT || 3000); 

The you can subsequently call app.listen(app.get('port'),...)

Answers 2

I was getting the same error, so I tried this method. I added this code to my package.json :

"scripts": {     "start": "node index.js" }, 

And in my Procfile:

web: npm start 

Answers 3

Try in your Procfile npm run start:production instead of using yarn. One time I got the same App crashed in Heroku because when calling the run scripts with yarn it didn't iniatilize the process global variable.

In the latest deploys I hadn't this problem, but it may be ocurring with you.

Answers 4

I am assuming that you are deploying a fresh/sample app. Can you please try above like for the same process :)

Heroku NodeJs sample app

Read More

Sunday, February 4, 2018

Heroku Application Error - Memory quota exceeded on deploy - Scout shows 4,804,423 allocations

Leave a Comment

I'm trying to find a memory bloat on my Rails application on Heroku.

I've read a bunch of articles about memory bloats and tried Scout to diagnose the problem.

I'm following Christoffers question about Heroku rising memory, but i have a different problem. Mine is almost always after a deploy, then the memory usage rises and my app breaks.

Here's an example from the Heroku Metrics: enter image description here

As you can see, the deploy is completed an then after the first visit the app is breaking.

I've benchmarked what i could(checked my queries) but nothing slow is showing in development. Also it doesn't seem that it's one controller, it's just the first controller to be used after the deploy that breaks. I've tried several, and they all break when they are first to load.

Scout Dashboard - Memory Allocation Breakdown is showing this as an example of a time out request for CategoriesController:

Scout Dashboard - Memory Allocation Breakdown

The partial and layout are rendering as it should under the image


System

I'm running Rails 5.1.4 with Webpacker installed and configured for Angular 2. This means that i've added a Procfile in my root with:

web: bundle exec puma -p $PORT this is recommended by Heroku documentation

The app is deploying as it should with minor errors about ... has incorrect peer dependency ...


Healthy and sick log

I've tried to locate a healthy Heroku log and a sick Heroku log.

Please request if this has any interest.


Number of workers

I've read the article Ruby Memory Use and tried to decrease the number of workers to 1 in my config/puma.rb, but with no result.



Updated!

1 . Weird behaviour with the memory usage on Heroku:

enter image description here

It's starting after the daily restart around 100 MB but then after the timeout (first visit) the memory usage JUMPS to just beneath 500 MB.

  1. @grizzthedj mentioned the public folder. It is 27.1 MB because of the heavy PDF.js plugin.

I'm looking for help to locate this problem. What could this be? Do you have any idea - let my try it!

I've tried what i found possible and nothing has helped yet.

Any help will be appreciated.

You can find the app on my Github page

1 Answers

Answers 1

There could be a few possibilities here.

First off, I suspect that there may be an issue with your webpacker build pipeline.

In your post, you mention that your pdf.js is 27.1 MB when deployed. When I download that file from the website, it is only ~514 KB.

I don't know what your webpacker build task is doing, but I suspect it may modifying this file unintentionally(via some wild card rule perhaps).

Secondly, there are also 3 other .js files in your /public/packs/ directory that are 7+ MB each. Thats almost 50 MB of .js alone! There are also duplicate pdf.js files in your public folder:

/public/pdfjs/build/pdf.js /public/pdf_categories/build/pdf.js  

Hard to tell if these are the only issues, but for starters, I would do the following(if you are not doing already):

  1. Double check that your webpacker is not adding any bloat to your pdf.js
  2. Use webpacker to minify your .js and .css files
  3. Ensure that you are using gzip compression for all static assets.
Read More

Thursday, February 1, 2018

Force Heroku PHP app to use https for both www and non-www versions

Leave a Comment

I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it's possible for a user to access the http version and I don't understand why.

Here is my .htaccess:

RewriteEngine on  RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$ RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R] 

My understanding is that this should force all users to access via https://www, but that doesn't always happen. For example, Google sometimes provides search results without the https and the links open insecure http instead.

Any ideas about what I'm doing wrong?

2 Answers

Answers 1

first redirect to the same host-name on :443, then redirect to www.. ordinary www. is just an alias in DNS, while most use the shorter non-www hostname for websites. you might have to extend the certificate, because it requires both host-names explicitly added, unless it's wild-carded.

one does not have to filter for the host-name:

RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

also see this answer here, concerning robots.txt with enforced SSL.

Answers 2

Try the following rules and let me know if it works or not these rule will use https request instead of http or www and non-www version. The following rule will now redirect the user to the something like this.

https://www.example.com/

RewriteEngine On  RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} !on RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE] 

Hope this will help to achieve what you wanted

Read More

Wednesday, January 17, 2018

How to troubleshoot memory bloat at boot for rails app?

Leave a Comment

I am having memory issues with a Rails app on Heroku running ruby 2.3.3 and Rails 4.1.13. When I load the app on Heroku it starts at around 430 Mb but is quite stable there - but still reached 512 Mb on Heroku (as would be expected). My main question is: How do I pinpoint and reduce memory usage during BOOT on my app? I.e. how do I reduce the amount of memory used at startup?

Heroku memory usage

I have looked into most gems, e.g. derailed, oink, memory profiler, and stackprof but what has helped me the most has been Scout add-on on Heroku in terms of finding memory bloats and memory hungry controllers etc. Through this I have managed to reduce the amount the application grows in terms of memory but not so much how much memory it uses at startup.

I know gems are loaded on startup and the more, and larger, the gems are the more memory is used at startup. Running bundle exec derailed bundle:mem gives me this:

TOP: 92.3008 MiB   carrierwave-aws: 16.7461 MiB     carrierwave/storage/aws: 16.6094 MiB       aws-sdk-core/s3: 7.9414 MiB       aws-sdk-resources: 2.5703 MiB         aws-sdk-core: 2.5117 MiB           jmespath: 1.8867 MiB             jmespath/nodes: 1.1406 MiB               jmespath/nodes/function: 0.3867 MiB       seahorse/client/base: 0.9414 MiB         seahorse/client/plugins/net_http: 0.5273 MiB       aws-sdk-core/xml/parser/engines/rexml: 0.8633 MiB         rexml/document: 0.8516 MiB           rexml/element: 0.5508 MiB   rails/all: 13.6992 MiB     rails: 8.9453 MiB (Also required by: active_record/railtie, active_model/railtie, and 6 others)       rails/application: 7.2188 MiB         rails/engine: 6.8672 MiB (Also required by: coffee/rails/engine)           rails/railtie: 6.5898 MiB (Also required by: sprockets/railtie, jbuilder/railtie)             rails/configuration: 6.3398 MiB (Also required by: rails/railtie/configuration)               active_support/core_ext/object: 6.0586 MiB                 active_support/core_ext/object/conversions: 4.7227 MiB                   active_support/core_ext/hash/conversions: 4.0039 MiB (Also required by: active_support/core_ext/hash, active_record/serializers/xml_serializer)                     active_support/time: 3.8008 MiB (Also required by: active_record/base)                       active_support/core_ext/time: 3.0938 MiB                         active_support/core_ext/time/calculations: 2.9922 MiB (Also required by: active_support/core_ext/numeric/time, active_support/core_ext/string/conversions)                           active_support/core_ext/time/conversions: 2.2148 MiB (Also required by: active_support/core_ext/time, active_support/core_ext/date_time/conversions)                             active_support/values/time_zone: 2.1602 MiB (Also required by: active_support/time_with_zone, active_support/core_ext/date_time/conversions)                               tzinfo: 1.8984 MiB                   active_support/core_ext/array/conversions: 0.6211 MiB (Also required by: active_support/duration, action_dispatch/http/request, and 2 others)                     active_support/xml_mini: 0.5508 MiB (Also required by: active_support/core_ext/hash/conversions)                 active_support/core_ext/object/json: 1.0352 MiB (Also required by: active_support/json/encoding)                   json: 0.7227 MiB (Also required by: active_support/json/decoding, pg/text_encoder, and 19 others)                     json/common: 0.3906 MiB (Also required by: json/ext)       active_support: 0.7109 MiB (Also required by: active_support/time, active_support/railtie, and 5 others)         active_support/dependencies/autoload: 0.332 MiB (Also required by: rails, active_support/rails)           active_support/inflector/methods: 0.332 MiB (Also required by: active_support/core_ext/string/inflections, active_support/core_ext/time/conversions, and 5 others)             active_support/inflections: 0.3164 MiB (Also required by: active_support/inflector)         active_support/logger: 0.3281 MiB       action_dispatch/railtie: 0.668 MiB (Also required by: action_controller/railtie)         action_dispatch: 0.6289 MiB (Also required by: action_controller)           active_support/rails: 0.4414 MiB (Also required by: active_record, active_model, and 4 others)             active_support/deprecation: 0.418 MiB (Also required by: sass/rails/helpers, formtastic/deprecation)     active_record/railtie: 2.8555 MiB       active_record: 1.9766 MiB (Also required by: friendly_id)         active_record/connection_adapters/abstract_adapter: 0.8516 MiB         arel: 0.8086 MiB (Also required by: active_record/base)           arel/visitors: 0.3438 MiB       action_controller/railtie: 0.875 MiB (Also required by: rails/all, sprockets/railtie)         action_controller: 0.6797 MiB (Also required by: heroku_rails_deflate/serve_zipped_assets)           action_controller/metal/live: 0.332 MiB     sprockets/railtie: 1.8516 MiB (Also required by: sass/rails/railtie)       sprockets/rails/helper: 0.918 MiB         action_view/helpers: 0.8945 MiB (Also required by: action_view/base)           action_view/helpers/form_helper: 0.3828 MiB (Also required by: action_view/helpers/form_options_helper)       sprockets: 0.9102 MiB (Also required by: sprockets/rails/helper)         sprockets/directive_processor: 0.5586 MiB           yaml: 0.5078 MiB (Also required by: active_support/ordered_hash, hirb, and 7 others)             psych: 0.5078 MiB   rails3-jquery-autocomplete: 9.9102 MiB     action_controller/base: 8.4922 MiB       action_controller/metal: 1.8281 MiB         abstract_controller/base: 1.0898 MiB           erubis: 0.8477 MiB (Also required by: action_view/template/handlers/erb, heroics)             erubis/engine: 0.4063 MiB (Also required by: erubis/engine/eruby)         action_dispatch/middleware/stack: 0.6367 MiB           active_support/dependencies: 0.5703 MiB (Also required by: abstract_controller/helpers, active_record/base)       abstract_controller/rendering: 1.5625 MiB         action_view/view_paths: 1.4531 MiB (Also required by: action_view/rendering)           action_view/base: 1.3477 MiB             action_view/lookup_context: 0.5156 MiB             action_view/template: 0.3789 MiB (Also required by: action_view/template/resolver)       action_controller/metal/redirecting: 1.0586 MiB         action_controller/metal/rack_delegation: 0.9297 MiB           action_dispatch/http/request: 0.8555 MiB       action_controller/metal/request_forgery_protection: 0.5859 MiB       action_controller/metal/params_wrapper: 0.5 MiB         action_dispatch/http/mime_type: 0.375 MiB (Also required by: abstract_controller/collector, jbuilder/jbuilder_template)       action_controller/metal/url_for: 0.3008 MiB     rails3-jquery-autocomplete/formtastic: 1.2578 MiB       formtastic/inputs/base: 0.8125 MiB   fog: 8.6523 MiB     fog/vcloud_director: 1.0156 MiB       fog/vcloud_director/compute: 0.9961 MiB         fog/vcloud_director/query: 0.4453 MiB           pp: 0.418 MiB (Also required by: scout_apm)     fog/openstack: 0.8398 MiB     fog/cloudstack: 0.5859 MiB       fog/cloudstack/compute: 0.5859 MiB     fog/internet_archive: 0.543 MiB       fog/internet_archive/storage: 0.5352 MiB         fog/internet_archive/core: 0.3125 MiB     fog/rackspace: 0.3867 MiB     fog/cloudsigma: 0.3594 MiB       fog/cloudsigma/compute: 0.3047 MiB     fog/vcloud: 0.3203 MiB       fog/vcloud/compute: 0.3125 MiB     fog/aws: 0.3125 MiB   twitter: 8.3711 MiB     addressable/uri: 4.2422 MiB (Also required by: twitter/base, twitter/rest/request, and 8 others)       addressable/idna: 2.7891 MiB         addressable/idna/pure: 2.7461 MiB       public_suffix: 0.3242 MiB     twitter/streaming/client: 1.7266 MiB       twitter/streaming/response: 1.4453 MiB         http: 1.418 MiB           http/response: 1.2109 MiB             http/cookie_jar: 0.9219 MiB               http/cookie: 0.9102 MiB                 domain_name: 0.8203 MiB                   domain_name/etld_data: 0.7813 MiB     twitter/configuration: 0.8477 MiB (Also required by: twitter/rest/help)       twitter/base: 0.6016 MiB (Also required by: twitter/entity, twitter/identity, and 12 others)         twitter/null_object: 0.4688 MiB (Also required by: twitter/trend_results)           naught: 0.4063 MiB     twitter/cursor: 0.8164 MiB (Also required by: twitter/rest/utils, twitter/rest/friends_and_followers, and 2 others)       twitter/rest/request: 0.7852 MiB (Also required by: twitter/rest/utils, twitter/rest/friends_and_followers, and 8 others)         faraday: 0.6406 MiB (Also required by: twitter/rest/client, twitter/rest/response/parse_json, and 6 others)     twitter/rest/client: 0.418 MiB       twitter/rest/api: 0.3828 MiB   asset_sync: 4.9609 MiB     asset_sync/multi_mime: 4.5039 MiB       mime/types: 4.4883 MiB (Also required by: mime/types/columnar)         mime/types/registry: 4.1914 MiB     asset_sync/storage: 0.4375 MiB       fog/core: 0.4063 MiB (Also required by: fog, fog/xml, and 48 others)   platform-api: 4.5273 MiB     platform-api/client: 2.8359 MiB   newrelic_rpm: 3.875 MiB     new_relic/control: 3.875 MiB       new_relic/agent: 3.4883 MiB         new_relic/agent/agent: 1.7422 MiB           new_relic/agent/configuration/manager: 0.4961 MiB (Also required by: new_relic/agent/configuration)             new_relic/agent/configuration/default_source: 0.3633 MiB         new_relic/agent/transaction_sampler: 0.3516 MiB   carrierwave: 2.8281 MiB (Also required by: carrierwave-aws)     carrierwave/uploader: 1.7656 MiB   friendly_id: 2.5273 MiB     friendly_id/object_utils: 2.4453 MiB       active_record/base: 2.4258 MiB         active_record/querying: 0.3906 MiB   compass: 2.1328 MiB (Also required by: compass-rails)     compass/sass_extensions: 1.2461 MiB       compass/sass_extensions/sprites: 0.6875 MiB         compass/sass_extensions/sprites/engines: 0.4609 MiB           compass/sass_extensions/sprites/engines/chunky_png_engine: 0.4492 MiB             chunky_png: 0.4492 MiB       compass/sass_extensions/functions: 0.5078 MiB     compass/configuration: 0.6172 MiB       compass/configuration/data: 0.6133 MiB   pg: 2.1055 MiB     pg_ext: 1.9102 MiB   feedjira: 2.0781 MiB     loofah: 0.625 MiB     sax-machine: 0.4414 MiB   sass-rails: 1.8047 MiB     sass/rails: 1.8008 MiB       sass/rails/helpers: 1.7578 MiB         sprockets/sass_functions: 1.7383 MiB           sass: 1.7383 MiB (Also required by: sass/rails/importer, sprockets/sass_importer)             sass/engine: 1.4492 MiB               sass/script: 0.5586 MiB (Also required by: sass/script/css_parser)               sass/scss: 0.3281 MiB                 sass/scss/parser: 0.3047 MiB   scout_apm: 1.418 MiB     webrick: 0.5664 MiB   jbuilder: 1.1016 MiB (Also required by: jbuilder/jbuilder_template)     active_support/cache: 0.3906 MiB   rmagick: 1.0234 MiB     rmagick_internal.rb: 1.0195 MiB       RMagick2.so: 0.6875 MiB   lazyload-rails: 0.8555 MiB     nokogiri: 0.8555 MiB (Also required by: TOP, sax-machine/handlers/sax_nokogiri_handler, and 5 others)   sitemap_generator: 0.5195 MiB   dalli: 0.4648 MiB   unicorn: 0.457 MiB   hirb: 0.3984 MiB 

I imagine 92 Mb is quite a bit in terms of gems but I do use them all in the app. Carrierwave is the largest, but very important in how I cache images on AWS (as well as with Fog) and so on. This only accounts for about 1/4 of the memory used at boot though.

In my application controller I have a before filter where I load some variables that are used throughout the website (in global headers, sidebars etc) like this:

@search = TextSearch.new    @administrator_logged_in = current_administrator     @nbr_of_stores_total = Store.active.size # Used in header @nbr_of_blog_posts_total = BlogPost.once_posted.size # Used in header contests_open = Contest.active.open.size @active_contests_string = contests_open > 0 ? " (" << contests_open.to_s << ")" : "" add_breadcrumb "Home", root_path @open_graph_image = "https://s3.eu-central-1.amazonaws.com/myapp/assets/myapp_logo_large.png"  # Season-related @is_christmas = false @gift_word_seasonal = "christmas presents" 

I would imagine this would be loaded into boot (and overall) memory, right?

Where else, and how, should I look for startup memory-usage? In short:

  1. Where in my rails app should I trouble boot memory (like middleware, initializers etc)?

  2. What tools (such as the derailed command above) can I use to find/pinpoint memory hungry calls/actions?

  3. I am having trouble finding the direct cause and effect on my trouble shooting actions. Like, finding the answer to "if I remove this code, how much memory do I save?". How should I measure/benchmark any actions I do on my app (rather than upload and check the overall usage in the graph)?

1 Answers

Answers 1

Try running GC.stat command This would give info on memory usage and garbage collection in the app based on which you can decide.

Do memory profiling https://github.com/ice799/memprof could also be of help to you

Read More

Wednesday, January 10, 2018

Heroku Ruby / Rails Cache Webpack + Yarn Between Deploys

Leave a Comment

I currently have a brand new ruby / rails app setup with webpacker. Every deploy to Heroku takes an additional 30+ seconds to re-install the yarn dependencies (runs yarn install).

remote:        [1/4] Resolving packages... remote:        [2/4] Fetching packages... remote:        info fsevents@1.1.3: The platform "linux" is incompatible with this module. remote:        info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation. remote:        [3/4] Linking dependencies... remote:        warning "babel-loader@7.1.2" has incorrect peer dependency "babel-core@6 || 7 || ^7.0.0-alpha || ^7.0.0-beta || ^7.0.0-rc". remote:        warning "babel-loader@7.1.2" has incorrect peer dependency "webpack@2 || 3". remote:        warning "compression-webpack-plugin@1.1.2" has incorrect peer dependency "webpack@^2.0.0 || ^3.0.0". remote:        warning "extract-text-webpack-plugin@3.0.2" has incorrect peer dependency "webpack@^3.1.0". remote:        warning "file-loader@1.1.5" has incorrect peer dependency "webpack@^2.0.0 || ^3.0.0". remote:        warning "postcss-cssnext@3.0.2" has incorrect peer dependency "caniuse-lite@^1.0.30000697". remote:        warning "rails-erb-loader@5.2.1" has incorrect peer dependency "webpack@^2.0.0 || >= 3.0.0-rc.0 || ^3.0.0". remote:        warning "sass-loader@6.0.6" has incorrect peer dependency "node-sass@^4.0.0". remote:        warning "sass-loader@6.0.6" has incorrect peer dependency "webpack@^2.0.0 || >= 3.0.0-rc.0 || ^3.0.0". remote:        warning "url-loader@0.6.2" has incorrect peer dependency "file-loader@*". remote:        warning "webpack-manifest-plugin@1.3.2" has incorrect peer dependency "webpack@1 || 2 || 3". remote:        warning "ajv-keywords@2.1.1" has incorrect peer dependency "ajv@^5.0.0". remote:        warning "uglifyjs-webpack-plugin@0.4.6" has incorrect peer dependency "webpack@^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc || ^3.0.0". remote:        warning "babel-plugin-transform-vue-jsx@3.5.0" has incorrect peer dependency "babel-helper-vue-jsx-merge-props@^2.0.0". remote:        warning "babel-plugin-transform-vue-jsx@3.5.0" has incorrect peer dependency "babel-plugin-syntax-jsx@^6.8.0". remote:        warning "vue-loader@13.5.0" has incorrect peer dependency "css-loader@*". remote:        warning "webpack-dev-server@2.9.7" has incorrect peer dependency "webpack@^2.2.0 || ^3.0.0". remote:        warning "webpack-dev-middleware@1.12.2" has incorrect peer dependency "webpack@^1.0.0 || ^2.0.0 || ^3.0.0". remote:        [4/4] Building fresh packages... remote:        Done in 33.50s. remote:        Webpacker is installed 🎉 🍰 

I'm currently using the heroku/ruby buildpack on the heroku-16 stack. Any easy way to get the caching to work like it does for bundler?

1 Answers

Answers 1

Maybe you can add a second nodejs buildpack in addition to your heroku stack:

heroku buildpacks:add --index 1 heroku/nodejs 

The nodejs buildpack should support yarn caching as described here.

Read More

Wednesday, December 27, 2017

Deploy app to Heroku with separate frontend/backend servers

Leave a Comment

I'm currently trying to deploy an app to a single Heroku dyno which does not use create-react-app but has an express server for webpack and a rails API backend.

I'm having issues getting express to proxy my requests to the API (but works fine locally), here is the error from Heroku logs:

2017-12-03T16:00:18.436271+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3005 2017-12-03T16:00:18.436308+00:00 app[web.1]:     at Object.exports._errnoException (util.js:1018:11) 2017-12-03T16:00:18.436309+00:00 app[web.1]:     at exports._exceptionWithHostPort (util.js:1041:20) 2017-12-03T16:00:18.436311+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14) 

I made sure to use buildpacks for both node and rails as described here.

Here is the relevant code:

Procfile

web: npm run start:prod api: bundle exec rails server --port=3005 --environment=production -b 127.0.0.1 

package.json

{   "name": "foo",   "version": "1.0.0",   "main": "index.js",   "license": "MIT",   "proxy": "http://127.0.0.1:3005/",   "engines": {     "node": "6.10.2",     "yarn": "0.24.5",     "npm": "5.5.1"   },   "scripts": {     "start": "NODE_ENV=development node server",     "start:prod": "yarn run build && NODE_ENV=production node server",     "build": "NODE_ENV=production webpack -p --config ./webpack.prod.js --progress --colors --display-error-details"   }, 

server.js

const express = require('express'); const proxy = require('express-http-proxy');  const app = express();  const port = process.env.PORT || 3000; const path = require('path') const webpack = require('webpack')  const proxyHost = '127.0.0.1'; const proxyPort = '3005';  app.use('/api', proxy(`${proxyHost}:${proxyPort}`));  const isProd = process.env.NODE_ENV === 'production'  let config  if (isProd) {   config = require('./webpack.prod.js') } else {   config = require('./webpack.dev.js') }  const publicPath = config.output.publicPath || '/'; const outputPath = config.output.path || path.resolve(process.cwd(), 'dist');  if (!isProd) {   console.log('Development env detected: Initializing hot reloading')   const webpackDevMiddleware = require('webpack-dev-middleware')   const webpackHotMiddleware = require('webpack-hot-middleware')   const compiler = webpack(config)    app.use(webpackHotMiddleware(compiler, {     log: console.log,     path: '/__webpack_hmr'   }))    app.use(webpackDevMiddleware(compiler, {     entry: config.entry,     publicPath: config.output.publicPath,     stats: {       colors: true     }   }))    app.use('*', function (req, res, next) {     const filename = path.join(compiler.outputPath, 'index.html')     compiler.outputFileSystem.readFile(filename, (err, result) => {       if (err) {         return next(err)       }       res.set('content-type', 'text/html')       res.send(result)       res.end()     })   })  } else {   app.use(publicPath, express.static(outputPath));   app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html'))); }  app.listen(port, (err) => {   if (err) {     console.log(err.message)   } else {     console.log(`Server Started at port ${port}`);   } }); 

Any help would be greatly appreciated!

EDIT FOR SOLUTION

So I was able to get to a solution based on the accepted answer below, but thought I'd update the post to give the specifics.

As pointed out in the answer, it seems Heroku uses a different dyno per process in your Procfile, which was why the frontend/backend servers were originally unable to communicate with each other.

To circumvent this, I simply created a dummy procfile which used foreman to initialize the real procfile:

Procfile (dummy used by Heroku)

web: foreman start -f StartProcfile 

StartProcfile (the actual processes)

web: npm run start:prod api: bundle exec rails server --port=3005 --environment=production 

It should be noted that in my case I ran into additional issues with exceeding the dyno memory cap AND taking longer than 60s to bind to the assigned heroku port. Turns out it was because I was including the build step as part of the web process, when I should have been using the postinstall hook in package.json.

package.json

  "scripts": {     "start": "NODE_ENV=development node server",     "start:prod": "NODE_ENV=production node server --optimize_for_size --max_old_space_size=460 --gc_interval=100",     "build": "NODE_ENV=production webpack -p --config ./webpack.prod.js --progress --colors --display-error-details",     "postinstall": "npm run build"   }, 

1 Answers

Answers 1

Each line in the Procfile ends up running in a separate dyno. If you need both processes to run on the same dyno (in this case web) then you need to either redefine web to call something like a shell script that launches the node server and then launches the rails server, or have the node boot process launch the rails server.

Full disclosure, I have never actually done what you are attempting. Binding the rails API server to port 3005 may not work even after making the changes outlined above. But, for sure, 127.0.0.1 in a web process will never be 127.0.0.1 in an api process since they will always run on different dynos. Hopefully that info helps.

Read More

Tuesday, December 5, 2017

Tests that use h2 in-mem db fail on Heroku

Leave a Comment

My Spring boot app has some tests that pass fine on my local, but fail on Heroku:

org.h2.jdbc.JdbcSQLException: Exception opening port "8082" (port may be in use), cause: "java.net.BindException: Address already in use (Bind failed)" [90061-196]

The data source configuration for the test profile:

@Configuration public class TestDataSourceConfiguration {     @Bean     @ConfigurationProperties(prefix = "spring.datasource")     @Profile("test")     public DataSource testDataSource() throws URISyntaxException {         return DataSourceBuilder.create().build();     } } 

application-test.properties: spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=

spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 

I know Heroku doesn't support h2, but this shouldn't be the case here as the app itself brings up the db, right?

Maybe I'm wrong, and it is not failing because of Heroku not supporting h2, but I don't have any other process listening on port 8082 (at least that I know of and being initiated from within my app)

3 Answers

Answers 1

Heroku will pass port number, you would need to use as enviroment variable with name PORT.

In order to use this variable to set your application port, you have to add line to your application-test.properties :

server.port=${PORT:8082} 

Or application-test.yml:

server:      port: ${PORT:8082} 

In case PORT is not set (like in your local environment), then default 8082 would be used.

This should cover java.net.BindException exception.

Answers 2

The db will not be auto generated unless you add this property in your properties file

spring.jpa.hibernate.ddl-auto = update 

Answers 3

This happens because of a discrepency between how tests are run on eclipse and Heroku. Eclipse runs each test separately, which means it runs each test with fresh start run of the whole application. But Heroku runs all the test classes on one machine sequentially. Therefore I have to kill the h2 server after each test class is finished running:

@AfterClass public static void tearDown() throws SQLException {     webServer.stop(); } 
Read More

Friday, November 24, 2017

Pushing to Heroku Fails - sinon-mongoose, grpc, node-pre-gyp

Leave a Comment

Up until yesterday I could push to Heroku. Currently, I'm getting my push to Heroku rejected with the following error message:

Installing node modules (yarn.lock) yarn install v1.3.2 [1/4] Resolving packages... [2/4] Fetching packages... [3/4] Linking dependencies... warning " > sinon-mongoose@1.3.0" has incorrect peer dependency "sinon@1". [4/4] Building fresh packages... error /tmp/build_592ecabd23ba493189b9cac8d/node_modules/multer-gcs/node_modules/grpc: Command failed. Exit code: 127 Command: ./node_modules/.bin/node-pre-gyp install --fallback-to-build Arguments: Directory: /tmp/build_592ecabd23ba493189b9cac8d/node_modules/multer-gcs/node_modules/grpc Output: /bin/sh: 1: ./node_modules/.bin/node-pre-gyp: not found info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command. 

The strange thing is that node-pre-gyp is there in the file path specified. How can I get my push to work? I've also tried updating the package.json, specifying the versions for engines.node, engines.npm, engines.yarn, since these were mentioned in the error message.

UPDATE:

I now know that the issue is coming from gcloud ("gcloud":"^0.37.2";) , since I temporarily removed that module from package.json and pushed again and the push went through without the error message.

0 Answers

Read More

Wednesday, September 6, 2017

Ruby on rails bootsy + cloudinary upload image trouble

Leave a Comment

I have RoR project, living on heroku. I have bootsy (editor with image upload funcs) and I have cloudinary. Ive setup uploader, cloudinary api keys and initializers (can show you, if it needed). Now, when I try to upload image in bootsy - it creates database row, and create image in cloudinary. But in js window from bootsy, there empty <img>

ruby '2.3.1' gem 'rails', '~> 5.1.1' gem 'bootsy' gem 'carrierwave' gem 'fog' gem 'cloudinary', '~> 1.8.1' 

1) uploaders/bootsy/image_uploader.rb

module Bootsy   class ImageUploader < CarrierWave::Uploader::Base     include CarrierWave::MiniMagick      # storage Bootsy.storage      include Cloudinary::CarrierWave      def store_dir       "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"     end      version :large do       process :eager => true       process resize_to_fit: [                   700, 700               ]      end      version :medium do       process :eager => true       process resize_to_fit: [                   300, 300               ]     end      version :small do       process :eager => true       process resize_to_fit: [                   150, 150               ]     end      version :thumb do       process :eager => true       process resize_to_fit: [                   150, 150               ]     end       def extension_white_list       %w(jpg jpeg gif png)     end   end end 

2) initializers/bootsy.rb

Bootsy.setup do |config|   config.image_versions_available = [:small, :medium, :large, :original]   config.storage = :fog end 

3) models/article.rb

class Article < ApplicationRecord   include Bootsy::Container   mount_uploader :image, Bootsy::ImageUploader    mount_uploader :main_image, ArticleImageUploader   mount_uploader :list_image, ArticleImageUploader  end 

This what I've in browser And html code from inspect

P.S Ok, I really have no idea - I just repeat this bug in public repository. https://bitbucket.org/dekakisalove/bootsy_tes/ I will add bounty to this question as soon as it will be possible.

1 Answers

Answers 1

This problem is due to an incorrect return value the method store! of class Cloudinary::CarrierWave::Storage

To work around this problem, you can use several variants, for example:

like this in config/initializers/cloudinary_store.rb

module CloudinaryStorage   def store!(file)     super || uploader.metadata   end end  ActiveSupport.on_load :after_initialize do   Cloudinary::CarrierWave::Storage.prepend CloudinaryStorage end 

or like this inapp/uploaders/image_uploader.rb

module Bootsy   class ImageUploader < CarrierWave::Uploader::Base     after :store, :reload_data      def reload_data(file)       model.reload     end     # etc.. 
Read More

Tuesday, August 29, 2017

devise token auth errors

Leave a Comment

I currently have a Rails 5 app running using Devise Token Auth, it is deployed on heroku.

Signing in and signing up all works fine, however, if restart the application, the next sign in, gives me a 500, with the following error.. Any ideas?

I have narrowed the bug down, it only happens on Heroku. When running locally in production mode it is fine.

vendor/bundle/ruby/2.3.0/gems/devise_token_auth-0.1.42/app/controllers/devise_token_auth/sessions_controller.rb:42:in `[]=' vendor/bundle/ruby/2.3.0/gems/devise_token_auth-0.1.42/app/controllers/devise_token_auth/sessions_controller.rb:42:in `create' 

devise initalizer:

Devise.setup do |config|   config.secret_key = 'xxx' 

devise token auth initalizer:

DeviseTokenAuth.setup do |config|   config.change_headers_on_each_request = false   config.token_lifespan = 1.year end 

Profile.rb (model which handles auth):

devise :database_authenticatable, :registerable,        :recoverable, :trackable, :validatable include DeviseTokenAuth::Concerns::User 

Longer stack trace

2017-08-21T13:47:59.917645+00:00 app[web.1]: I, [2017-08-21T13:47:59.917547 #4]  INFO -- : [8f6962a7-f07c-4754-959c-c51dafa37d76] Started POST "/auth/sign_in" for 82.163.112.30 at 2017-08-21 13:47:59 +0000 2017-08-21T13:48:00.165030+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action' 2017-08-21T13:48:00.165036+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/activesupport-5.1.3/lib/active_support/notifications.rb:166:in `instrument' 2017-08-21T13:47:59.925118+00:00 app[web.1]: I, [2017-08-21T13:47:59.925047 #4]  INFO -- : [8f6962a7-f07c-4754-959c-c51dafa37d76] Processing by DeviseTokenAuth::SessionsController#create as */* 2017-08-21T13:48:00.165031+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/abstract_controller/base.rb:186:in `process_action' 2017-08-21T13:48:00.165036+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/instrumentation.rb:30:in `process_action' 2017-08-21T13:47:59.925184+00:00 app[web.1]: I, [2017-08-21T13:47:59.925134 #4]  INFO -- : [8f6962a7-f07c-4754-959c-c51dafa37d76]   Parameters: {"email"=>"rob@example.com", "password"=>"[FILTERED]", "session"=>{"email"=>"rob@example.com", "password"=>"[FILTERED]"}} 2017-08-21T13:48:00.165032+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/rendering.rb:30:in `process_action' 2017-08-21T13:48:00.165036+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/params_wrapper.rb:252:in `process_action' 2017-08-21T13:47:59.976389+00:00 app[web.1]: D, [2017-08-21T13:47:59.976252 #4] DEBUG -- : [8f6962a7-f07c-4754-959c-c51dafa37d76]   Profile Load (2.1ms)  SELECT  "profiles".* FROM "profiles" WHERE (email = 'rob@example.com' AND provider='email') ORDER BY "profiles"."id" ASC LIMIT $1  [["LIMIT", 1]] 2017-08-21T13:48:00.165032+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/abstract_controller/callbacks.rb:20:in `block in process_action' 2017-08-21T13:48:00.165037+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/activerecord-5.1.3/lib/active_record/railties/controller_runtime.rb:22:in `process_action' 2017-08-21T13:48:00.163017+00:00 app[web.1]: I, [2017-08-21T13:48:00.162930 #4]  INFO -- : [8f6962a7-f07c-4754-959c-c51dafa37d76] Completed 500 Internal Server Error in 238ms (ActiveRecord: 19.2ms) 2017-08-21T13:48:00.165033+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/activesupport-5.1.3/lib/active_support/callbacks.rb:131:in `run_callbacks' 2017-08-21T13:48:00.164815+00:00 app[web.1]: F, [2017-08-21T13:48:00.164748 #4] FATAL -- : [8f6962a7-f07c-4754-959c-c51dafa37d76]    2017-08-21T13:48:00.165033+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/abstract_controller/callbacks.rb:19:in `process_action' 2017-08-21T13:48:00.164880+00:00 app[web.1]: F, [2017-08-21T13:48:00.164820 #4] FATAL -- : [8f6962a7-f07c-4754-959c-c51dafa37d76] IndexError (string not matched): 2017-08-21T13:48:00.165034+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/rescue.rb:20:in `process_action' 2017-08-21T13:48:00.164933+00:00 app[web.1]: F, [2017-08-21T13:48:00.164884 #4] FATAL -- : [8f6962a7-f07c-4754-959c-c51dafa37d76]    2017-08-21T13:48:00.165034+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' 2017-08-21T13:48:00.165028+00:00 app[web.1]: F, [2017-08-21T13:48:00.164957 #4] FATAL -- : [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/devise_token_auth-0.1.42/app/controllers/devise_token_auth/sessions_controller.rb:42:in `[]=' 2017-08-21T13:48:00.165035+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/activesupport-5.1.3/lib/active_support/notifications.rb:166:in `block in instrument' 2017-08-21T13:48:00.165029+00:00 app[web.1]: [8f6962a7-f07c-4754-959c-c51dafa37d76] vendor/bundle/ruby/2.3.0/gems/devise_token_auth-0.1.42/app/controllers/devise_token_auth/sessions_controller.rb:42:in `create' 

1 Answers

Answers 1

Adding this to my migration fixed it:

reversible do |direction|   direction.up do     User.find_each do |user|       user.tokens = nil       user.save!     end   end end 
Read More

Friday, August 18, 2017

OAuth2::Error, invalid_request: redirect_uri does not match application configuration

Leave a Comment

I'm working on a rails app that authenticates using Bungie OAuth using this gem. My configurations in initializers/devise.rb are as follows:

config.omniauth :bungie, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'], ENV['X_API_KEY'], ENV['REDIRECT_URL'] 

Bungie's developer portal requires a redirect URL with HTTPS, so I've pushed my application to Heroku and used a redirect to force authentication back to localhost for testing. Using this method, everything works fine. However, when I push the app to production, the response back to my application from Bungie fails with OAuth2::Error, invalid_request: redirect_uri does not match application configuration. The redirect_url is the exact same thing in both my application's env variables and on Bungie's development portal.

Seeing as it's in production, I'm limited to the logs that I can see. I've tried tracking the requests in the network tab of the dev tools in my browser, but everything looks as it should.

I've tried working with the developer of the bungie-oauth2 gem, but we have not been able to come to a resolution (and his prod apps work fine with it).

Is there anything that might cause the redirect_url to differ once in Heroku?

As requested, here is my route for omniauth:

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } 

Output from rake routes:

 users_sign_out GET      /users/sign_out(.:format)             devise/sessions#destroy           new_user_session GET      /users/sign_in(.:format)              devise/sessions#new               user_session POST     /users/sign_in(.:format)              devise/sessions#create       destroy_user_session DELETE   /users/sign_out(.:format)             devise/sessions#destroy user_bungie_omniauth_authorize GET|POST /users/auth/bungie(.:format)          users/omniauth_callbacks#passthru user_bungie_omniauth_callback GET|POST /users/auth/bungie/callback(.:format) users/omniauth_callbacks#bungie          new_user_password GET      /users/password/new(.:format)         devise/passwords#new         edit_user_password GET      /users/password/edit(.:format)        devise/passwords#edit              user_password PATCH    /users/password(.:format)             devise/passwords#update                            PUT      /users/password(.:format)             devise/passwords#update                            POST     /users/password(.:format)             devise/passwords#create   cancel_user_registration GET      /users/cancel(.:format)               devise/registrations#cancel      new_user_registration GET      /users/sign_up(.:format)              devise/registrations#new     edit_user_registration GET      /users/edit(.:format)                 devise/registrations#edit          user_registration PATCH    /users(.:format)                      devise/registrations#update                            PUT      /users(.:format)                      devise/registrations#update                            DELETE   /users(.:format)                      devise/registrations#destroy                            POST     /users(.:format)                      devise/registrations#create 

and my controller:

def bungie   @user = User.from_omniauth(request.env["omniauth.auth"])    if @user.persisted?     @user.remember_me = true     sign_in_and_redirect @user, :event => :authentication   else     session["devise.bungie_data"] = request.env["omniauth.auth"]     redirect_to root_path   end end 

Full source can be found at https://github.com/destiny-aviato/destinder.

2 Answers

Answers 1

Encoding of redirect_uri param in your auth request to bungie jumps out:

https%25253A%25252F%25252Fdestinder.herokuapp.com%25252Fusers%25252Fauth%25252Fbungie%25252Fcallback 

To read it in plain, I had to decode it thrice. Normally params are encoded just once

URI.decode(URI.decode(URI.decode("https%25253A%25252F%25252Fdestinder.herokuapp.com%25252Fusers%25252Fauth%25252Fbungie%25252Fcallback"))) 

Not sure if this is what causing the issue. Can you check how many times request_uri gets encoded when you hit it from local. If it's less than 3, then during heroku deployment your request_uri gets encoded one extra time.

To get request_uri for local, logout from bungie, click on "Sign in with bungie" on your local. The url in browser would have request_uri.

Answers 2

replace redirect url of your Heroku application in credential

Read More