code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def modified_body body = @original_response.body index = body.rindex(%r{</body>}i) || body.rindex(%r{</html>}i) if index body.dup.insert(index, badge_content) else body end end
Modify the body of the original response @return String The modified body
modified_body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def badge_content html = File.read(File.expand_path('../../app/views/rails_mini_profiler/badge.html.erb', __dir__)) @position = css_position template = ERB.new(html) template.result(binding) end
Render the badge template @return String The badge HTML content to be injected
badge_content
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def css_position case @configuration.ui.badge_position when 'top-right' 'top: 5px; right: 5px;' when 'bottom-left' 'bottom: 5px; left: 5px;' when 'bottom-right' 'bottom: 5px; right: 5px;' else 'top: 5px; left: 5px;' end end
Transform the configuration position into CSS style positions @return String The badge position as CSS style
css_position
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def reset @enabled = proc { |_env| Rails.env.development? || Rails.env.test? } @flamegraph_enabled = true @flamegraph_sample_rate = 0.5 @logger = RailsMiniProfiler::Logger.new(Rails.logger) @skip_paths = [] @storage = Storage.new @tracers = %i[controller instantiation sequel view rmp] @ui = UserInterface.new @user_provider = proc { |env| Rack::Request.new(env).ip } end
Reset the configuration to default values
reset
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration.rb
MIT
def initialize(request_context, configuration: RailsMiniProfiler.configuration) @request_context = request_context @request = request_context.request @configuration = configuration end
@param request_context [RequestContext] the current request context @param configuration [Configuration] the current configuration
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def profile? return false unless enabled? return false if ignored_path? true end
Whether or not to profile Profiling is disabled the profiler has been flat out disabled in the configuration or if the current request path matches on of the ignored paths. @return [Boolean] false if no profiling should be done
profile?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def ignored_path? return true if /#{Engine.routes.url_helpers.root_path}/.match?(@request.path) return true if asset_path? return true if actioncable_request? ignored_paths = @configuration.skip_paths return true if ignored_paths.any? && Regexp.union(ignored_paths).match?(@request.path) false end
Is the path of the current request an ignored one? @return [Boolean] true if the path is ignored. Per default, paths going to the engine itself are ignored, as are asset requests, and the paths the user has configured.
ignored_path?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def engine_path? # Try the Rails 8+ approach first engine_script_name = Engine.routes.find_script_name({}) return true if engine_script_name.present? && /#{Regexp.escape(engine_script_name)}/.match?(@request.path) # Fallback: check if path starts with any known engine mount points # This is a common pattern where engines are mounted at /rails_mini_profiler return true if @request.path.start_with?('/rails_mini_profiler') false end
Is the current request to the engine itself? @return [Boolean] if the request path matches the engine mount path
engine_path?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def actioncable_request? return false unless defined?(ActionCable) /#{ActionCable.server.config.mount_path}/.match?(@request.path) end
Is the current request an actioncable ping @return [Boolean] if the request path matches the mount path of actioncable
actioncable_request?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def enabled? enabled = @configuration.enabled return enabled unless enabled.respond_to?(:call) enabled.call(@request.env) end
Is the profiler enabled? Takes into account the current request env to decide if the profiler is enabled. @return [Boolean] false if the profiler is disabled
enabled?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/guard.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/guard.rb
MIT
def initialize(request_context) @request = request_context.request @profiled_request = request_context.profiled_request end
@param request_context [RequestContext] the current request context
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/redirect.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb
MIT
def render params = CGI.parse(@request.query_string).transform_values(&:first).with_indifferent_access if params[:rmp_flamegraph].present? return redirect_to(RailsMiniProfiler::Engine.routes.url_helpers.flamegraph_path(@profiled_request.id)) end false end
Renders a redirect to a specific resource under certain conditions When the user requests a Flamegraph using a parameter for a specific request, they are being served a redirect. @return [Boolean] false if no redirect happens @return [Array] response with status 302 and the new location to redirect to
render
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/redirect.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/redirect.rb
MIT
def initialize(request) @request = request @env = request.env @saved = false @complete = false end
Create a new request context @param request [RequestWrapper] the request as sent to the application
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def authorized? @authorized ||= User.get(@env).present? end
If a user is currently authorized @return [Boolean] true if the user is authorized
authorized?
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def save_results! ActiveRecord::Base.transaction do profiled_request = build_profiled_request profiled_request.flamegraph = RailsMiniProfiler::Flamegraph.new(data: flamegraph) if flamegraph.present? profiled_request.save insert_traces(profiled_request) unless traces.empty? @profiled_request = profiled_request end @saved = true end
Save profiling data in the database. This will store the profiled request, as well as any attached traces and Flamgraph.
save_results!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def insert_traces(profiled_request) return if traces.empty? timestamp = Time.zone.now inserts = traces.reverse.map do |trace| { rmp_profiled_request_id: profiled_request.id, created_at: timestamp, updated_at: timestamp, **trace.to_h.symbolize_keys # Symbolize keys needed for Ruby 2.6 } end RailsMiniProfiler::Trace.insert_all(inserts) end
We insert multiple at once for performance reasons.
insert_traces
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_context.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_context.rb
MIT
def body input = super return '' unless input # Store current position current_pos = input.pos if input.respond_to?(:pos) # Rewind to beginning to read full content input.rewind if input.respond_to?(:rewind) body_content = input.read # Restore position if current_pos && input.respond_to?(:seek) input.seek(current_pos) elsif input.respond_to?(:rewind) input.rewind end body_content || '' rescue StandardError => e # If we can't read the body, return empty string RailsMiniProfiler.logger.debug("Failed to read request body: #{e.message}") '' end
Convenience method to read the request body as String @return [String] the request body
body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb
MIT
def headers env.select { |k, _v| k.start_with? 'HTTP_' } || {} end
The request headers @return [Hash] the request headers
headers
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/request_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/request_wrapper.rb
MIT
def body body = super case body when String body when Array body.join when ActionDispatch::Response::RackBody body.body else '' end end
Return the response body as String Depending on preceding middleware, response bodies may be Strings, Arrays or literally anything else. This method converts whatever it is to a string so we can store it later. @return [String] of the response body
body
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/response_wrapper.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/response_wrapper.rb
MIT
def configuration @configuration ||= new end
Construct a new configuration instance @return [Storage] a new storage configuration
configuration
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def configure yield(configuration) configuration end
Configure how profiling data is stored @yieldreturn [Storage] a new storage configuration object
configure
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def defaults! @database = nil @profiled_requests_table = 'rmp_profiled_requests' @flamegraphs_table = 'rmp_flamegraphs' @traces_table = 'rmp_traces' end
Reset the configuration to default values
defaults!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/storage.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/storage.rb
MIT
def configuration @configuration ||= new end
Construct a new UI configuration instance @return [UserInterface] a new storage configuration
configuration
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def configure yield(configuration) configuration end
Configure how profiling data is shown to the user @yieldreturn [UserInterface] a new UI configuration object
configure
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def defaults! @badge_enabled = true @badge_position = 'top-left' # We must not set base controller when the app loads, aka during autoload time, as we are loading # constants. Rather, we only load the base controller constants when any engine controllers are first initialized # and call #base_controller @base_controller = nil @page_size = 25 end
Reset the configuration to default values
defaults!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/configuration/user_interface.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/configuration/user_interface.rb
MIT
def tracers @tracers ||= tracer_map .values .each_with_object({}) do |tracer, obj| subscriptions = wrap(tracer.subscribes_to) subscriptions.each { |subscription| obj[subscription] = tracer } end end
Tracers that are available in the application, indexed by events they subscribe to. @return [Hash] a hash where keys are event names and values are the corresponding tracers
tracers
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/registry.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb
MIT
def presenters @presenters ||= tracer_map .values .each_with_object({}) do |tracer, obj| presenters = tracer.presents if presenters.is_a?(Hash) obj.merge!(presenters) else obj[tracer.subscribes_to] = presenters end end end
Presenters that are available in the application, indexed by events they should present. @return [Hash] a hash where keys are event names and values are the corresponding presenters
presenters
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/registry.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/registry.rb
MIT
def setup!(subscriptions, &) subscriptions.each do |event| subscribe(event, &) end end
Subscribe to each individual active support event using a callback.
setup!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/subscriptions.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/subscriptions.rb
MIT
def create(event) tracer = @tracers[event.name] || Tracer tracer.build_from(event) end
Create a new trace from an event @param event [ActiveSupport::Notifications::Event] an event from the application @return [Trace] a processed trace
create
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/tracers/trace_factory.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/tracers/trace_factory.rb
MIT
def set_movie @movie = Movie.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_movie
ruby
hschne/rails-mini-profiler
spec/dummy/app/controllers/movies_controller.rb
https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb
MIT
def movie_params params.require(:movie).permit(:title, :imdb_id, :popularity, :budget, :revenue, :runtime, :release_date) end
Only allow a list of trusted parameters through.
movie_params
ruby
hschne/rails-mini-profiler
spec/dummy/app/controllers/movies_controller.rb
https://github.com/hschne/rails-mini-profiler/blob/master/spec/dummy/app/controllers/movies_controller.rb
MIT
def create_pluralized_getter(key) define_singleton_method(BOOKWORM_KEYS[key]['plural'].to_sym) do self[key] end end
This creates a method based off the (pluralized) Bookworm key. Syntactical sugar that can make some rules/reports easier to read.
create_pluralized_getter
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
Apache-2.0
def init_key_with_cookbook_name(key, files) self[key] = {} self['cookbook'] ||= {} path_name_regex = BOOKWORM_KEYS[key]['path_name_regex'] files.each do |path, ast| m = path.match(%r{/?([\w-]+)/#{path_name_regex}}) cookbook_name = m[1] file_name = m[2] self['cookbook'][cookbook_name] ||= {} self[key]["#{cookbook_name}::#{file_name}"] = { 'path' => path, 'cookbook' => cookbook_name, 'ast' => ast } end end
The difference between this method and init_key is that it: 1. initializes cookbook metakey if it doesn't already exist 2. instead of using the filename for file key, uses COOKBOOK::FILENAME where FILENAME has the '.rb' suffix stripped (making it similar to the include_recipe calling conventions in Chef
init_key_with_cookbook_name
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/knowledge_base.rb
Apache-2.0
def determine_cookbooks_with_dynamic_recipe_inclusion @kb.recipes.select do |_, m| if m['IncludeRecipeDynamic'] @kb.cookbooks[m['cookbook']]['dynamic_recipe_inclusion'] = true end end end
Cookbooks with dynamic recipe inclusion can't be safely shaken :-(
determine_cookbooks_with_dynamic_recipe_inclusion
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/reports/CookbookDepShaker.rb
Apache-2.0
def output @metadata['ast'] == Bookworm::Crawler::EMPTY_RUBOCOP_AST end
See note in crawler.rb about EMPTY_RUBOCOP_AST constant
output
ruby
facebook/chef-cookbooks
cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_bookworm/files/default/bookworm/lib/bookworm/rules/NoParsedRuby.rb
Apache-2.0
def serialize_config final_conf = [] config.each do |key, val| if val.respond_to?(:call) final_conf << Config.new(key, val.call) elsif val.is_a?(Array) final_conf += val.map { |v| Config.new(key, v) } # Hashes can have some inner nesting, but only to a certain point. elsif val.is_a?(Hash) val.each do |k, v| if v.is_a?(Array) final_conf += v.map { |e| Config.new(key, "#{k}=#{e}") } else final_conf << Config.new(key, "#{k}=#{v}") end end else final_conf << Config.new(key, val) end end final_conf end
Fluentbit's config is a little odd. It mostly seems to be key/value based, with the following caveats * Keys can repeat (which seems to OR all the values) * Values can sometimes be key/value based. In order to support these two, the following API decisions were made: * Multiple keys are supported by setting cookbook API values to lists. We then replicate each key/value pair, one per value in the list. * Values that are key/values pairs are separated by = and replicated like the above. * Values can be callable by passing in 'procs' (similar to other cookbooks). See spec tests for examples of what this looks like.
serialize_config
ruby
facebook/chef-cookbooks
cookbooks/fb_fluentbit/libraries/helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fluentbit/libraries/helpers.rb
Apache-2.0
def should_keep(mounted_data, desired_mounts, base_mounts) Chef::Log.debug( "fb_fstab: Should we keep #{mounted_data}?", ) # Does it look like something in desired mounts? desired_mounts.each_value do |desired_data| begin desired_device = canonicalize_device(desired_data['device']) rescue RuntimeError next if desired_data['allow_mount_failure'] raise end Chef::Log.debug("fb_fstab: --> Lets see if it matches #{desired_data}") # if the devices are the same *and* are real devices, the # rest doesn't matter - we won't unmount a moved device. moves # option changes, etc. are all the work of the 'mount' step later. if mounted_data['device']&.start_with?('/dev/') if desired_device == mounted_data['device'] Chef::Log.debug( "fb_fstab: Device #{mounted_data['device']} is supposed to be " + ' mounted, not considering for unmount', ) return true end # If it's a virtual device, we just check the type and mount # point are the same elsif desired_data['mount_point'] == mounted_data['mount'] && compare_fstype(desired_data['type'], mounted_data['fs_type']) Chef::Log.debug( "fb_fstab: Virtual fs of type #{mounted_data['fs_type']} is " + "desired at #{mounted_data['mount']}, not considering for unmount", ) return true end Chef::Log.debug('fb_fstab: --> ... nope') end # If not, is it autofs controlled? if FB::Fstab.autofs_parent(mounted_data['mount'], node) Chef::Log.debug( "fb_fstab: #{mounted_data['device']} (#{mounted_data['mount']}) is" + ' autofs-controlled.', ) return true end # If not, is it a base mount? # Note that if it's not in desired mounts, we can be more strict, # no one is trying to move things... it should be same device and point. Chef::Log.debug('fb_fstab: --> OK, well is it a base mount?') if base_mounts[mounted_data['device']] && base_mounts[mounted_data['device']]['mount_point'] == mounted_data['mount'] Chef::Log.debug( "fb_fstab: #{mounted_data['device']} on #{mounted_data['mount']} is" + ' a base mount, not considering for unmount', ) return true end false end
Given a *mounted* device from node['filesystem'] in `mounted_data`, check to see if we want to keep it. It looks in `desired_mounts` (an export of node['fb_fstab']['mounts'] as well as `base_mounts` (a hash representation of the saved OS mounts file).
should_keep
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def check_unwanted_filesystems # extra things to skip devs_to_skip = node['fb_fstab']['umount_ignores']['devices'].dup dev_prefixes_to_skip = node['fb_fstab']['umount_ignores']['device_prefixes'].dup mounts_to_skip = node['fb_fstab']['umount_ignores']['mount_points'].dup mount_prefixes_to_skip = node['fb_fstab']['umount_ignores']['mount_point_prefixes'].dup mount_regexes_to_skip = node['fb_fstab']['umount_ignores']['mount_point_regexes'].dup fstypes_to_skip = node['fb_fstab']['umount_ignores']['types'].dup base_mounts = get_unmasked_base_mounts(:hash) # we're going to iterate over specified mounts a lot, lets dump it desired_mounts = node['fb_fstab']['mounts'].to_hash fs_data = node.filesystem_data fs_data['by_pair'].to_hash.each_value do |mounted_data| # ohai uses many things to populate this structure, one of which # is 'blkid' which gives info on devices that are not currently # mounted. This skips those, plus swap, of course. unless mounted_data['mount'] Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "- it isn't mounted.", ) next end # Work around chef 12 ohai bug if mounted_data.key?('inodes_used') && !mounted_data.key?('kb_used') Chef::Log.debug( 'fb_fstab: Skipping mal-formed Chef 12 "df -i" entry ' + mounted_data.to_s, ) next end # skip anything seemingly magical if devs_to_skip.include?(mounted_data['device']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted device", ) next elsif mounts_to_skip.include?(mounted_data['mount']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted mountpoint", ) next elsif fstypes_to_skip.include?(mounted_data['fs_type']) Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}): exempted fstype", ) next elsif dev_prefixes_to_skip.any? do |i| mounted_data['device']&.start_with?(i) end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted device prefix", ) next elsif mount_prefixes_to_skip.any? do |i| mounted_data['mount']&.start_with?(i) end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted mount_point prefix", ) next elsif mount_regexes_to_skip.any? do |i| mounted_data['mount'] =~ /#{i}/ end Chef::Log.debug( "fb_fstab: Skipping umount check for #{mounted_data['device']} " + "(#{mounted_data['mount']}) - exempted mount_point regex", ) next end # Is this device in our list of desired mounts? next if should_keep(mounted_data, desired_mounts, base_mounts) if node['fb_fstab']['enable_unmount'] converge_by "unmount #{mounted_data['mount']}" do umount(mounted_data['mount'], mounted_data['lock_file'], node['fb_fstab']['umount_delete_empty_mountdir']) end else Chef::Log.warn( "fb_fstab: Would umount #{mounted_data['device']} from " + "#{mounted_data['mount']}, but " + 'node["fb_fstab"]["enable_unmount"] is false', ) Chef::Log.debug("fb_fstab: #{mounted_data}") end end end
Walk all mounted filesystems and umount anything we don't know about
check_unwanted_filesystems
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def compare_fstype(type1, type2) type1 == type2 || _normalize_type(type1) == _normalize_type(type2) end
We consider a filesystem type the "same" if they are identical or if one is auto.
compare_fstype
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def translate_size_opt(opt) val = opt.split('=').last mag = val[-1].downcase mags = ['k', 'm', 'g', 't'] return opt unless mags.include?(mag) num = val[0..-2].to_i mags.each do |d| num *= 1024 return "size=#{num}" if mag == d end fail RangeError "fb_fstab: Failed to translate #{opt}" end
This translates human-readable size mount options into their canonical bytes form. I.e. "size=4G" into "size=4194304" Assumes it's really a size opt - validate before calling!
translate_size_opt
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def compare_opts(opts1, opts2, skipped_opts = []) c1 = canonicalize_opts(opts1, skipped_opts) c2 = canonicalize_opts(opts2, skipped_opts) # Check that they're the same c1 == c2 end
Take opts in a variety of forms, and compare them intelligently
compare_opts
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def _are_tmpfs_using_inode64? return node.linux? && (FB::Version.new(node['kernel']['release']) > FB::Version.new('5.9')) end
on Kernel >= 5.9, tmpfs are mounted with inode64 opt active
_are_tmpfs_using_inode64?
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def tmpfs_mount_status(desired) # Start with checking if it was mounted the way we would mount it # this is ALMOST the same as the 'is it identical' check for non-tmpfs # filesystems except that with tmpfs we don't treat 'auto' as equivalent and # that we skip inode64 option on current mount status - because it's activated # by default on Linux kernel >= 5.9 fs_data = node.filesystem_data key = "#{desired['device']},#{desired['mount_point']}" if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash if mounted['fs_type'] == 'tmpfs' Chef::Log.debug( "fb_fstab: tmpfs #{desired['device']} on " + "#{desired['mount_point']} is currently mounted...", ) skipped_opts = [] if _are_tmpfs_using_inode64? # inode64 is active by default on tmpfs for Linux kernel > 5.9 skipped_opts.push('inode64') end if compare_opts(desired['opts'], mounted['mount_options'], skipped_opts) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end end end # OK, if that's not the case, we don't have the same device, which # is OK. Find out if we have something mounted at the same spot, and # get its device name so we can find it's entry in node['filesystem'] if fs_data['by_mountpoint'][desired['mount_point']] # If we are here the mountpoints are the same... mounted = fs_data['by_mountpoint'][desired['mount_point']].to_hash # OK, if it's tmpfs as well, we're diong good if mounted['fs_type'] == 'tmpfs' Chef::Log.warn( "fb_fstab: Treating #{mounted['devices']} on " + "#{desired['mount_point']} the same as #{desired['device']} on " + "#{desired['mount_point']} because they are both tmpfs.", ) Chef::Log.debug( "fb_fstab: tmpfs #{desired['device']} on " + "#{desired['mount_point']} is currently mounted...", ) Chef::Log.debug("fb_fstab: #{desired} vs #{mounted}") if compare_opts(desired['opts'], mounted['mount_options']) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end end Chef::Log.warn( "fb_fstab: tmpfs is desired on #{desired['mount_point']}, but " + "non-tmpfs #{mounted['devices']} (#{mounted['fs_type']}) currently " + 'mounted there.', ) return :conflict end :missing end
Given a tmpfs desired mount `desired` check to see what it's status is; mounted (:same), needs remount (:remount), not mounted (:missing) or something else is mounted in the way (:conflict) This is roughly the same as mount_status() below but we make many exceptions for tmpfs filesystems. Unlike mount_status() we will never return :moved since there's no unique device to move.
tmpfs_mount_status
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def mount_status(desired) # We treat tmpfs specially. While we don't want people to mount tmpfs with # a device of 'none' or 'tmpfs', we also don't want to make them remount # (and lose all their data) just to convert to fb_fstab. So we'll make # them use a new name in the config, but we will treat the pre-mounted # mounts as valid/the same. Besides, since the device is meaningless, we # can just ignore it for the purposes of this test anyway. if desired['type'] == 'tmpfs' return tmpfs_mount_status(desired) end key = "#{desired['device']},#{desired['mount_point']}" fs_data = node.filesystem_data mounted = nil if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash else key = "#{desired['device']}/,#{desired['mount_point']}" if fs_data['by_pair'][key] mounted = fs_data['by_pair'][key].to_hash end end if mounted Chef::Log.debug( "fb_fstab: There is an entry in node['filesystem'] for #{key}", ) # If it's a virtual device, we require the fs type to be identical. # otherwise, we require them to be similar. This is because 'auto' # is meaningless without a physical device, so we don't want to allow # it to be the same. if compare_fstype(desired['type'], mounted['fs_type']) || (desired['device'].start_with?('/') && [desired['type'], mounted['fs_type']].include?('auto')) Chef::Log.debug( "fb_fstab: FS #{desired['device']} on #{desired['mount_point']}" + ' is currently mounted...', ) if compare_opts(desired['opts'], mounted['mount_options']) Chef::Log.debug('fb_fstab: ... with identical options.') return :same else Chef::Log.debug( "fb_fstab: ... with different options #{desired['opts']} vs " + mounted['mount_options'].join(','), ) Chef::Log.info( "fb_fstab: #{desired['mount_point']} is mounted with options " + "#{canonicalize_opts(mounted['mount_options'])} instead of " + canonicalize_opts(desired['opts']).to_s, ) return :remount end else Chef::Log.warn( "fb_fstab: Device #{desired['device']} is mounted at " + "#{mounted['mount']} as desired, but with fstype " + "#{mounted['fs_type']} instead of #{desired['type']}", ) return :conflict end end # In this case we don't have the device we expect at the mountpoint we # expect. Assuming it's not NFS/Gluster which can be mounted in more than # once place, we look up this device and see if it moved or just isn't # mounted unless ['nfs', 'nfs4', 'glusterfs'].include?(desired['type']) device = fs_data['by_device'][desired['device']] # Here we are checking if the device we want # has already a mount defined # We want to return :moved if it does except # in the case when it's a btrfs # disk and our desired and current options # are trying to mount different subvolumes if device && device['mounts'] && !device['mounts'].empty? && !( FB::Fstab.btrfs_subvol?( device['fs_type'], device['mount_options'].join(','), ) && FB::Fstab.btrfs_subvol?( desired['type'], desired['opts'], ) && !FB::Fstab.same_subvol?( device['mounts'][0], device['mount_options'].join(','), desired['opts'], ) ) Chef::Log.warn( "fb_fstab: #{desired['device']} is at #{device['mounts']}, but" + " we want it at #{desired['mount_point']}", ) return :moved end end # Ok, this device isn't mounted, but before we return we need to check # if anything else is mounted where we want to be. if fs_data['by_mountpoint'][desired['mount_point']] devices = fs_data['by_mountpoint'][ desired['mount_point']]['devices'] Chef::Log.warn( "fb_fstab: Device #{desired['device']} desired at " + "#{desired['mount_point']} but something #{devices} already " + 'mounted there.', ) return :conflict end :missing end
Given a desired mount `desired` check to see what it's status is; mounted (:same), needs remount (:remount), not mounted (:missing), moved (:moved), or something else is mounted in the way (:conflict)
mount_status
ruby
facebook/chef-cookbooks
cookbooks/fb_fstab/libraries/provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_fstab/libraries/provider.rb
Apache-2.0
def initialize(s) @string_form = s if s.nil? @arr = [] return end @arr = s.split(/[._-]/).map(&:to_i) end
This is intentional. rubocop:disable Lint/MissingSuper
initialize
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/fb_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/fb_helpers.rb
Apache-2.0
def el_min_version?(version, full = false) self.rhel_family? && self.os_min_version?(version, full) end
Is this a RHEL-compatible OS with a minimum major version number of `version`
el_min_version?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def el_max_version?(version, full = false) self.rhel_family? && self.os_max_version?(version, full) end
Is this a RHEL-compatible OS with a maximum major version number of `version`
el_max_version?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def windows1903? windows? && self['platform_version'] == '10.0.18362' end
from https://en.wikipedia.org/wiki/Windows_10_version_history
windows1903?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def in_aws_account?(*accts) return false if self.quiescent? return false unless self['ec2'] accts.flatten! accts.include?(self['ec2']['account_id']) end
Takes one or more AWS account IDs as strings and return true if this node is in any of those accounts.
in_aws_account?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_of_mount(m) fs = self.filesystem_data unless Pathname.new(m).mountpoint? Chef::Log.warn( "fb_helpers: #{m} is not a mount point - I can't determine its " + 'device.', ) return nil end unless fs && fs['by_pair'] Chef::Log.warn( 'fb_helpers: no filesystem data so no node.device_of_mount', ) return nil end fs['by_pair'].to_hash.each do |pair, info| # we skip fake filesystems 'rootfs', etc. next unless pair.start_with?('/') # is this our FS? next unless pair.end_with?(",#{m}") # make sure this isn't some fake entry next unless info['kb_size'] return info['device'] end Chef::Log.warn( "fb_helpers: #{m} shows as valid mountpoint, but Ohai can't find it.", ) nil end
Take a string representing a mount point, and return the device it resides on.
device_of_mount
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def fs_value(p, val) key = case val when 'size' 'kb_size' when 'used' 'kb_used' when 'available' 'kb_available' when 'percent' 'percent_used' else fail "fb_helpers: Unknown FS val #{val} for node.fs_value" end fs = self.filesystem_data # Some things like /dev/root and rootfs have same mount point... if fs && fs['by_mountpoint'] && fs['by_mountpoint'][p] && fs['by_mountpoint'][p][key] return fs['by_mountpoint'][p][key].to_f end Chef::Log.warn( "fb_helpers: Tried to get filesystem information for '#{p}', but it " + 'is not a recognized filesystem, or does not have the requested info.', ) nil end
Takes a string corresponding to a filesystem. Returns the size in GB of that filesystem.
fs_value
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def shard_block(threshold, &block) yield block if block_given? && in_shard?(threshold) end
This method allows you to conditionally shard chef resources @param threshold [Fixnum] An integer value that you are sharding up to. @yields The contents of the ruby block if the node is in the shard. @example This will log 'hello' during the chef run for all nodes <= shard 5 node.shard_block(5) do log 'hello' do level :info end end
shard_block
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def device_ssd?(device) unless self['block_device'][device] fail "fb_helpers: Device '#{device}' passed to node.device_ssd? " + "doesn't appear to be a block device!" end self['block_device'][device]['rotational'] == '0' end
is this device a SSD? If it's not rotational, then it's SSD expects a short device name, e.g. 'sda', not '/dev/sda', not '/dev/sda3'
device_ssd?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def rpm_version(name) if (self.centos? && !self.centos7?) || self.fedora? || self.redhat8? || self.oracle8? || self.redhat9? || self.oracle9? || self.aristaeos_4_30_or_newer? # returns epoch.version v = Chef::Provider::Package::Dnf::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end elsif self.centos7? && (FB::Version.new(Chef::VERSION) > FB::Version.new('14')) # returns epoch.version.arch v = Chef::Provider::Package::Yum::PythonHelper.instance. package_query(:whatinstalled, name).version unless v.nil? v.split(':')[1] end else # return version Chef::Provider::Package::Yum::YumCache.instance. installed_version(name) end end
returns the version-release of an rpm installed, or nil if not present
rpm_version
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def attr_lookup(path, delim: '/', default: nil) return default if path.nil? node_path = path.split(delim) # implicit-begin is a function of ruby2.5 and later, but we still # support 2.4, so.... until then node_path.inject(self) do |location, key| if key.respond_to?(:to_s) && location.respond_to?(:attribute?) location.attribute?(key.to_s) ? location[key] : default else default end end end
Safely dig through the node's attributes based on the specified `path`, with the option to provide a default value in the event the key does not exist. @param path [required] [String] A string representing the path to search for the key. @param delim [opt] [String] A character that you will split the path on. @param default [opt] [Object] An object to return if the key is not found. @return [Object] Returns an arbitrary object in the event the key isn't there. @note Returns nil by default @note Returns the default value in the event of an exception @example irb> node.default.awesome = 'yup' => "yup" irb> node.attr_lookup('awesome/not_there') => nil irb> node.attr_lookup('awesome') => "yup" irb> node.override.not_cool = 'but still functional' => "but still functional" irb> node.attr_lookup('not_cool') => "but still functional" irb> node.attr_lookup('default_val', default: 'I get this back anyway') => "I get this back anyway" irb> node.automatic.a.very.deeply.nested.value = ':)' => ":)" irb> node.attr_lookup('a/very/deeply/nested/value') => ":)"
attr_lookup
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def interface_change_allowed?(interface) method = self['fb_helpers']['interface_change_allowed_method'] if method return method.call(self, interface) else return self.nw_changes_allowed? || ['ip6tnl0', 'tunlany0', 'tunl0'].include?(interface) || interface.match(Regexp.new('^tunlany\d+:\d+')) end end
We can change interface configs if nw_changes_allowed? or we are operating on a DSR VIP
interface_change_allowed?
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def files_unowned_by_pkgmgmt(files) # this uses the chef-utils helpers, which we should be moving towards # instead of the fb_helpers helpers. rpm_based is obvious, debian? # is all debian-derived distros unowned_files = [] if rpm_based? s = Mixlib::ShellOut.new(['/bin/rpm', '-qf'] + files).run_command unless s.exitstatus == 0 s.stdout.split("\n").each do |line| m = /file (.*) is not owned by any package/.match(line.strip) next unless m unowned_files << m[1] end end elsif debian? s = Mixlib::ShellOut.new(['dpkg', '-S'] + files).run_command unless s.exitstatus == 0 s.stderr.split("\n").each do |line| m = /no path found matching pattern (.*)/.match(line.strip) next unless m unowned_files << m[1] end end end unowned_files end
Given a list of files, return those that are not owned by the relevant package management for this host. Note: When using this, if you have other filters (like, "is this in my config"), use this filter last, so that you don't execute pkgmgmt stuff on files you don't need to (and hopefully not at all)
files_unowned_by_pkgmgmt
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/libraries/node_methods.rb
Apache-2.0
def forced_why_run @saved_why_run = Chef::Config[:why_run] Chef::Config[:why_run] = true yield ensure Chef::Config[:why_run] = @saved_why_run end
Copied from lib/chef/runner.rb
forced_why_run
ruby
facebook/chef-cookbooks
cookbooks/fb_helpers/resources/gated_template.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_helpers/resources/gated_template.rb
Apache-2.0
def launchd_resource(label, action, attrs = {}) Chef::Log.debug( "fb_launchd: new launchd resource '#{label}' with action '#{action}' " + "and attributes #{attrs}", ) return unless label res = launchd label do action action.to_sym if attrs['only_if'] only_if { attrs['only_if'].call } end if attrs['not_if'] not_if { attrs['not_if'].call } end end attrs.each do |attribute, value| next if ['action', 'only_if', 'not_if'].include?(attribute) res.send(attribute.to_sym, value) end res end
Constructs a new launchd resource with label 'label' and action 'action'. attrs is a Hash of key/value pairs of launchd attributes and their values. Returns the new launchd resource.
launchd_resource
ruby
facebook/chef-cookbooks
cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def managed_plists(prefix) PLIST_DIRECTORIES.map do |dir| plist_glob = ::File.join(::File.expand_path(dir), "*#{prefix}*.plist") ::Dir.glob(plist_glob) end.flatten end
Finds any managed plists in the standard launchd directories with the specified prefix. Returns a list of paths to the managed plists.
managed_plists
ruby
facebook/chef-cookbooks
cookbooks/fb_launchd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_launchd/resources/default.rb
Apache-2.0
def validate_network_addresses(conf) address = conf.dig('config', 'Network', 'Address') if address.is_a?(String) begin ::IPAddr.new(address) rescue ::IPAddr::Error raise "Trying to use bad Network Address IP: '#{address}' from conf: #{conf}" end elsif address.is_a?(Array) address.each do |ip| ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad Network Address IP: '#{ip}' from conf: #{conf}" end end conf.dig('config', 'Address')&.each do |addr| if (ip = addr['Address']) begin ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad Address IP: '#{ip}' from conf: #{conf}" end end end conf.dig('config', 'Route')&.each do |route| ['Gateway', 'Destination', 'Source'].each do |route_type| if route[route_type] ip = route[route_type] begin ::IPAddr.new(ip) rescue ::IPAddr::Error raise "Trying to use bad route #{route_type} IP: '#{ip}' from route: #{route}" end end end end end
TODO: A more reusable approach community-wise would be to create custom resources for the different networkd units and move this validation to those custom resources
validate_network_addresses
ruby
facebook/chef-cookbooks
cookbooks/fb_networkd/resources/default.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkd/resources/default.rb
Apache-2.0
def generate_config_hashes(from_file, desired_config) defaults = {} if desired_config['_defaults'] defaults = desired_config['_defaults'].dup desired_config.delete('_defaults') end current = {} if ::File.exist?(from_file) current = IniParse.parse(::File.read(from_file)).to_hash end interim_config = Chef::Mixin::DeepMerge.merge(defaults, current) new_config = Chef::Mixin::DeepMerge.merge(interim_config, desired_config) [current, new_config] end
the magic here is all DeepMerge and testing this is arguably a bit silly, but since this is the most important part of the whole cookbook, we add a test just to make sure no one ever reverses the arguments or something weird
generate_config_hashes
ruby
facebook/chef-cookbooks
cookbooks/fb_networkmanager/libraries/resource.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_networkmanager/libraries/resource.rb
Apache-2.0
def ip?(iface_address) self['network']['interfaces'].to_hash.each_value do |value| if value['addresses'] && value['addresses'][iface_address] return true end end false end
Returns true if the address provided as input is configured in any of the network interfaces.
ip?
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/node_methods.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/node_methods.rb
Apache-2.0
def will_restart_network?(run_context) root_run_context = run_context.root_run_context root_run_context.delayed_notification_collection.each_value do |notif| notif.each do |n| will_run = n.notifying_resource.updated_by_last_action? name = n.resource if name.to_s == 'service[network]' && will_run return true end end end false end
Walk all notifications that are queued
will_restart_network?
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
Apache-2.0
def get_ip_object(str, failok = false) canonicalize_ipv6(str) rescue IPAddr::InvalidAddressError => e msg = "fb_network_scripts: Failed to parse IPv6 address #{str}" if failok Chef::Log.warn( "#{msg}, but told failure is OK, so returning nil (#{e})", ) return nil end raise "#{msg}: #{e}" end
When building IP objects we want to fail only if the *new* address fails parsing, not the old one, so we can fix stuff
get_ip_object
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/libraries/rh_int_helpers.rb
Apache-2.0
def start(interface, best_effort) s = Mixlib::ShellOut.new("/sbin/ifup #{interface}").run_command unless best_effort s.error! end end
This can shellout because it's called within `converge_by`
start
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/resources/redhat_interface.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb
Apache-2.0
def stop(interface) # handle the case where we have an up interface without a config file if ::File.exist?("/etc/sysconfig/network-scripts/ifcfg-#{interface}") cmd = "/sbin/ifdown #{interface}" else cmd = "/sbin/ifconfig #{interface} down" end s = Mixlib::ShellOut.new(cmd).run_command s.error! end
This can shellout because it's called within `converge_by`
stop
ruby
facebook/chef-cookbooks
cookbooks/fb_network_scripts/resources/redhat_interface.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_network_scripts/resources/redhat_interface.rb
Apache-2.0
def get_latest_version( list, version = nil ) Chef::Log.debug( "Grabbing the latest version from list: #{list.map(&:to_s).join(', ')}", ) unless version.nil? || version.to_s.eql?('0') Chef::Log.debug("Reducing versions to #{version}") list = reduce_by_version(list, version) end latest_version = list.max # If Gem::Version.new() is passed an empty string, it returns version 0 # It is safe to assume there will never be a version 0 and Install-Module # will never accept that. if latest_version.nil? fail "#{new_resource.repository} does not have " + "#{new_resource.module_name} with version #{version} " + 'available to be installed.' end return latest_version end
Returns the latest version from the repo list
get_latest_version
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def get_repo_list Chef::Log.debug( "Fetching all versions of #{new_resource.module_name} " + "from #{new_resource.repository}.", ) psexec = powershell_exec( <<-EOH, $splat = @{ Name = "#{new_resource.module_name}" Repository = "#{new_resource.repository}" AllVersions = $True } (Find-Module @splat).Version.ForEach({$_.ToString()}) EOH ).error! latest = psexec.result Chef::Log.debug("Available versions: #{latest.join(', ')}") return latest.map { |v| Gem::Version.new(v) } end
Returns all available version from the repo.
get_repo_list
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def get_current_version(version) # 0 would be if we are looking for latest if version.to_s.eql?('0') Chef::Log.debug( 'No version filtering. Grabbing the highest version from disk', ) # Current_resource.version is string. return Gem::Version.new(current_resource.version.max) else Chef::Log.debug("Grabbing the highest version of v#{version} from disk.") # Grab the highest version that meets the major, minor, build given list = current_resource.version.map { |v| Gem::Version.new(v) } Chef::Log.debug("Installed versions found: #{list.join(', ')}") # Reducing by version can result in nil array. max = reduce_by_version(list, version).max return max.nil? ? Gem::Version.new(0) : max end end
Get the latest version on disk version is Gem::Version object
get_current_version
ruby
facebook/chef-cookbooks
cookbooks/fb_powershell/resources/fb_powershell_module.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_powershell/resources/fb_powershell_module.rb
Apache-2.0
def filter_work(needs_work, how_to_collapse, storage) case how_to_collapse when :all { :devices => needs_work[:missing_partitions] + needs_work[:mismatched_partitions], :partitions => needs_work[:missing_filesystems] + needs_work[:mismatched_filesystems], :arrays => needs_work[:missing_arrays] + needs_work[:mismatched_arrays], } when :missing { :devices => needs_work[:missing_partitions], :partitions => needs_work[:missing_filesystems], # for missing arrays, we have to do more work below :arrays => filter_arrays_with_mounted_drives( needs_work[:missing_arrays], storage ), } when :filesystems { :devices => [], :partitions => needs_work[:missing_filesystems] + needs_work[:mismatched_filesystems], :arrays => [], } end end
Helper function to filter down work to be done
filter_work
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def merge_work(lhs, rhs) { :devices => (lhs[:devices] + rhs[:devices]).uniq, :partitions => (lhs[:partitions] + rhs[:partitions]).uniq, :arrays => (lhs[:arrays] + rhs[:arrays]).uniq, } end
Hash#merge in ruby doesn't do deep-merges that handle arrays at all, so the array on the RHS always wins. We need this smarter merge.
merge_work
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def filesystems_to_format(storage) to_do = get_primary_work(storage) # all physical hardware, and desired arrays are configured out # # but non-physical hardware requires some extrapolation based on that # data so here we figure out arrays to be filled, cleaned up, etc. fill_in_dynamic_work(to_do, storage) end
Takes things that need to be converted according to the Storage class and filters it for what we're allowed to converge
filesystems_to_format
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def disable_systemd_fstab_generator return unless node.systemd? Chef::Log.info( 'fb_storage: Disabling systemd fstab generator', ) # The way one masks units in systemd is by making a symlink to /dev/null # (an empty file will also work). For most units you can do # `systemctl mask $UNIT`, but not in this case. # # While theoretically you could put a real file in /run, since it's a # tmpfs, that's not a thing you'd actually do, so in practice it's # effectively just a place to mask things. unless File.exist?(FSTAB_GENERATOR_FILE) FileUtils.ln_s('/dev/null', FSTAB_GENERATOR_FILE) # rubocop:disable Chef/Meta/DontUseFileUtils end unless File.exist?(UDEV_MDADM_RULE) FileUtils.ln_s('/dev/null', UDEV_MDADM_RULE) # rubocop:disable Chef/Meta/DontUseFileUtils end systemd_daemon_reload end
Disabling the generator and reloading systemd will drop all of the auto-generated unit files. Therefore systemd won't mount devices as we partition them
disable_systemd_fstab_generator
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/format_devices_provider.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/format_devices_provider.rb
Apache-2.0
def out_of_spec @out_of_spec ||= _out_of_spec end
Return a list of devices and partitions that are out of spec. Note: this doesn't take into account what we are or are not allowed to touch - it's just what doesn't match the desired state
out_of_spec
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def gen_fb_fstab(node) use_labels = node['fb_storage']['fstab_use_labels'] fstab = {} fstab_fields = %w{type mount_point opts pass enable_remount allow_mount_failure} if node['fb_storage']['hybrid_xfs_use_helper'] node.default['fb_fstab']['type_normalization_map']['rtxfs'] = 'xfs' node.default['fb_fstab']['ignorable_opts'] << /^rtdev=.*/ end @config.each do |device, devconf| next if devconf['_skip'] if devconf['whole_device'] partconf = devconf['partitions'][0] if partconf['_swraid_array'] || partconf['_no_mount'] || partconf['_swraid_array_journal'] next end name = "storage_#{device}_whole" fstab[name] = { 'device' => use_labels ? "LABEL=#{devconf['label']}" : device, } fstab_fields.each do |field| fstab[name][field] = devconf['partitions'][0][field] end next end # rubocop:disable Lint/ShadowingOuterLocalVariable devconf['partitions'].each_with_index do |partconf, index| # If we are a member of a SW raid array, or we are a member # of a hybrid-xfs FS or we've been asked not to mount, then we skip # generating the fstab entry. if partconf['_no_mount'] || partconf['_swraid_array'] || partconf['_swraid_array_journal'] || partconf['_xfs_rt_data'] || partconf['_xfs_rt_rescue'] || partconf['_xfs_rt_metadata'] next end partnum = index + 1 partition = FB::Storage.partition_device_name( device, partnum ) name = "storage_#{partition}" fstab[name] = { 'device' => use_labels ? "LABEL=#{partconf['label']}" : partition, } fstab_fields.each do |field| fstab[name][field] = partconf[field] end end # rubocop:enable Lint/ShadowingOuterLocalVariable end @arrays.each do |array, arrayconf| next if arrayconf['_skip'] || arrayconf['_no_mount'] name = "storage_#{array}" if use_labels device = "LABEL=#{arrayconf['label']}" elsif arrayconf['raid_level'] == 'hybrid_xfs' device = arrayconf['journal'] else device = array end fstab[name] = { 'device' => device, } fstab_fields.each do |field| fstab[name][field] = arrayconf[field] end if arrayconf['raid_level'] == 'hybrid_xfs' if node['fb_storage']['hybrid_xfs_use_helper'] fstab[name]['type'] = 'rtxfs' else # point the XFS filesystem to it's data device (rtdev) fstab[name]['opts'] << ",rtdev=#{arrayconf['members'].first}" end end end fstab end
Maps the storage config to an fb_fstab config
gen_fb_fstab
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def build_mapping(node) FB::Storage.build_mapping(node, @maintenance_disks) end
we make an instance method that calls a class method for easier testing of this method without having to factor out `initialize`.
build_mapping
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage.rb
Apache-2.0
def remove_all_partitions_from_all_arrays list = existing_partitions + [@device] Chef::Log.debug( 'fb_storage: Removing all partitions from all arrays ' + "that contain any of #{list}", ) affected = remove_from_arrays(list) affected.each { |d| nuke_raid_header(d) } end
When we're not an array, nuke anything holding us
remove_all_partitions_from_all_arrays
ruby
facebook/chef-cookbooks
cookbooks/fb_storage/libraries/storage_handlers.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookbooks/fb_storage/libraries/storage_handlers.rb
Apache-2.0
def on_true(node) return unless node&.parent&.if_type? return unless node.sibling_index == 0 # Checks `true` is the conditional, not the value ifnode = node.parent add_offense(node, :severity => :refactor) do |corrector| if ifnode.elsif? replace_elsif_true(corrector, ifnode) elsif ifnode.unless? if ifnode.branches.count == 1 replace_unless_true(corrector, ifnode) else replace_unless_true_else(corrector, ifnode) end else replace_if_true(corrector, ifnode) end end end
This class only fires on true/false boolean literals, as firing on every single if-type node would be expensive. However, you'll quickly notice most operations are on the `if` node of the AST, hence the `ifnode` variable. To keep the logic readable, we'll be using the `if` helper methods from rubocop-ast wherever possible https://github.com/rubocop/rubocop-ast/blob/master/lib/rubocop/ast/node/if_node.rb
on_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_true(corrector, ifnode) str = "else\n" str << ' ' * ifnode.if_branch.loc.column str << ifnode.if_branch.source corrector.replace(ifnode, str) end
if foo untouched_case elsif true <- fires here contents else will_be_removed end
replace_elsif_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_true(corrector, ifnode) corrector.replace(ifnode, ifnode.if_branch.source) end
# if/else if true <- fires here contents else will_be_removed end # if/elsif/else if true <- fires here contents elsif whatever will_be_removed else will_be_removed end # ternary foo = true ? contents : will_be_removed
replace_if_true
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false(corrector, ifnode) corrector.replace(ifnode, '') end
if false <-- you are here will_be_removed end
replace_if_false
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false(corrector, ifnode) range = range_between( ifnode.parent.else_branch.loc.expression.begin_pos, ifnode.parent.loc.end.begin_pos, ) corrector.replace(range, '') end
if foo untouched_case elsif false <-- you are here will_be_removed end
replace_elsif_false
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false_else(corrector, ifnode) corrector.replace(ifnode, ifnode.else_branch.source) end
foo = false ? will_be_removed : contents if false will_be_removed else untouched_case end
replace_if_false_else
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_if_false_elsif(corrector, ifnode) range = range_between( ifnode.condition.loc.expression.begin_pos, ifnode.else_branch.condition.loc.expression.begin_pos, ) corrector.replace(range, '') end
if false puts "this should go" elsif var puts "this should be the new if" elsif bar puts "this should remain" else puts "this should remain, too" end if false puts "this should go" elsif var puts "this should be the new if" else puts "this should remain, too" end
replace_if_false_elsif
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false_else(corrector, ifnode) range = range_between( ifnode.loc.expression.begin_pos, ifnode.loc.else.begin_pos, ) corrector.replace(range, '') end
if foo puts "this should stay" elsif false puts "this should go" else puts "this should remain" end
replace_elsif_false_else
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def replace_elsif_false_elsif(corrector, ifnode) range = range_between( ifnode.loc.expression.begin_pos, ifnode.else_branch.loc.expression.begin_pos, ) corrector.replace(range, '') end
if foo puts "this should stay" elsif false puts "this should go" elsif var puts "this should remain" else puts "this should remain, too" end
replace_elsif_false_elsif
ruby
facebook/chef-cookbooks
cookstyle/ConditionalBooleanLiteralCleanup.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/ConditionalBooleanLiteralCleanup.rb
Apache-2.0
def on_new_investigation src = processed_source node = src.ast # only keep `depends ...` actual_dependencies = node.children.filter_map do |child| r = get_dependant(child) r unless r.nil? end expected_sorted = actual_dependencies.sort return if actual_dependencies == expected_sorted # skip if it's already sorted # Grab everything except lines with depends sans_depends = src.raw_source.each_line.reject do |x| x.start_with?('depends') end # Add the depends in order at the end sans_depends += expected_sorted.map { |d| "depends '#{d}'\n" } add_offense(node, :severity => :refactor) do |c| c.replace(processed_source.buffer.source_range, sans_depends.join) end end
This needs to be done at this level vs on_send because we need to be able to offer an autocorrect that doesn't lose items when correcting
on_new_investigation
ruby
facebook/chef-cookbooks
cookstyle/OrderedDependancies.rb
https://github.com/facebook/chef-cookbooks/blob/master/cookstyle/OrderedDependancies.rb
Apache-2.0
def type class_name = object.class.name @@class_names[class_name] ||= class_name.demodulize.tableize.dasherize.freeze end
Override this to customize the JSON:API "type" for this object. By default, the type is the object's class name lowercased, pluralized, and dasherized, per the spec naming recommendations: http://jsonapi.org/recommendations/#naming For example, 'MyApp::LongCommment' will become the 'long-comments' type.
type
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def format_name(attribute_name) attr_name = attribute_name.to_s @@formatted_attribute_names[attr_name] ||= attr_name.dasherize.freeze end
Override this to customize how attribute names are formatted. By default, attribute names are dasherized per the spec naming recommendations: http://jsonapi.org/recommendations/#naming
format_name
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def unformat_name(attribute_name) attr_name = attribute_name.to_s @@unformatted_attribute_names[attr_name] ||= attr_name.underscore.freeze end
The opposite of format_name. Override this if you override format_name.
unformat_name
ruby
fotinakis/jsonapi-serializers
lib/jsonapi-serializers/serializer.rb
https://github.com/fotinakis/jsonapi-serializers/blob/master/lib/jsonapi-serializers/serializer.rb
MIT
def call_proc(proc, *params) # The parameters array for a lambda created from a symbol (&:foo) differs # from explictly defined procs/lambdas, so we can't deduce the number of # parameters from the array length (and differs between Ruby 2.x and 3). # In the case of negative arity -- unlimited/unknown argument count -- # just send the object to act as the method receiver. if proc.arity.negative? proc.call(params.first) else proc.call(*params.take(proc.parameters.length)) end end
Calls either a Proc or a Lambda, making sure to never pass more parameters to it than it can receive @param [Proc] proc the Proc or Lambda to call @param [Array<Object>] *params any number of parameters to be passed to the Proc @return [Object] the result of the Proc call with the supplied parameters
call_proc
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/helpers.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/helpers.rb
Apache-2.0
def is_collection?(resource, force_is_collection = nil) return force_is_collection unless force_is_collection.nil? resource.is_a?(Enumerable) && !resource.respond_to?(:each_pair) end
Detects a collection/enumerable @return [TrueClass] on a successful detection
is_collection?
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/object_serializer.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb
Apache-2.0
def deprecated_cache_options(cache_options) warn('DEPRECATION WARNING: `store:` is a required cache option, we will default to `Rails.cache` for now. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.') %i[enabled cache_length].select { |key| cache_options.key?(key) }.each do |key| warn("DEPRECATION WARNING: `#{key}` is a deprecated cache option and will have no effect soon. See https://github.com/fast-jsonapi/fast_jsonapi#caching for more information.") end self.cache_store_instance = cache_options[:enabled] ? Rails.cache : nil self.cache_store_options = { expires_in: cache_options[:cache_length] || 5.minutes, race_condition_ttl: cache_options[:race_condition_ttl] || 5.seconds } end
FIXME: remove this method once deprecated cache_options are not supported anymore
deprecated_cache_options
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/object_serializer.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/object_serializer.rb
Apache-2.0
def record_cache_options(options, fieldset, includes_list, params) return options unless fieldset options = options ? options.dup : {} options[:namespace] ||= 'jsonapi-serializer' fieldset_key = fieldset.join('_') # Use a fixed-length fieldset key if the current length is more than # the length of a SHA1 digest if fieldset_key.length > 40 fieldset_key = Digest::SHA1.hexdigest(fieldset_key) end options[:namespace] = "#{options[:namespace]}-fieldset:#{fieldset_key}" options end
Cache options helper. Use it to adapt cache keys/rules. If a fieldset is specified, it modifies the namespace to include the fields from the fieldset. @param options [Hash] default cache options @param fieldset [Array, nil] passed fieldset values @param includes_list [Array, nil] passed included values @param params [Hash] the serializer params @return [Hash] processed options hash rubocop:disable Lint/UnusedMethodArgument
record_cache_options
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/serialization_core.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb
Apache-2.0
def parse_includes_list(includes_list) includes_list.each_with_object({}) do |include_item, include_sets| include_base, include_remainder = include_item.to_s.split('.', 2) include_sets[include_base.to_sym] ||= Set.new include_sets[include_base.to_sym] << include_remainder if include_remainder end end
It chops out the root association (first part) from each include. It keeps an unique list and collects all of the rest of the include value to hand it off to the next related to include serializer. This method will turn that include array into a Hash that looks like: { authors: Set.new([ 'books', 'books.genre', 'books.genre.books', 'books.genre.books.authors', 'books.genre.books.genre' ]), genre: Set.new(['books']) } Because the serializer only cares about the root associations included, it only needs the first segment of each include (for books, it's the "authors" and "genre") and it doesn't need to waste cycles parsing the rest of the include value. That will be done by the next serializer in line. @param includes_list [List] to be parsed @return [Hash]
parse_includes_list
ruby
jsonapi-serializer/jsonapi-serializer
lib/fast_jsonapi/serialization_core.rb
https://github.com/jsonapi-serializer/jsonapi-serializer/blob/master/lib/fast_jsonapi/serialization_core.rb
Apache-2.0
def update if params[:user][:password].blank? params[:user].delete 'password' params[:user].delete 'password_confirmation' end current_user.update_attributes user_params respond_with current_user do |format| format.html do if current_user.valid? flash[:success] = t('controllers.accounts.update.success') redirect_to account_url else render 'show' end end end end
Updates the current user with the attributes in the `:user` parameterized hash. Routes ------ * `PATCH /account` Body Parameters --------------- | | | |:-------|:----------------------------------------------------------| | `user` | New attributes for the current user (parameterized hash). |
update
ruby
SquareSquash/web
app/controllers/accounts_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/accounts_controller.rb
Apache-2.0
def markdown $markdown ||= ->(text) { Kramdown::Document.new(text).to_html } end
@return [Kramdown::Document] A Markdown renderer that can be used to render comment bodies. Also available in views.
markdown
ruby
SquareSquash/web
app/controllers/application_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/application_controller.rb
Apache-2.0
def index respond_to do |format| format.html do @filter_users = User.where(id: @environment.bugs.select('assigned_user_id').uniq.limit(PER_PAGE).map(&:assigned_user_id)).order('username ASC') # index.html.rb end format.json do filter = (params[:filter] || ActionController::Parameters.new).permit(:fixed, :irrelevant, :assigned_user_id, :deploy_id, :search, :any_occurrence_crashed) filter.each { |k, v| filter[k] = nil if v == '' } filter.delete('deploy_id') if filter['deploy_id'].nil? # no deploy set means ANY deploy, not NO deploy filter.delete('any_occurrence_crashed') if filter['any_occurrence_crashed'].nil? # sentinel values filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'somebody' filter.delete('assigned_user_id') if filter['assigned_user_id'] == 'anybody' filter['assigned_user_id'] = nil if filter['assigned_user_id'] == 'nobody' query = filter.delete('search') sort_column, default_dir = SORTS[params[:sort]] dir = if params[:dir].kind_of?(String) then SORT_DIRECTIONS.include?(params[:dir].upcase) ? params[:dir].upcase : default_dir else default_dir end @bugs = @environment.bugs.where(filter).order("#{sort_column} #{dir}, bugs.number #{dir}").limit(PER_PAGE) @bugs = @bugs.where('assigned_user_id IS NOT NULL') if params[:filter] && params[:filter][:assigned_user_id] == 'somebody' @bugs = @bugs.query(query) if query.present? last = params[:last].present? ? @environment.bugs.find_by_number(params[:last]) : nil @bugs = @bugs.where(infinite_scroll_clause(sort_column, dir, last, 'bugs.number')) if last begin render json: decorate_bugs(@bugs) rescue => err if (err.kind_of?(ActiveRecord::StatementInvalid) || (defined?(ActiveRecord::JDBCError) && err.kind_of?(ActiveRecord::JDBCError))) && err.to_s =~ /syntax error in tsquery/ head :unprocessable_entity else raise end end end format.atom { @bugs = @environment.bugs.order('first_occurrence DESC').limit(100) } end end
Generally, displays a list of a Bugs. HTML ==== Renders a page with a sortable table displaying the Bugs in an Environment. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs` JSON ==== Powers said sortable table; returns a paginating list of 50 Bugs, sorted according to the query parameters. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs.json` Query Parameters ---------------- | | | |:-------|:----------------------------------------------------------------------------------------------------------| | `sort` | How to sort the list of Bugs; see {SORTS}. | | `dir` | The direction of sort, "ASC" or "DESC" (ignored otherwise). | | `last` | The number of the last Bug of the previous page; used to determine the start of the next page (optional). | Atom ==== Returns a feed of the most recently received bugs. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs.atom`
index
ruby
SquareSquash/web
app/controllers/bugs_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb
Apache-2.0
def show @aggregation_dimensions = Occurrence::AGGREGATING_FIELDS. map { |field| [Occurrence.human_attribute_name(field), field.to_s] }. unshift(['', nil]) # We use `duplicate_of_number` on the view and `duplicate_of_id` in the # backend, so we need to copy between those values. @bug.duplicate_of_number = @bug.duplicate_of.try!(:number) @new_issue_url = Service::JIRA.new_issue_link(summary: t('controllers.bugs.show.jira_link.summary', class_name: @bug.class_name, file_name: File.basename(@bug.file), line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line, locale: @bug.environment.project.locale), environment: @environment.name, description: t('controllers.bugs.show.jira_link.description', class_name: @bug.class_name, file: File.basename(@bug.file), line: @bug.special_file? ? t('controllers.bugs.show.jira_link.not_applicable') : @bug.line, message: @bug.message_template, revision: @bug.revision, url: project_environment_bug_url(@project, @environment, @bug), locale: @bug.environment.project.locale), issuetype: 1) respond_with @project, @environment, @bug.as_json.merge(watched: current_user.watches?(@bug)) end
Displays a page with information about a Bug. Routes ------ * `GET /projects/:project_id/environments/:environment_id/bugs/:id` Path Parameters --------------- | | | |:-----|:-------------------------| | `id` | The Bug number (not ID). |
show
ruby
SquareSquash/web
app/controllers/bugs_controller.rb
https://github.com/SquareSquash/web/blob/master/app/controllers/bugs_controller.rb
Apache-2.0