Rails Job loses reference to module randomly - ruby-on-rails

EDIT: same things happens when I fork a process manually...
I'm getting some weird behavior with a Rails Job that calls a module of mine called RedisService.
I've added lib/modules to my autoload_paths but the TextService module that calls the RedisService one loses reference to it, sometimes immediately, sometimes 3 or 4 job calls in...
I've even required the module in my TextService to no avail, even added some puts to check that always show the module is defined and responds to the method I'm calling...!
Something escapes me...
Here's a gist to the backtrace
Repo: https://gitlab.com/thomasbromehead/snmp-simulator-ruby-manager.
ruby --version: 2.6.5
rails version: 6.1.3.1
My "service" objects:
Module that calls RedisService
require_relative 'redis_service'
module TextService
def self.write_to_file(dataObject, redis, path: "./")
begin
file_with_path = path + dataObject.filename
# Store all lines prior to the one being modified, File.read closes the file
f = File.read(file_with_path)
new_content = f.gsub(dataObject.old_set_value, dataObject.new_set_value)
# File.open closes the file when passed a block
File.open(file_with_path, "w") { |file| file.puts new_content }
puts "Redis is: #{redis}" ======> RedisService
puts "Redis responds to multi: #{redis.respond_to?(:multi)}" ======> true
redis.multi do
redis.zrem("#{dataObject.name}-sorted-set", dataObject.old_set_value)
redis.hset("#{dataObject.name}-offsets", "#{dataObject.start_index}:#{dataObject.oid}:#{dataObject.end_index}", dataObject.new_set_value)
redis.zadd("#{dataObject.name}-sorted-set", dataObject.start_index, dataObject.new_set_value)
end
rescue EOFError
end
end
Variation class called from VariateJob
require_relative '../../../lib/modules/redis_service'
module Snmp
class Variation
include ActiveModel::Model
attr_reader :oid, :type, :duration, :to, :from, :filename, :redis
def initialize(oid:nil, duration:nil, type:nil, to:nil, filename: nil, from:nil)
#to = to
#from = from
#oid = oid
#type = type
#filename = filename
#redis = RedisService
end
def run(data)
current_value, new_set_value, start_index, end_index = prepare_values(JSON.parse(data))
transferData = Snmp::TransferData.new({
filename: #filename,
old_set_value: current_value,
new_set_value: new_set_value,
start_index: start_index,
end_index: end_index,
name: #name,
oid: oid
})
TextService.write_to_file(transferData, #redis)
end
VariateJob
class VariateJob < ApplicationJob
queue_as :default
def perform(dumped_variation, data)
Marshal.load(dumped_variation).run(Marshal.load(data))
end
end
VariationsController
class VariationsController < ApplicationController
before_action :set_file_name, only: :start
def start
if params["linear"]
type = :linear
elsif params["random"]
type = :random
end
data = redis.hscan_each("##name-offsets", match: "*:#{params["snmp_variation"]["oid"]}*")
# data is an Enumerator, transform it to an array and dump to JSON
variation = Snmp::Variation.new(params_to_keywords(params["snmp_variation"]).merge({type: type}))
VariateJob.perform_later(Marshal.dump(variation), Marshal.dump(JSON.generate(data.to_a.first)))
end
RedisService
require 'redis'
module RedisService
include GlobalID::Identification
[...]
def self.multi(&block)
#redis.multi { block.call() }
end
[...]
end

You are not losing the reference to the RedisService, but to Redis in your RedisService. Probably because you use a server or worker that forks new processes and you don't initialize a new connection after the fork.
To fix this issue I would replace this method
def self.start(host,port)
#redis ||= Redis.new(host: host, port: port)
self
end
with
def self.redis
#redis ||= Redis.new(host: ::Snmpapp.redis_config[:host], port: ::Snmpapp.redis_config[:port])
end
And then I would replace all call to the #redis with a redis call to the new method.

Related

Pivotal tracker story is not getting updated after code push

We had pivotal tracker integrated with GitHub and when we used to commit with story id, it used to update the story with a commit message update story status.
We recently migrated to Team Foundation Server from GitHub and that integration is not working anymore.
Looks like there is no integration App exists yet.
Is there a programmatic way of doing it?
Create file named pre-push (without any extension) and put it under ./.git/hooks/ folder inside your repo. This folder should already exist if it's a valid repo. Copy paste following code in the file. Don't forget to replace the API token value in the following code -
#!/usr/bin/env ruby
# encoding: UTF-8
require 'net/https'
require 'json'
class GitLogs
attr_accessor :raw_log, :commit_data, :commit, :author, :message, :refs
def initialize
self.commit = 'Commit: ' + `git log -1 --pretty=format:%h`.force_encoding('utf-8')
self.author = 'Author: ' + `git log -1 --pretty=format:%aN`.force_encoding('utf-8')
self.message = 'Message: ' + `git log -1 --pretty=format:%s`.force_encoding('utf-8')
self.refs = 'Refs: ' + `git log -1 --pretty=format:%d`.force_encoding('utf-8')
# Example git formatted log output:
#
# Commit: 8872e8fe03a10238d7be84d78813874d79ce0c3d
# Author: John Doe <john.doe#unknown.com>
# Message: [#90743834] test new v5 hook addition
# Refs: (HEAD, feature/hook-test)
parse!
self
end
def parse!
self.commit_data = GitLog.new(self.commit, self.author, self.message, self.refs)
end
def pivotal_sync!
Pivotal.new(commit_data).send! if commit_has_story_id?
end
def commit_has_story_id?
# somewhere between square brackets there has to be a hash followed by multiple digits
!commit_data.message.scan(/\[*+\#(\d+)\D?(.*)\]/).empty?
end
end
class GitLog
attr_accessor :hash, :author, :message, :refs
def initialize hash, author, message, refs
self.hash = hash
self.author = author
self.refs = refs
self.message = message
updated_message
end
def updated_message
return message
end
def to_json
{ source_commit:
{ commit_id: self.hash,
author: self.author,
message: self.message,
}
}.to_json
end
end
class Pivotal
attr_accessor :git_log, :tracker_token
BASE_URI = URI('https://www.pivotaltracker.com/')
def initialize git_log
self.git_log = git_log
self.tracker_token = get_token
end
def get_token
'YOUR APT TOKEN GOES HERE. CAN GET IT FROM https://www.pivotaltracker.com/profile'
end
def send!
https = Net::HTTP.start(BASE_URI.host, 443, {
use_ssl: true,
verify_mode: OpenSSL::SSL::VERIFY_NONE
})
request = Net::HTTP::Post.new('/services/v5/source_commits')
request['X-TrackerToken'] = tracker_token
request['Content-type'] = 'application/json'
request.body = git_log.to_json
response = https.request(request)
end
end
GitLogs.new().pivotal_sync!

What could cause performance issue(s) when using roadie-rails for our case?

Originally posted as
https://github.com/Mange/roadie-rails/issues/75
We are seeing performance issue for our daily email jobs
By using NewRelic custom instrumentation,
we found out that most time is spent in calling Roadies
Screenshot of our NewRelic data for an example worker:
The integration code:
# frozen_string_literal: true
require "rails"
require "action_controller"
require "contracts"
require "memoist"
require "roadie"
require "roadie-rails"
require "new_relic/agent/method_tracer"
module Shared::MailerMixins
module WithRoadieIntegration
# I don't want to include the constants into the class as well
module Concern
def self.included(base)
base.extend ClassMethods
end
include ::NewRelic::Agent::MethodTracer
def mail(*args, &block)
super.tap do |m|
options = roadie_options
next unless options
trace_execution_scoped(
[
[
"WithRoadieIntegration",
"Roadie::Rails::MailInliner.new(m, options).execute",
].join("/"),
],
) do
Roadie::Rails::MailInliner.new(m, options).execute
end
end
end
private
def roadie_options
::Rails.application.config.roadie.tap do |options|
options.asset_providers = [UserAssetsProvider.new]
options.external_asset_providers = [UserAssetsProvider.new]
options.keep_uninlinable_css = false
options.url_options = url_options.slice(*[
:host,
:port,
:path,
:protocol,
:scheme,
])
end
end
add_method_tracer(
:roadie_options,
"WithRoadieIntegration/roadie_options",
)
end
class UserAssetsProvider
extend(
::Memoist,
)
include(
::Contracts::Core,
::Contracts::Builtin,
)
include ::NewRelic::Agent::MethodTracer
ABSOLUTE_ASSET_PATH_REGEXP = /\A#{Regexp.escape("//")}.+#{Regexp.escape("/assets/")}/i
Contract String => Maybe[Roadie::Stylesheet]
def find_stylesheet(name)
return nil unless file_exists?(name)
Roadie::Stylesheet.new("whatever", stylesheet_content(name))
end
add_method_tracer(
:find_stylesheet,
"UserAssetsProvider/find_stylesheet",
)
Contract String => Roadie::Stylesheet
def find_stylesheet!(name)
stylesheet = find_stylesheet(name)
if stylesheet.nil?
raise Roadie::CssNotFound.new(
name,
"does not exists",
self,
)
end
stylesheet
end
add_method_tracer(
:find_stylesheet!,
"UserAssetsProvider/find_stylesheet!",
)
private
def file_exists?(name)
if assets_precompiled?
File.exists?(local_file_path(name))
else
sprockets_asset(name)
end
end
memoize :file_exists?
# If on-the-fly asset compilation is disabled, we must be precompiling assets.
def assets_precompiled?
!Rails.configuration.assets.compile
rescue
false
end
def local_file_path(name)
asset_path = asset_path(name)
if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "assets/")
end
File.join(Rails.public_path, asset_path)
end
memoize :local_file_path
add_method_tracer(
:local_file_path,
"UserAssetsProvider/local_file_path",
)
def sprockets_asset(name)
asset_path = asset_path(name)
if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "")
end
# Strange thing is since rails 4.2
# name is passed in like
# `/assets/mailer-a9c96bd713d0b091297b82053ccd9155b933c00a53595812d755825d1747f42d.css`
# Before any processing
# And since `sprockets_asset` is used for preview
# We just "fix" the name by removing the
#
# Regexp taken from gem `asset_sync`
# https://github.com/AssetSync/asset_sync/blob/v1.2.1/lib/asset_sync/storage.rb#L142
#
# Modified to match what we need here (we need `.css` suffix)
if asset_path =~ /-[0-9a-fA-F]{32,}\.css$/
asset_path.gsub!(/-[0-9a-fA-F]{32,}\.css$/, ".css")
end
Rails.application.assets.find_asset(asset_path)
end
add_method_tracer(
:sprockets_asset,
"UserAssetsProvider/sprockets_asset",
)
def asset_path(name)
name.gsub(%r{^[/]?assets/}, "")
end
Contract String => String
def stylesheet_content(name)
if assets_precompiled?
File.read(local_file_path(name))
else
# This will compile and return the asset
sprockets_asset(name).to_s
end.strip
end
memoize :stylesheet_content
add_method_tracer(
:stylesheet_content,
"UserAssetsProvider/stylesheet_content",
)
end
end
end
I would like to report my own findings
With NewRelic data, we think most of the time is spent on
Roadies::Inliner/selector_elements => Roadie::Inliner/elements_matching_selector
And it seems a stylesheet with more style rules will make the style inlining takes longer
Benchmark code will be something like:
# frozen_string_literal: true
require "benchmark/ips"
class TestMailer < ::ActionMailer::Base
def show(benchmark_file_path:)
return mail(
from: "somewhere#test.com",
to: ["somewhere#test.com"],
subject: "some subject",
# This is trying to workaround a strange bug in `mail` gem
# https://github.com/mikel/mail/issues/912#issuecomment-156186383
content_type: "text/html",
) do |format|
format.html do
render(
file: benchmark_file_path,
layout: false,
)
end
end
end
end
Benchmark.ips do |x|
x.warmup = 5
x.time = 60
options = Roadie::Rails::Options.new(
# Use your own provider or use built-in providers
# I use a custom provider which can be used inside a rails app,
# See https://github.com/Mange/roadie for built-in providers
#
# options.asset_providers = [UserAssetsProvider.new]
# options.external_asset_providers = [UserAssetsProvider.new]
options.keep_uninlinable_css = false
)
# Need to prepare html_file yourself with
# different stylesheet tag pointing to two different stylesheet files
x.report("fat") do
message = ::TestMailer.
show(
benchmark_file_path: "benchmark-fat-stylesheet.html",
).message.tap do |m|
Roadie::Rails::MailInliner.new(m, options).execute
end
if message.body.to_s =~ /stylesheet/
raise "stylesheet not processed"
end
end
x.report("slim") do
message = ::TestMailer.
show(
benchmark_file_path: "benchmark-slim-stylesheet.html",
).message
if message.body.to_s =~ /stylesheet/
raise "stylesheet not processed"
end
end
# Compare the iterations per second of the various reports!
x.compare!
end

JRuby Oracle connection failing

I am following a tutorial to establish ojdbc connection in JRuby so that I can execute some SQL statements. But it is failing to connect to the database. Below are the steps:
Copied ojdbc6.jar under working directory where the ruby files reside.
Created oracle_connection.rb file
Create test_connection.rb file as the driver class
oracle_connection.rb
require 'java'
require 'ojdbc6.jar'
java_import 'oracle.jdbc.OracleDriver'
java_import 'java.sql.DriverManager'
class OracleConnection
#conn = nil
#user = nil
#pwd = nil
def initialize(user, pwd, url)
#user = user
#pwd = pwd
#url = url
#Load driver class
ora_driver = OracleDriver.new
DriverManager.registerDriver ora_driver
#conn = DriverManager.get_connection url, user, pwd
#conn.auto_commit = false
end
#Add getters and setters for all attributes we wish to expose
attr_reader :user, :pwd, :url, :connection
def close_connection()
#conn.close() unless #conn
end
def prepare_call(call)
#conn.prepare_call call
end
def create_statement()
#conn.create_statement
end
def prepare_statement(sql)
#conn.prepare_statement sql
end
def commit()
#conn.commit
end
def to_s
"OracleConnection [user=#{#user}, url=#{#url}]"
end
alias_method :to_string, :to_s
end
#test_connection.rb
require 'oracle_connection'
#Edit these for your database schema
user = "ABC"
pwd = "EFG"
url = "jdbc:oracle:thin:#host_name:1520/db_instance"
print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"
begin
conn = OracleConnection.new.create(user, pwd, url)
puts conn, "\n"
end
print "\nEnded at #{Time.now}\n"
While running test_connection.rb, I see the below error:
ruby test_connection.rb
Run at 2013-09-16 10:11:05 -0700 using JRuby 1.9.2
NoMethodError: undefined method `create' for OracleConnection:Class
(root) at test_connection.rb:11
I don't know what is causing the problem. Guidance on this is really appreciated. Thanks!
In "test_connection.rb" I was calling "create" method whereas in OracleConnection class "create" method is not defined. Hence it was failing.
Replacing conn = OracleConnection.new.create(user, pwd, url) with conn = OracleConnection.new(user, pwd, url) fixes the issue.
Below I am re-writing the working test_connection.rb
#test_connection.rb
require 'oracle_connection'
#Edit these for your database schema
user = "ABC"
pwd = "EFG"
url = "jdbc:oracle:thin:#host_name:1520/db_instance"
print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"
begin
conn = OracleConnection.new(user, pwd, url)
puts conn, "\n"
end
print "\nEnded at #{Time.now}\n"

Monkey Patch Guard Cucumber Notification Formatter not working

I want to make a simple change to the Guard Cucumber Notification Formatter to pass a priority, a bit like Guard Rspec does, so that growl styling can be improved. Small thing really.
I have tried this as a monkey patch in an initializer file but it won't work. I've tried all kinds of things but for whatever reason I cannot get it to recognize my monkey-patch when running the tests. No change I make in the patch seems to make a difference. I've tried all kinds of variants on the namespacing in case I'm making an error there - and I think that's most likely. Here's what I'm trying to apply:
initializers/guard_cucumber_patch.rb
require 'guard'
require 'guard/notifier'
require 'cucumber/formatter/console'
require 'cucumber/formatter/io'
module Guard
class Cucumber
class NotificationFormatter
def step_name(keyword, step_match, status, source_indent, background, file_colon_line)
if [:failed, :pending, :undefined].index(status)
#rerun = true
step_name = step_match.format_args(lambda { |param| "*#{ param }*" })
::Guard::Notifier.notify(step_name,
:title => #feature_name,
:image => icon_for(status),
:priority => priority(icon_for(status)))
end
end
# Just stolen from the guard/rspec/formatter code
def priority(image)
{ :failed => 2,
:pending => -1,
:success => -2
}[image]
end
end
end
end
The original guard/cucumber/notification_formatter.rb file is as follows:
require 'guard'
require 'guard/notifier'
require 'cucumber/formatter/console'
require 'cucumber/formatter/io'
module Guard
class Cucumber
# The notification formatter is a Cucumber formatter that Guard::Cucumber
# passes to the Cucumber binary. It writes the `rerun.txt` file with the failed features
# an creates system notifications.
#
# #see https://github.com/cucumber/cucumber/wiki/Custom-Formatters
#
class NotificationFormatter
include ::Cucumber::Formatter::Console
attr_reader :step_mother
# Initialize the formatter.
#
# #param [Cucumber::Runtime] step_mother the step mother
# #param [String, IO] path_or_io the path or IO to the feature file
# #param [Hash] options the options
#
def initialize(step_mother, path_or_io, options)
#options = options
#file_names = []
#step_mother = step_mother
end
# Notification after all features have completed.
#
# #param [Array[Cucumber::Ast::Feature]] features the ran features
#
def after_features(features)
notify_summary
write_rerun_features if !#file_names.empty?
end
# Before a feature gets run.
#
# #param [Cucumber::Ast::FeatureElement] feature_element
#
def before_feature_element(feature_element)
#rerun = false
#feature_name = feature_element.name
end
# After a feature gets run.
#
# #param [Cucumber::Ast::FeatureElement] feature_element
#
def after_feature_element(feature_element)
if #rerun
#file_names << feature_element.file_colon_line
#rerun = false
end
end
# Gets called when a step is done.
#
# #param [String] keyword the keyword
# #param [Cucumber::StepMatch] step_match the step match
# #param [Symbol] status the status of the step
# #param [Integer] source_indent the source indentation
# #param [Cucumber::Ast::Background] background the feature background
# #param [String] file name and line number describing where the step is used
#
def step_name(keyword, step_match, status, source_indent, background, file_colon_line)
if [:failed, :pending, :undefined].index(status)
#rerun = true
step_name = step_match.format_args(lambda { |param| "*#{ param }*" })
::Guard::Notifier.notify step_name, :title => #feature_name, :image => icon_for(status)
end
end
private
# Notify the user with a system notification about the
# result of the feature tests.
#
def notify_summary
icon, messages = nil, []
[:failed, :skipped, :undefined, :pending, :passed].reverse.each do |status|
if step_mother.steps(status).any?
step_icon = icon_for(status)
icon = step_icon if step_icon
messages << dump_count(step_mother.steps(status).length, 'step', status.to_s)
end
end
::Guard::Notifier.notify messages.reverse.join(', '), :title => 'Cucumber Results', :image => icon
end
# Writes the `rerun.txt` file containing all failed features.
#
def write_rerun_features
File.open('rerun.txt', 'w') do |f|
f.puts #file_names.join(' ')
end
end
# Gives the icon name to use for the status.
#
# #param [Symbol] status the cucumber status
# #return [Symbol] the Guard notification symbol
#
def icon_for(status)
case status
when :passed
:success
when :pending, :undefined, :skipped
:pending
when :failed
:failed
else
nil
end
end
end
end
end
EDIT: I am using jruby-head if that makes a difference to monkey business.
Guard::Cucumber makes a system call to start Cucumber in a subshell and your monkey patch is not loaded in that environment. You need to tell Cucumber to require your patch on start like the notification formatter is required.
I'm not actively developing Guard::Cucumber at the moment because I have no project with Cucumber, but I still do maintain it and I'll happily merge that improvement if you make a pull request. I think your improvement would be useful for other users as well.
try to put this file in spec/support dir (create if not exists)
this dir contents are usually included in spec/spec_helper.rb just before running any tests

Storing image using open URI and paperclip having size less than 10kb

I want to import some icons from my old site. The size of those icons is less than 10kb. So when I am trying to import the icons its returning stringio.txt file.
require "open-uri"
class Category < ActiveRecord::Base
has_attached_file :icon, :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension"
def icon_from_url(url)
self.icon = open(url)
end
end
In rake task.
category = Category.new
category.icon_from_url "https://xyz.com/images/dog.png"
category.save
Try:
def icon_from_url(url)
extname = File.extname(url)
basename = File.basename(url, extname)
file = Tempfile.new([basename, extname])
file.binmode
open(URI.parse(url)) do |data|
file.write data.read
end
file.rewind
self.icon = file
end
To override the default filename of a "fake file upload" in Paperclip (stringio.txt on small files or an almost random temporary name on larger files) you have 2 main possibilities:
Define an original_filename on the IO:
def icon_from_url(url)
io = open(url)
io.original_filename = "foo.png"
self.icon = io
end
You can also get the filename from the URI:
io.original_filename = File.basename(URI.parse(url).path)
Or replace :basename in your :path:
has_attached_file :icon, :path => ":rails_root/public/:attachment/:id/:style/foo.png", :url => "/:attachment/:id/:style/foo.png"
Remember to alway change the :url when you change the :path, otherwise the icon.url method will be wrong.
You can also define you own custom interpolations (e.g. :rails_root/public/:whatever).
You are almost there I think, try opening parsed uri, not the string.
require "open-uri"
class Category < ActiveRecord::Base
has_attached_file :icon, :path =>:rails_root/public/:attachment/:id/:style/:basename.:extension"
def icon_from_url(url)
self.icon = open(URI.parse(url))
end
end
Of course this doesn't handle errors
You can also disable OpenURI from ever creating a StringIO object, and force it to create a temp file instead. See this SO answer:
Why does Ruby open-uri's open return a StringIO in my unit test, but a FileIO in my controller?
In the past, I found the most reliable way to retrieve remote files was by using the command line tool "wget". The following code is mostly copied straight from an existing production (Rails 2.x) app with a few tweaks to fit with your code examples:
class CategoryIconImporter
def self.download_to_tempfile (url)
system(wget_download_command_for(url))
##tempfile.path
end
def self.clear_tempfile
##tempfile.delete if ##tempfile && ##tempfile.path && File.exist?(##tempfile.path)
##tempfile = nil
end
def self.set_wget
# used for retrieval in NrlImage (and in future from other sies?)
if !##wget
stdin, stdout, stderr = Open3.popen3('which wget')
##wget = stdout.gets
##wget ||= '/usr/local/bin/wget'
##wget.strip!
end
end
def self.wget_download_command_for (url)
set_wget
##tempfile = Tempfile.new url.sub(/\?.+$/, '').split(/[\/\\]/).last
command = [ ##wget ]
command << '-q'
if url =~ /^https/
command << '--secure-protocol=auto'
command << '--no-check-certificate'
end
command << '-O'
command << ##tempfile.path
command << url
command.join(' ')
end
def self.import_from_url (category_params, url)
clear_tempfile
filename = url.sub(/\?.+$/, '').split(/[\/\\]/).last
found = MIME::Types.type_for(filename)
content_type = !found.empty? ? found.first.content_type : nil
download_to_tempfile url
nicer_path = RAILS_ROOT + '/tmp/' + filename
File.copy ##tempfile.path, nicer_path
Category.create(category_params.merge({:icon => ActionController::TestUploadedFile.new(nicer_path, content_type, true)}))
end
end
The rake task logic might look like:
[
['Cat', 'cat'],
['Dog', 'dog'],
].each do |name, icon|
CategoryIconImporter.import_from_url {:name => name}, "https://xyz.com/images/#{icon}.png"
end
This uses the mime-types gem for content type discovery:
gem 'mime-types', :require => 'mime/types'

Resources