_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q3700
SadPanda.Emotion.call
train
def call words = stems_for(remove_stopwords_in(@words)) score_words(frequencies_for(words)) scores.key(scores.values.max) end
ruby
{ "resource": "" }
q3701
SadPanda.Emotion.method_missing
train
def method_missing(emotion) return scores[emotion] || 0 if scores.keys.include? emotion raise NoMethodError, "#{emotion} is not defined" end
ruby
{ "resource": "" }
q3702
SadPanda.Emotion.ambiguous_score
train
def ambiguous_score unq_scores = scores.values.uniq scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero? end
ruby
{ "resource": "" }
q3703
SadPanda.Emotion.score_emotions
train
def score_emotions(emotion, term, frequency) return unless SadPanda::Bank::EMOTIONS[emotion].include?(term) scores[emotion] += frequency end
ruby
{ "resource": "" }
q3704
SadPanda.Emotion.set_emotions
train
def set_emotions(word, frequency) SadPanda::Bank::EMOTIONS.keys.each do |emotion| score_emotions(emotion, word, frequency) end end
ruby
{ "resource": "" }
q3705
SadPanda.Emotion.score_words
train
def score_words(word_frequencies) word_frequencies.each do |word, frequency| set_emotions(word, frequency) end score_emoticons ambiguous_score end
ruby
{ "resource": "" }
q3706
Autoversion.DSL.parse_file
train
def parse_file path, matcher File.open(path) do |f| f.each do |line| if m = matcher.call(line) return m end end end raise "#{path}: found no matching lines." end
ruby
{ "resource": "" }
q3707
Autoversion.DSL.update_file
train
def update_file path, matcher, currentVersion, nextVersion temp_path = "#{path}.autoversion" begin File.open(path) do |source| File.open(temp_path, 'w') do |target| source.each do |line| if matcher.call(line) target.write line.gsub currentVersion.to_s, nextVersion.to_s else target.write line end end end end File.rename temp_path, path ensure File.unlink temp_path if File.file? temp_path end end
ruby
{ "resource": "" }
q3708
Autoversion.DSL.update_files
train
def update_files paths, matcher, currentVersion, nextVersion paths.each do |path| update_file path, matcher, currentVersion, nextVersion end end
ruby
{ "resource": "" }
q3709
RightScale.BundleRunner.echo
train
def echo(options) which = options[:id] ? "with ID #{options[:id].inspect}" : "named #{format_script_name(options[:name])}" scope = options[:scope] == :all ? "'all' servers" : "a 'single' server" where = options[:tags] ? "on #{scope} with tags #{options[:tags].inspect}" : "locally on this server" using = "" if options[:parameters] && !options[:parameters].empty? using = " using parameters #{options[:parameters].inspect}" end if options[:json] using += !using.empty? && options[:json_file] ? " and " : " using " using += "options from JSON file #{options[:json_file].inspect}" end if options[:thread] thread = " on thread #{options[:thread]}" else thread = "" end if options[:policy] policy = " auditing on policy #{options[:policy]}" else policy = "" end puts "Requesting to execute the #{type} #{which} #{where}#{using}#{thread}#{policy}" true end
ruby
{ "resource": "" }
q3710
RightScale.BundleRunner.to_forwarder_options
train
def to_forwarder_options(options) result = {} if options[:tags] result[:tags] = options[:tags] result[:selector] = options[:scope] end if options[:thread] result[:thread] = options[:thread] end if options[:policy] result[:policy] = options[:policy] end if options[:audit_period] result[:audit_period] = options[:audit_period].to_s end result end
ruby
{ "resource": "" }
q3711
Ruyml.Data.render
train
def render(template, output = nil) result = ERB.new(File.read(template), 0, '-').result(binding) if !output.nil? File.open(output, "w") do |file| file.write(result) end else puts result end end
ruby
{ "resource": "" }
q3712
Outpost.Application.add_scout
train
def add_scout(scout_description, &block) config = ScoutConfig.new config.instance_eval(&block) scout_description.each do |scout, description| @scouts[scout] << { :description => description, :config => config } end end
ruby
{ "resource": "" }
q3713
Outpost.Application.notify
train
def notify if reports.any? @notifiers.each do |notifier, options| # .dup is NOT reliable options_copy = Marshal.load(Marshal.dump(options)) notifier.new(options_copy).notify(self) end end end
ruby
{ "resource": "" }
q3714
RightScale.AuditProxy.append_output
train
def append_output(text) @mutex.synchronize do @buffer << RightScale::AuditProxy.force_utf8(text) end EM.next_tick do buffer_size = nil @mutex.synchronize do buffer_size = @buffer.size end if buffer_size > MAX_AUDIT_SIZE flush_buffer else reset_timer end end end
ruby
{ "resource": "" }
q3715
RightScale.AuditProxy.internal_send_audit
train
def internal_send_audit(options) RightScale::AuditProxy.force_utf8!(options[:text]) opts = { :audit_id => @audit_id, :category => options[:category], :offset => @size } opts[:category] ||= EventCategories::CATEGORY_NOTIFICATION unless EventCategories::CATEGORIES.include?(opts[:category]) Log.warning("Invalid category '#{opts[:category]}' for notification '#{options[:text]}', using generic category instead") opts[:category] = EventCategories::CATEGORY_NOTIFICATION end log_method = options[:kind] == :error ? :error : :info log_text = AuditFormatter.send(options[:kind], options[:text])[:detail] log_text.chomp.split("\n").each { |l| Log.__send__(log_method, l) } begin audit = AuditFormatter.__send__(options[:kind], options[:text]) @size += audit[:detail].size request = RetryableRequest.new("/auditor/update_entry", opts.merge(audit), :timeout => AUDIT_DELIVERY_TIMEOUT) request.callback { |_| } # No result of interest other than know it was successful request.errback { |message| Log.error("Failed to send update for audit #{@audit_id} (#{message})") } request.run rescue Exception => e Log.error("Failed to send update for audit #{@audit_id}", e, :trace) end true end
ruby
{ "resource": "" }
q3716
RightScale.AuditProxy.flush_buffer
train
def flush_buffer # note we must discard cancelled timer or else we never create a new timer and stay cancelled. if @timer @timer.cancel @timer = nil end to_send = nil @mutex.synchronize do unless @buffer.empty? to_send = @buffer @buffer = '' end end if to_send internal_send_audit(:kind => :output, :text => to_send, :category => EventCategories::NONE) end end
ruby
{ "resource": "" }
q3717
Emcee.Document.htmlify_except
train
def htmlify_except(nodes) nodes.reduce(to_html) do |output, node| output.gsub(node.to_html, node.to_xhtml) end end
ruby
{ "resource": "" }
q3718
RightScale.Reenroller.run
train
def run(options) check_privileges AgentConfig.root_dir = AgentConfig.right_link_root_dirs if RightScale::Platform.windows? cleanup_certificates(options) # Write state file to indicate to RightScaleService that it should not # enter the rebooting state (which is the default behavior when the # RightScaleService starts). reenroller_state = {:reenroll => true} File.open(STATE_FILE, "w") { |f| f.write reenroller_state.to_json } print 'Restarting RightScale service...' if options[:verbose] res = system('net start RightScale') puts to_ok(res) if options[:verbose] else print 'Stopping RightLink daemon...' if options[:verbose] pid_file = AgentConfig.pid_file('instance') pid = pid_file ? pid_file.read_pid[:pid] : nil system('/opt/rightscale/bin/rchk --stop') # Wait for agent process to terminate retries = 0 while process_running?(pid) && retries < 40 sleep(0.5) retries += 1 print '.' if options[:verbose] end puts to_ok(!process_running?(pid)) if options[:verbose] # Kill it if it's still alive after ~ 20 sec if process_running?(pid) print 'Forcing RightLink daemon to exit...' if options[:verbose] res = Process.kill('KILL', pid) rescue nil puts to_ok(res) if options[:verbose] end cleanup_certificates(options) # Resume option bypasses cloud state initialization so that we can # override the user data puts((options[:resume] ? 'Resuming' : 'Restarting') + ' RightLink daemon...') if options[:verbose] action = (options[:resume] ? 'resume' : 'start') res = system("/etc/init.d/rightlink #{action} > /dev/null") end true end
ruby
{ "resource": "" }
q3719
RightScale.Reenroller.process_running?
train
def process_running?(pid) return false unless pid Process.getpgid(pid) != -1 rescue Errno::ESRCH false end
ruby
{ "resource": "" }
q3720
RightScale.AgentChecker.start
train
def start(options) begin setup_traps @state_serializer = Serializer.new(:json) # Retrieve instance agent configuration options @agent = AgentConfig.agent_options('instance') error("No instance agent configured", nil, abort = true) if @agent.empty? # Apply agent's ping interval if needed and adjust options to make them consistent @options = options unless @options[:time_limit] if @agent[:ping_interval] @options[:time_limit] = @agent[:ping_interval] * PING_INTERVAL_MULTIPLIER else @options[:time_limit] = DEFAULT_TIME_LIMIT end end @options[:retry_interval] = [@options[:retry_interval], @options[:time_limit]].min @options[:max_attempts] = [@options[:max_attempts], @options[:time_limit] / @options[:retry_interval]].min @options[:log_path] ||= RightScale::Platform.filesystem.log_dir # Attach to log used by instance agent Log.program_name = 'RightLink' Log.facility = 'user' Log.log_to_file_only(@agent[:log_to_file_only]) Log.init(@agent[:identity], @options[:log_path], :print => true) Log.level = :debug if @options[:verbose] @logging_enabled = true # Catch any egregious eventmachine failures, especially failure to connect to agent with CommandIO # Exit even if running as daemon since no longer can trust EM and should get restarted automatically EM.error_handler do |e| if e.class == RuntimeError && e.message =~ /no connection/ error("Failed to connect to agent for communication check", nil, abort = false) @command_io_failures = (@command_io_failures || 0) + 1 reenroll! if @command_io_failures > @options[:max_attempts] else error("Internal checker failure", e, abort = true) end end # note that our Windows service monitors rnac and rchk processes # externally and restarts them if they die, so no need to roll our # own cross-monitoring on that platform. use_agent_watcher = !RightScale::Platform.windows? EM.run do check setup_agent_watcher if use_agent_watcher end stop_agent_watcher if use_agent_watcher rescue SystemExit => e raise e rescue Exception => e error("Failed to run", e, abort = true) end true end
ruby
{ "resource": "" }
q3721
RightScale.AgentChecker.check
train
def check begin checker_identity = "#{@agent[:identity]}-rchk" pid_file = PidFile.new(checker_identity, @agent[:pid_dir]) if @options[:stop] # Stop checker pid_data = pid_file.read_pid if pid_data[:pid] info("Stopping checker daemon") if RightScale::Platform.windows? begin send_command({:name => :terminate}, verbose = @options[:verbose], timeout = 30) do |r| info(r) terminate end rescue Exception => e error("Failed stopping checker daemon, confirm it is still running", e, abort = true) end else Process.kill('TERM', pid_data[:pid]) terminate end else terminate end elsif @options[:daemon] # Run checker as daemon pid_file.check rescue error("Cannot start checker daemon because already running", nil, abort = true) daemonize(checker_identity, @options) unless RightScale::Platform.windows? pid_file.write at_exit { pid_file.remove } listen_port = CommandConstants::BASE_INSTANCE_AGENT_CHECKER_SOCKET_PORT @command_runner = CommandRunner.start(listen_port, checker_identity, AgentCheckerCommands.get(self)) info("Checker daemon options:") log_options = @options.inject([]) { |t, (k, v)| t << "- #{k}: #{v}" } log_options.each { |l| info(l, to_console = false, no_check = true) } info("Starting checker daemon with #{elapsed(@options[:time_limit])} polling " + "and #{elapsed(@options[:time_limit])} last communication limit") iteration = 0 EM.add_periodic_timer(@options[:time_limit]) do iteration += 1 debug("Checker iteration #{iteration}") check_communication(0) end else # Perform one check check_communication(0, @options[:ping]) end rescue SystemExit => e raise e rescue Exception => e error("Internal checker failure", e, abort = true) end true end
ruby
{ "resource": "" }
q3722
RightScale.AgentChecker.check_communication
train
def check_communication(attempt, must_try = false) attempt += 1 begin if !must_try && (time = time_since_last_communication) < @options[:time_limit] @retry_timer.cancel if @retry_timer elapsed = elapsed(time) info("Passed communication check with activity as recently as #{elapsed} ago", to_console = !@options[:daemon]) terminate unless @options[:daemon] elsif attempt <= @options[:max_attempts] debug("Trying communication" + (attempt > 1 ? ", attempt #{attempt}" : "")) try_communicating(attempt) @retry_timer = EM::Timer.new(@options[:retry_interval]) do error("Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}") @agent = AgentConfig.agent_options('instance') # Reload in case not using right cookie check_communication(attempt) end else reenroll! end rescue SystemExit => e raise e rescue Exception => e abort = !@options[:daemon] && (attempt > @options[:max_attempts]) error("Failed communication check", e, abort) check_communication(attempt) end true end
ruby
{ "resource": "" }
q3723
RightScale.AgentChecker.time_since_last_communication
train
def time_since_last_communication state_file = @options[:state_path] || File.join(AgentConfig.agent_state_dir, 'state.js') state = @state_serializer.load(File.read(state_file)) if File.file?(state_file) state.nil? ? (@options[:time_limit] + 1) : (Time.now.to_i - state["last_communication"]) end
ruby
{ "resource": "" }
q3724
RightScale.AgentChecker.try_communicating
train
def try_communicating(attempt) begin send_command({:name => "check_connectivity"}, @options[:verbose], COMMAND_IO_TIMEOUT) do |r| @command_io_failures = 0 res = serialize_operation_result(r) rescue nil if res && res.success? info("Successful agent communication" + (attempt > 1 ? " on attempt #{attempt}" : "")) @retry_timer.cancel if @retry_timer check_communication(attempt) else error = (res && result.content) || "<unknown error>" error("Failed agent communication attempt", error, abort = false) # Let existing timer control next attempt end end rescue Exception => e error("Failed to access agent for communication check", e, abort = false) end true end
ruby
{ "resource": "" }
q3725
RightScale.AgentChecker.reenroll!
train
def reenroll! unless @reenrolling @reenrolling = true begin info("Triggering re-enroll after unsuccessful communication check", to_console = true) cmd = "rs_reenroll" cmd += " -v" if @options[:verbose] cmd += '&' unless RightScale::Platform.windows? # Windows relies on the command protocol to terminate properly. # If rchk terminates itself, then rchk --stop will hang trying # to connect to this rchk. terminate unless RightScale::Platform.windows? system(cmd) # Wait around until rs_reenroll has a chance to stop the checker # otherwise we may restart it sleep(5) rescue Exception => e error("Failed re-enroll after unsuccessful communication check", e, abort = true) end @reenrolling = false end true end
ruby
{ "resource": "" }
q3726
RightScale.AgentChecker.error
train
def error(description, error = nil, abort = false) if @logging_enabled msg = "[check] #{description}" msg += ", aborting" if abort msg = Log.format(msg, error, :trace) if error Log.error(msg) end msg = description msg += ": #{error}" if error puts "** #{msg}" if abort terminate exit(1) end true end
ruby
{ "resource": "" }
q3727
RightScale.AgentChecker.elapsed
train
def elapsed(time) time = time.to_i if time <= MINUTE "#{time} sec" elsif time <= HOUR minutes = time / MINUTE seconds = time - (minutes * MINUTE) "#{minutes} min #{seconds} sec" elsif time <= DAY hours = time / HOUR minutes = (time - (hours * HOUR)) / MINUTE "#{hours} hr #{minutes} min" else days = time / DAY hours = (time - (days * DAY)) / HOUR minutes = (time - (days * DAY) - (hours * HOUR)) / MINUTE "#{days} day#{days == 1 ? '' : 's'} #{hours} hr #{minutes} min" end end
ruby
{ "resource": "" }
q3728
RightScale.InstanceCommands.run_recipe_command
train
def run_recipe_command(opts) payload = opts[:options] || {} target = {} target[:tags] = payload.delete(:tags) if payload[:tags] target[:scope] = payload.delete(:scope) if payload[:scope] target[:selector] = payload.delete(:selector) if payload[:selector] if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all) send_push("/instance_scheduler/execute", opts[:conn], payload, target) else run_request("/forwarder/schedule_recipe", opts[:conn], payload) end end
ruby
{ "resource": "" }
q3729
RightScale.InstanceCommands.run_right_script_command
train
def run_right_script_command(opts) payload = opts[:options] || {} target = {} target[:tags] = payload.delete(:tags) if payload[:tags] target[:scope] = payload.delete(:scope) if payload[:scope] target[:selector] = payload.delete(:selector) if payload[:selector] if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all) send_push("/instance_scheduler/execute", opts[:conn], payload, target) else run_request("/forwarder/schedule_right_script", opts[:conn], payload) end end
ruby
{ "resource": "" }
q3730
RightScale.InstanceCommands.send_retryable_request_command
train
def send_retryable_request_command(opts) options = opts[:options] options[:timeout] ||= opts[:timeout] send_retryable_request(opts[:type], opts[:conn], opts[:payload], options) end
ruby
{ "resource": "" }
q3731
RightScale.InstanceCommands.get_instance_state_agent_command
train
def get_instance_state_agent_command(opts) result = RightScale::InstanceState.value CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) ) rescue Exception => e CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) ) end
ruby
{ "resource": "" }
q3732
RightScale.InstanceCommands.get_instance_state_run_command
train
def get_instance_state_run_command(opts) value = RightScale::InstanceState.value result = case value when 'booting' "booting#{InstanceState.reboot? ? ':reboot' : ''}" when 'operational', 'stranded' value when 'decommissioning', 'decommissioned' decom_reason = "unknown" decom_reason = InstanceState.decommission_type if ShutdownRequest::LEVELS.include?(InstanceState.decommission_type) "shutting-down:#{decom_reason}" end CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) ) rescue Exception => e CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) ) end
ruby
{ "resource": "" }
q3733
RightScale.InstanceCommands.get_tags_command
train
def get_tags_command(opts) AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) } end
ruby
{ "resource": "" }
q3734
RightScale.InstanceCommands.add_tag_command
train
def add_tag_command(opts) AgentTagManager.instance.add_tags(opts[:tag], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3735
RightScale.InstanceCommands.remove_tag_command
train
def remove_tag_command(opts) AgentTagManager.instance.remove_tags(opts[:tag], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3736
RightScale.InstanceCommands.query_tags_command
train
def query_tags_command(opts) AgentTagManager.instance.query_tags_raw(opts[:tags], opts[:hrefs], opts) do |raw_response| reply = @serializer.dump(raw_response) rescue raw_response CommandIO.instance.reply(opts[:conn], reply) end end
ruby
{ "resource": "" }
q3737
RightScale.InstanceCommands.audit_create_entry_command
train
def audit_create_entry_command(opts) payload = { :agent_identity => @agent_identity, :summary => opts[:summary], :category => opts[:category] || RightScale::EventCategories::NONE, :user_email => opts[:user_email], :detail => opts[:detail] } send_push('/auditor/create_entry', opts[:conn], payload) end
ruby
{ "resource": "" }
q3738
RightScale.InstanceCommands.audit_update_status_command
train
def audit_update_status_command(opts) AuditCookStub.instance.forward_audit(:update_status, opts[:content], opts[:thread_name], opts[:options]) CommandIO.instance.reply(opts[:conn], 'OK', close_after_writing=false) end
ruby
{ "resource": "" }
q3739
RightScale.InstanceCommands.set_inputs_patch_command
train
def set_inputs_patch_command(opts) payload = {:agent_identity => @agent_identity, :patch => opts[:patch]} send_push("/updater/update_inputs", opts[:conn], payload) CommandIO.instance.reply(opts[:conn], 'OK') end
ruby
{ "resource": "" }
q3740
RightScale.InstanceCommands.send_push
train
def send_push(type, conn, payload = nil, target = nil, options = {}) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_push(type, payload, target, options) CommandIO.instance.reply(conn, 'OK') true end
ruby
{ "resource": "" }
q3741
RightScale.InstanceCommands.send_request
train
def send_request(type, conn, payload = nil, target = nil, options = {}) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_request(type, payload, target, options) do |r| reply = @serializer.dump(r) rescue '\"Failed to serialize response\"' CommandIO.instance.reply(conn, reply) end true end
ruby
{ "resource": "" }
q3742
RightScale.InstanceCommands.send_retryable_request
train
def send_retryable_request(type, conn, payload = nil, opts = {}) req = RetryableRequest.new(type, payload, opts) callback = Proc.new do |content| result = OperationResult.success(content) reply = @serializer.dump(result) rescue '\"Failed to serialize response\"' CommandIO.instance.reply(conn, reply) end errback = Proc.new do |content| result = OperationResult.error(content) reply = @serializer.dump(result) rescue '\"Failed to serialize response\"' CommandIO.instance.reply(conn, reply) end req.callback(&callback) req.errback(&errback) req.run end
ruby
{ "resource": "" }
q3743
RightScale.InstanceCommands.run_request
train
def run_request(type, conn, payload) payload ||= {} payload[:agent_identity] = @agent_identity Sender.instance.send_request(type, payload) do |r| r = OperationResult.from_results(r) if r && r.success? && r.content.is_a?(RightScale::ExecutableBundle) @scheduler.schedule_bundle(:bundle => r.content) reply = @serializer.dump(OperationResult.success) else reply = @serializer.dump(r) rescue '\"Failed to serialize response\"' end CommandIO.instance.reply(conn, reply) end true end
ruby
{ "resource": "" }
q3744
RightScale.InstanceCommands.get_shutdown_request_command
train
def get_shutdown_request_command(opts) shutdown_request = ShutdownRequest.instance CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? }) rescue Exception => e CommandIO.instance.reply(opts[:conn], { :error => e.message }) end
ruby
{ "resource": "" }
q3745
RightScale.InstanceCommands.set_shutdown_request_command
train
def set_shutdown_request_command(opts) shutdown_request = ShutdownRequest.submit(opts) CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? }) rescue Exception => e CommandIO.instance.reply(opts[:conn], { :error => e.message }) end
ruby
{ "resource": "" }
q3746
Streamio.Video.add_transcoding
train
def add_transcoding(parameters) response = self.class.resource.post("#{id}/transcodings", parameters) reload response.code.to_i == 201 end
ruby
{ "resource": "" }
q3747
RightScale.ServerImporter.http_get
train
def http_get(path, keep_alive = true) uri = safe_parse_http_uri(path) history = [] loop do Log.debug("http_get(#{uri})") # keep history of live connections for more efficient redirection. host = uri.host connection = Rightscale::HttpConnection.new(:logger => Log, :exception => QueryFailed) # prepare request. ensure path not empty due to Net::HTTP limitation. # # note that the default for Net::HTTP is to close the connection after # each request (contrary to expected conventions). we must be explicit # about keep-alive if we want that behavior. request = Net::HTTP::Get.new(uri.path) request['Connection'] = keep_alive ? 'keep-alive' : 'close' # get. response = connection.request(:protocol => uri.scheme, :server => uri.host, :port => uri.port, :request => request) return response.body if response.kind_of?(Net::HTTPSuccess) if response.kind_of?(Net::HTTPServerError) || response.kind_of?(Net::HTTPNotFound) Log.debug("Request failed but can retry; #{response.class.name}") return nil elsif response.kind_of?(Net::HTTPRedirection) # keep history of redirects. location = response['Location'] uri = safe_parse_http_uri(location) else # not retryable. # # note that the EC2 metadata server is known to give malformed # responses on rare occasions, but the right_http_connection will # consider these to be 'bananas' and retry automatically (up to a # pre-defined limit). Log.error("HTTP request failed: #{response.class.name}") raise QueryFailed, "HTTP request failed: #{response.class.name}" end end end
ruby
{ "resource": "" }
q3748
RightScale.ServerImporter.safe_parse_http_uri
train
def safe_parse_http_uri(path) raise ArgumentError.new("URI path cannot be empty") if path.to_s.empty? begin uri = URI.parse(path) rescue URI::InvalidURIError => e # URI raises an exception for paths like "<IP>:<port>" # (e.g. "127.0.0.1:123") unless they also have scheme (e.g. http) # prefix. raise e if path.start_with?("http://") || path.start_with?("https://") uri = URI.parse("http://" + path) uri = URI.parse("https://" + path) if uri.port == 443 path = uri.to_s end # supply any missing default values to make URI as complete as possible. if uri.scheme.nil? || uri.host.nil? scheme = (uri.port == 443) ? 'https' : 'http' uri = URI.parse("#{scheme}://#{path}") path = uri.to_s end if uri.path.to_s.empty? uri = URI.parse("#{path}/") path = uri.to_s end return uri end
ruby
{ "resource": "" }
q3749
Mago.Detector.process_file
train
def process_file(path) code = File.read(path) sexp_node = RubyParser.new.parse(code) file = Mago::RubyFile.new(path) sexp_processor = Mago::SexpProcessor.new(file, @ignore) sexp_processor.process(sexp_node) @report.files << file @on_file.call(file) if @on_file rescue Errno::ENOENT => err handle_error(err.message) rescue Racc::ParseError, Encoding::CompatibilityError => err msg = "#{path} has invalid ruby code. " << err.message handle_error(msg) end
ruby
{ "resource": "" }
q3750
RightScale.ShutdownRequest.process
train
def process(errback = nil, audit = nil, &block) # yield if not shutting down (continuing) or if already requested shutdown. if continue? || @shutdown_scheduled block.call if block return true end # ensure we have an audit, creating a temporary audit if necessary. sender = Sender.instance agent_identity = sender.identity if audit case @level when REBOOT, STOP, TERMINATE operation = "/forwarder/shutdown" payload = {:agent_identity => agent_identity, :kind => @level} else raise InvalidLevel.new("Unexpected shutdown level: #{@level.inspect}") end # request shutdown (kind indicated by operation and/or payload). audit.append_info("Shutdown requested: #{self}") sender.send_request(operation, payload) do |r| res = OperationResult.from_results(r) if res.success? @shutdown_scheduled = true block.call if block else fail(errback, audit, "Failed to shutdown instance", res) end end else AuditProxy.create(agent_identity, "Shutdown requested: #{self}") do |new_audit| process(errback, new_audit, &block) end end true rescue Exception => e fail(errback, audit, e) end
ruby
{ "resource": "" }
q3751
RightScale.ShutdownRequest.fail
train
def fail(errback, audit, msg, res = nil) if msg.kind_of?(Exception) e = msg detailed = Log.format("Could not process shutdown state #{self}", e, :trace) msg = e.message else detailed = nil end msg += ": #{res.content}" if res && res.content audit.append_error(msg, :category => RightScale::EventCategories::CATEGORY_ERROR) if audit Log.error(detailed) if detailed errback.call if errback true end
ruby
{ "resource": "" }
q3752
Netzke::Basepack::DataAdapters.ActiveRecordAdapter.predicates_for_and_conditions
train
def predicates_for_and_conditions(conditions) return nil if conditions.empty? predicates = conditions.map do |q| q = HashWithIndifferentAccess.new(Netzke::Support.permit_hash_params(q)) attr = q[:attr] method, assoc = method_and_assoc(attr) arel_table = assoc ? Arel::Table.new(assoc.klass.table_name.to_sym) : @model.arel_table value = q['value'] op = q['operator'] attr_type = attr_type(attr) case attr_type when :datetime update_predecate_for_datetime(arel_table[method], op, value.to_date) when :string, :text update_predecate_for_string(arel_table[method], op, value) when :boolean update_predecate_for_boolean(arel_table[method], op, value) when :date update_predecate_for_rest(arel_table[method], op, value.to_date) when :enum # HACKY! monkey patching happens here... update_predecate_for_enum(arel_table[method], op, value) else update_predecate_for_rest(arel_table[method], op, value) end end # join them by AND predicates[1..-1].inject(predicates.first) { |r, p| r.and(p) } end
ruby
{ "resource": "" }
q3753
RightScale.AuditStub.send_command
train
def send_command(cmd, content, options) begin options ||= {} cmd = { :name => cmd, :content => RightScale::AuditProxy.force_utf8(content), :options => options } EM.next_tick { @agent_connection.send_command(cmd) } rescue Exception => e $stderr.puts 'Failed to audit' $stderr.puts Log.format("Failed to audit '#{cmd[:name]}'", e, :trace) end end
ruby
{ "resource": "" }
q3754
Webpacked.Helper.webpacked_tags
train
def webpacked_tags(entries, kind) common_entry = ::Rails.configuration.webpacked.common_entry_name common_bundle = asset_tag(common_entry, kind) page_bundle = Array(entries).reduce('') do |memo, entry| tag = asset_tag(entry, kind) memo << tag if tag end common_bundle ? [common_bundle, page_bundle].join : page_bundle end
ruby
{ "resource": "" }
q3755
Webpacked.Helper.asset_tag
train
def asset_tag(entry, kind) path = webpacked_asset_path(entry, kind) if path case kind when :js then javascript_include_tag path when :css then stylesheet_link_tag path end end end
ruby
{ "resource": "" }
q3756
RightScale.ExecutableSequenceProxy.cook_path
train
def cook_path relative_path = File.join(File.dirname(__FILE__), '..', '..', 'bin', 'cook_runner') return File.normalize_path(relative_path) end
ruby
{ "resource": "" }
q3757
RightScale.ExecutableSequenceProxy.report_failure
train
def report_failure(title, msg=nil) @context.audit.append_error(title, :category => RightScale::EventCategories::CATEGORY_ERROR) @context.audit.append_error(msg) unless msg.nil? @context.succeeded = false fail true end
ruby
{ "resource": "" }
q3758
RightScale::Clouds.Azure.get_updated_userdata
train
def get_updated_userdata(data) result = RightScale::CloudUtilities.parse_rightscale_userdata(data) api_url = "https://#{result['RS_server']}/api" client_id = result['RS_rn_id'] client_secret = result['RS_rn_auth'] new_userdata = retrieve_updated_data(api_url, client_id , client_secret) if (new_userdata.to_s.empty?) return data else return new_userdata end end
ruby
{ "resource": "" }
q3759
RightScale.ExternalParameterGatherer.run
train
def run if done? #we might not have ANY external parameters! report_success return true end @audit.create_new_section('Retrieving credentials') #Preflight to check validity of cred objects ok = true @executables_inputs.each_pair do |exe, inputs| inputs.each_pair do |name, location| next if location.is_a?(RightScale::SecureDocumentLocation) msg = "The provided credential (#{location.class.name}) is incompatible with this version of RightLink" report_failure('Cannot process external input', msg) ok = false end end return false unless ok @executables_inputs.each_pair do |exe, inputs| inputs.each_pair do |name, location| payload = { :ticket => location.ticket, :namespace => location.namespace, :names => [location.name] } options = { :targets => location.targets } self.send_retryable_request('/vault/read_documents', payload, options) do |data| handle_response(exe, name, location, data) end end end rescue Exception => e report_failure('Credential gathering failed', "The following execption occurred while gathering credentials", e) end
ruby
{ "resource": "" }
q3760
RightScale.ExternalParameterGatherer.handle_response
train
def handle_response(exe, name, location, response) result = @serializer.load(response) if result.success? if result.content # Since we only ask for one credential at a time, we can do this... secure_document = result.content.first if secure_document.envelope_mime_type.nil? @executables_inputs[exe][name] = secure_document @audit.append_info("Got #{name} of '#{exe.nickname}'; #{count_remaining} remain.") if done? @audit.append_info("All credential values have been retrieved and processed.") report_success end else # The call succeeded but we can't process the credential value msg = "The #{name} input of '#{exe.nickname}' was retrieved from the external source, but its type " + "(#{secure_document.envelope_mime_type}) is incompatible with this version of RightLink." report_failure('Cannot process credential', msg) end end else # We got a result, but it was a failure... msg = "Could not retrieve the value of the #{name} input of '#{exe.nickname}' " + "from the external source. Reason for failure: #{result.content}." report_failure('Failed to retrieve credential', msg) end rescue Exception => e msg = "An unexpected error occurred while retrieving the value of the #{name} input of '#{exe.nickname}.'" report_failure('Unexpected error while retrieving credentials', msg, e) end
ruby
{ "resource": "" }
q3761
RightScale.ExternalParameterGatherer.count_remaining
train
def count_remaining count = @executables_inputs.values.map { |a| a.values.count { |p| not p.is_a?(RightScale::SecureDocument) } } return count.inject { |sum,x| sum + x } || 0 end
ruby
{ "resource": "" }
q3762
RightScale.ExternalParameterGatherer.substitute_parameters
train
def substitute_parameters @executables_inputs.each_pair do |exe, inputs| inputs.each_pair do |name, value| case exe when RightScale::RecipeInstantiation exe.attributes[name] = value.content when RightScale::RightScriptInstantiation exe.parameters[name] = value.content end end end end
ruby
{ "resource": "" }
q3763
RightScale.ExternalParameterGatherer.report_failure
train
def report_failure(title, message, exception = nil) if exception Log.error("ExternalParameterGatherer failed due to " + "#{exception.class.name}: #{exception.message} (#{exception.backtrace.first})") end @failure_title = title @failure_message = message EM.next_tick { fail } end
ruby
{ "resource": "" }
q3764
RightScale.ExternalParameterGatherer.send_retryable_request
train
def send_retryable_request(operation, payload, options = {}, &callback) connection = EM.connect('127.0.0.1', @listen_port, AgentConnection, @cookie, @thread_name, callback) EM.next_tick do connection.send_command(:name => :send_retryable_request, :type => operation, :payload => payload, :options => options) end end
ruby
{ "resource": "" }
q3765
RightScale.CookbookRepoRetriever.should_be_linked?
train
def should_be_linked?(repo_sha, position) @dev_cookbooks.has_key?(repo_sha) && @dev_cookbooks[repo_sha].positions && @dev_cookbooks[repo_sha].positions.detect { |dev_position| dev_position.position == position } end
ruby
{ "resource": "" }
q3766
RightScale.CookbookRepoRetriever.checkout_cookbook_repos
train
def checkout_cookbook_repos(&callback) @dev_cookbooks.each_pair do |repo_sha, dev_repo| repo = dev_repo.to_scraper_hash # get the root dir this repo should be, or was, checked out to repo_dir = @scraper.repo_dir(repo) if File.directory?(repo_dir) # repo was already checked out on this machine; leave it alone # synthesize a scraper callback so our progress listener knows what's up if callback callback.call(:commit, :initialize, "Skipping checkout -- repository already exists in #{repo_dir}", nil) end @registered_checkouts[repo_sha] = repo_dir else # repo wasn't checked out successfully yet; check it out now success = false begin success = @scraper.scrape(repo, &callback) ensure if success @registered_checkouts[repo_sha] = repo_dir else # nuke the repo dir if checkout fails, so we try again next time FileUtils.rm_rf(repo_dir) unless success # scraper logger is an odd duck, so just transfer any errors to # the normal logger. @scraper.errors.each { |e| ::RightScale::Log.error(e) } ::RightScale::Log.error("Failed to checkout from #{repo[:url].inspect}") end end end end true end
ruby
{ "resource": "" }
q3767
RightScale.CookbookRepoRetriever.link
train
def link(repo_sha, position) # symlink to the checked out cookbook only if it was actually checked out if repo_dir = @registered_checkouts[repo_sha] checkout_path = CookbookPathMapping.checkout_path(repo_dir, position) raise ArgumentError.new("Missing directory cannot be linked: #{checkout_path}") unless File.directory?(checkout_path) repose_path = CookbookPathMapping.repose_path(@repose_root, repo_sha, position) FileUtils.mkdir_p(File.dirname(repose_path)) Platform.filesystem.create_symlink(checkout_path, repose_path) return true end false end
ruby
{ "resource": "" }
q3768
RightScale.AgentConnection.send_command
train
def send_command(options) return if @stopped_callback @pending += 1 command = options.dup command[:cookie] = @cookie command[:thread_name] = @thread_name send_data(CommandSerializer.dump(command)) true end
ruby
{ "resource": "" }
q3769
RightScale.AgentConnection.stop
train
def stop(&callback) send_command(:name => :close_connection) @stopped_callback = callback Log.info("[cook] Disconnecting from agent (#{@pending} response#{@pending > 1 ? 's' : ''} pending)") @stop_timeout = EM::Timer.new(STOP_TIMEOUT) do Log.warning("[cook] Time out waiting for responses from agent, forcing disconnection") @stop_timeout = nil on_stopped end true end
ruby
{ "resource": "" }
q3770
RightScale.LoginUserManager.uuid_to_uid
train
def uuid_to_uid(uuid) uuid = Integer(uuid) if uuid >= 0 && uuid <= MAX_UUID 10_000 + uuid else raise RangeError, "#{uuid} is not within (0..#{MAX_UUID})" end end
ruby
{ "resource": "" }
q3771
RightScale.LoginUserManager.pick_username
train
def pick_username(ideal) name = ideal i = 0 while user_exists?(name) i += 1 name = "#{ideal}_#{i}" end name end
ruby
{ "resource": "" }
q3772
RightScale.LoginUserManager.create_user
train
def create_user(username, uuid, superuser) uid = LoginUserManager.uuid_to_uid(uuid) if uid_exists?(uid, ['rightscale']) username = uid_to_username(uid) elsif !uid_exists?(uid) username = pick_username(username) yield(username) if block_given? add_user(username, uid) modify_group('rightscale', :add, username) # NB it is SUPER IMPORTANT to pass :force=>true here. Due to an oddity in Ruby's Etc # extension, a user who has recently been added, won't seem to be a member of # any groups until the SECOND time we enumerate his group membership. manage_user(uuid, superuser, :force=>true) else raise RightScale::LoginManager::SystemConflict, "A user with UID #{uid} already exists and is " + "not managed by RightScale" end username end
ruby
{ "resource": "" }
q3773
RightScale.LoginUserManager.manage_user
train
def manage_user(uuid, superuser, options={}) uid = LoginUserManager.uuid_to_uid(uuid) username = uid_to_username(uid) force = options[:force] || false disable = options[:disable] || false if ( force && uid_exists?(uid) ) || uid_exists?(uid, ['rightscale']) modify_user(username, disable) action = superuser ? :add : :remove modify_group('rightscale_sudo', action, username) if group_exists?('rightscale_sudo') username else false end end
ruby
{ "resource": "" }
q3774
RightScale.LoginUserManager.add_user
train
def add_user(username, uid, shell=nil) uid = Integer(uid) shell ||= DEFAULT_SHELLS.detect { |sh| File.exists?(sh) } useradd = find_sbin('useradd') unless shell.nil? dash_s = "-s #{Shellwords.escape(shell)}" end result = sudo("#{useradd} #{dash_s} -u #{uid} -p #{random_password} -m #{Shellwords.escape(username)}") case result.exitstatus when 0 home_dir = Shellwords.escape(Etc.getpwnam(username).dir) # Locking account to prevent warning os SUSE(it complains on unlocking non-locked account) modify_user(username, true, shell) RightScale::Log.info("LoginUserManager created #{username} successfully") else raise RightScale::LoginManager::SystemConflict, "Failed to create user #{username}" end true end
ruby
{ "resource": "" }
q3775
RightScale.LoginUserManager.modify_user
train
def modify_user(username, locked=false, shell=nil) shell ||= DEFAULT_SHELLS.detect { |sh| File.exists?(sh) } usermod = find_sbin('usermod') if locked # the man page claims that "1" works here, but testing proves that it doesn't. # use 1970 instead. dash_e = "-e 1970-01-01 -L" else dash_e = "-e 99999 -U" end unless shell.nil? dash_s = "-s #{Shellwords.escape(shell)}" end result = sudo("#{usermod} #{dash_e} #{dash_s} #{Shellwords.escape(username)}") case result.exitstatus when 0 RightScale::Log.info("LoginUserManager modified #{username} successfully") else RightScale::Log.error("LoginUserManager failed to modify #{username}") end true end
ruby
{ "resource": "" }
q3776
RightScale.LoginUserManager.modify_group
train
def modify_group(group, operation, username) #Ensure group/user exist; this raises ArgumentError if either does not exist Etc.getgrnam(group) Etc.getpwnam(username) groups = Set.new Etc.group { |g| groups << g.name if g.mem.include?(username) } case operation when :add return false if groups.include?(group) groups << group when :remove return false unless groups.include?(group) groups.delete(group) else raise ArgumentError, "Unknown operation #{operation}; expected :add or :remove" end groups = Shellwords.escape(groups.to_a.join(',')) username = Shellwords.escape(username) usermod = find_sbin('usermod') result = sudo("#{usermod} -G #{groups} #{username}") case result.exitstatus when 0 RightScale::Log.info "Successfully performed group-#{operation} of #{username} to #{group}" return true else RightScale::Log.error "Failed group-#{operation} of #{username} to #{group}" return false end end
ruby
{ "resource": "" }
q3777
RightScale.LoginUserManager.uid_exists?
train
def uid_exists?(uid, groups=[]) uid = Integer(uid) user_exists = Etc.getpwuid(uid).uid == uid if groups.empty? user_belongs = true else mem = Set.new username = Etc.getpwuid(uid).name Etc.group { |g| mem << g.name if g.mem.include?(username) } user_belongs = groups.all? { |g| mem.include?(g) } end user_exists && user_belongs rescue ArgumentError false end
ruby
{ "resource": "" }
q3778
RightScale.LoginUserManager.group_exists?
train
def group_exists?(name) groups = Set.new Etc.group { |g| groups << g.name } groups.include?(name) end
ruby
{ "resource": "" }
q3779
RightScale.LoginUserManager.find_sbin
train
def find_sbin(cmd) path = SBIN_PATHS.detect do |dir| File.exists?(File.join(dir, cmd)) end raise RightScale::LoginManager::SystemConflict, "Failed to find a suitable implementation of '#{cmd}'." unless path File.join(path, cmd) end
ruby
{ "resource": "" }
q3780
RightScale.FlatMetadataFormatter.recursive_flatten_metadata
train
def recursive_flatten_metadata(tree_metadata, flat_metadata = {}, metadata_path = [], path_index = 0) unless tree_metadata.empty? tree_metadata.each do |key, value| metadata_path[path_index] = key if value.respond_to?(:has_key?) recursive_flatten_metadata(value, flat_metadata, metadata_path, path_index + 1) else flat_path = flatten_metadata_path(metadata_path) flat_metadata[flat_path] = value end end metadata_path.pop raise "Unexpected path" unless metadata_path.size == path_index end return flat_metadata end
ruby
{ "resource": "" }
q3781
RightScale.FlatMetadataFormatter.flatten_metadata_path
train
def flatten_metadata_path(metadata_path) flat_path = transform_path(metadata_path) if @formatted_path_prefix && !(flat_path.start_with?(RS_METADATA_PREFIX) || flat_path.start_with?(@formatted_path_prefix)) return @formatted_path_prefix + flat_path end return flat_path end
ruby
{ "resource": "" }
q3782
RightScale.RightScriptsCookbook.script_path
train
def script_path(nickname) base_path = nickname.gsub(/[^0-9a-zA-Z_]/,'_') base_path = File.join(@recipes_dir, base_path) candidate_path = RightScale::Platform.shell.format_script_file_name(base_path) i = 1 path = candidate_path path = candidate_path + (i += 1).to_s while File.exists?(path) path end
ruby
{ "resource": "" }
q3783
RightScale.RightScriptsCookbook.cache_dir
train
def cache_dir(script) # prefix object ID with a text constant to make a legal directory name # in case object id is negative (Ubuntu, etc.). this method will be called # more than once and must return the same directory each time for a given # script instantiation. path = File.normalize_path(File.join(AgentConfig.cache_dir, 'right_scripts_content', "rs_attach" + script.object_id.to_s)) # convert to native format for ease of scripting in Windows, etc. the # normalized path is normal for Ruby but not necessarily for native FS. return RightScale::Platform.filesystem.pretty_path(path, true) end
ruby
{ "resource": "" }
q3784
Yourub.MetaSearch.search
train
def search(criteria) begin @api_options= { :part => 'snippet', :type => 'video', :order => 'relevance', :safeSearch => 'none', } @categories = [] @count_filter = {} @criteria = Yourub::Validator.confirm(criteria) search_by_criteria do |result| yield result end rescue ArgumentError => e Yourub.logger.error "#{e}" end end
ruby
{ "resource": "" }
q3785
Yourub.MetaSearch.get_views
train
def get_views(video_id) params = { :id => video_id, :part => 'statistics' } request = Yourub::REST::Videos.list(self,params) v = Yourub::Result.format(request).first v ? Yourub::CountFilter.get_views_count(v) : nil end
ruby
{ "resource": "" }
q3786
Yourub.MetaSearch.get
train
def get(video_id) params = {:id => video_id, :part => 'snippet,statistics'} request = Yourub::REST::Videos.list(self,params) Yourub::Result.format(request).first end
ruby
{ "resource": "" }
q3787
Hamlet.Parser.parse_text_block
train
def parse_text_block(text_indent = nil, from = nil) empty_lines = 0 first_line = true embedded = nil case from when :from_tag first_line = true when :from_embedded embedded = true end close_bracket = false until @lines.empty? if @lines.first =~ /\A\s*>?\s*\Z/ next_line @stacks.last << [:newline] empty_lines += 1 if text_indent else indent = get_indent(@lines.first) break if indent <= @indents.last if @lines.first =~ /\A\s*>/ indent += 1 #$1.size if $1 close_bracket = true else close_bracket = false end if empty_lines > 0 @stacks.last << [:slim, :interpolate, "\n" * empty_lines] empty_lines = 0 end next_line # The text block lines must be at least indented # as deep as the first line. if text_indent && indent < text_indent # special case for a leading '>' being back 1 char unless first_line && close_bracket && (text_indent - indent == 1) @line.lstrip! syntax_error!('Unexpected text indentation') end end @line.slice!(0, text_indent || indent) unless embedded @line = $' if @line =~ /\A>/ # a code comment if @line =~ /(\A|[^\\])#([^{]|\Z)/ @line = $` + $1 end end @stacks.last << [:newline] if !first_line && !embedded @stacks.last << [:slim, :interpolate, (text_indent ? "\n" : '') + @line] << [:newline] # The indentation of first line of the text block # determines the text base indentation. text_indent ||= indent first_line = false end end end
ruby
{ "resource": "" }
q3788
Emcee.DirectiveProcessor.render
train
def render(context, locals) @context = context @pathname = context.pathname @directory = File.dirname(@pathname) @header = data[HEADER_PATTERN, 0] || "" @body = $' || data # Ensure body ends in a new line @body += "\n" if @body != "" && @body !~ /\n\Z/m @included_pathnames = [] @result = "" @result.force_encoding(body.encoding) @has_written_body = false process_directives process_source @result end
ruby
{ "resource": "" }
q3789
RightScale.SpecHelper.cleanup_state
train
def cleanup_state # intentionally not deleting entire temp dir to preserve localized # executable directories between tests on Windows. see how we reference # RS_RIGHT_RUN_EXE below. delete_if_exists(state_file_path) delete_if_exists(chef_file_path) delete_if_exists(past_scripts_path) delete_if_exists(log_path) delete_if_exists(cook_state_file_path) end
ruby
{ "resource": "" }
q3790
RightScale.SpecHelper.delete_if_exists
train
def delete_if_exists(file) # Windows cannot delete open files, but we only have a path at this point # so it's too late to close the file. report failure to delete files but # otherwise continue without failing test. begin File.delete(file) if File.file?(file) rescue Exception => e puts "\nWARNING: #{e.message}" end end
ruby
{ "resource": "" }
q3791
RightScale.SpecHelper.setup_script_execution
train
def setup_script_execution Dir.glob(File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, '__TestScript*')).should be_empty Dir.glob(File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, '[0-9]*')).should be_empty AgentConfig.cache_dir = File.join(RIGHT_LINK_SPEC_HELPER_TEMP_PATH, 'cache') end
ruby
{ "resource": "" }
q3792
Prowler.Application.verify
train
def verify(api_key = nil) raise ConfigurationError, "You must provide an API key to verify" if api_key.nil? && self.api_key.nil? perform(:verify, { :providerkey => provider_key, :apikey => api_key || self.api_key }, :get, Success) end
ruby
{ "resource": "" }
q3793
PgComment.SchemaDumper.tables_with_comments
train
def tables_with_comments(stream) tables_without_comments(stream) @connection.tables.sort.each do |table_name| dump_comments(table_name, stream) end unless (index_comments = @connection.index_comments).empty? index_comments.each_pair do |index_name, comment| stream.puts " set_index_comment '#{index_name}', '#{format_comment(comment)}'" end end end
ruby
{ "resource": "" }
q3794
PgComment.SchemaDumper.dump_comments
train
def dump_comments(table_name, stream) unless (comments = @connection.comments(table_name)).empty? comment_statements = comments.map do |row| column_name = row[0] comment = format_comment(row[1]) if column_name " set_column_comment '#{table_name}', '#{column_name}', '#{comment}'" else " set_table_comment '#{table_name}', '#{comment}'" end end stream.puts comment_statements.join("\n") stream.puts end end
ruby
{ "resource": "" }
q3795
RightScale.CommandHelper.send_command
train
def send_command(cmd, verbose, timeout=20) config_options = ::RightScale::AgentConfig.agent_options('instance') listen_port = config_options[:listen_port] raise ::ArgumentError.new('Could not retrieve agent listen port') unless listen_port client = ::RightScale::CommandClient.new(listen_port, config_options[:cookie]) result = nil block = Proc.new do |res| result = res yield res if block_given? end client.send_command(cmd, verbose, timeout, &block) result end
ruby
{ "resource": "" }
q3796
RightScale.CommandHelper.default_logger
train
def default_logger(verbose=false) if verbose logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger.formatter = PlainLoggerFormatter.new else logger = RightScale::Log end return logger end
ruby
{ "resource": "" }
q3797
RightScale.OhaiRunner.run
train
def run $0 = "rs_ohai" # to prevent showing full path to executalbe in help banner Log.program_name = 'RightLink' init_logger RightScale::OhaiSetup.configure_ohai Ohai::Application.new.run true end
ruby
{ "resource": "" }
q3798
RightScale.VolumeManagementHelper.manage_planned_volumes
train
def manage_planned_volumes(&block) # state may have changed since timer calling this method was added, so # ensure we are still booting (and not stranded). return if InstanceState.value == 'stranded' # query for planned volume mappings belonging to instance. last_mappings = InstanceState.planned_volume_state.mappings || [] payload = {:agent_identity => @agent_identity} req = RetryableRequest.new("/storage_valet/get_planned_volumes", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS) req.callback do |res| res ||= [] # res is nil or an array of hashes begin mappings = merge_planned_volume_mappings(last_mappings, res) InstanceState.planned_volume_state.mappings = mappings if mappings.empty? # no volumes requiring management. @audit.append_info("This instance has no planned volumes.") block.call if block elsif (detachable_volume_count = mappings.count { |mapping| is_unmanaged_attached_volume?(mapping) }) >= 1 # must detach all 'attached' volumes if any are attached (or # attaching) but not yet managed on the instance side. this is the # only way to ensure they receive the correct device names. mappings.each do |mapping| if is_unmanaged_attached_volume?(mapping) detach_planned_volume(mapping) do detachable_volume_count -= 1 if 0 == detachable_volume_count # add a timer to resume volume management later and pass the # block for continuation afterward (unless detachment stranded). Log.info("Waiting for volumes to detach for management purposes. "\ "Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...") EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) } end end end end elsif mapping = mappings.find { |mapping| is_detaching_volume?(mapping) } # we successfully requested detachment but status has not # changed to reflect this yet. Log.info("Waiting for volume #{mapping[:volume_id]} to fully detach. "\ "Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...") EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) } elsif mapping = mappings.find { |mapping| is_managed_attaching_volume?(mapping) } Log.info("Waiting for volume #{mapping[:volume_id]} to fully attach. Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...") EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) } elsif mapping = mappings.find { |mapping| is_managed_attached_unassigned_volume?(mapping) } manage_volume_device_assignment(mapping) do unless InstanceState.value == 'stranded' # we can move on to next volume 'immediately' if volume was # successfully assigned its device name. if mapping[:management_status] == 'assigned' EM.next_tick { manage_planned_volumes(&block) } else Log.info("Waiting for volume #{mapping[:volume_id]} to initialize using \"#{mapping[:mount_points].first}\". "\ "Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...") EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) } end end end elsif mapping = mappings.find { |mapping| is_detached_volume?(mapping) } attach_planned_volume(mapping) do unless InstanceState.value == 'stranded' unless mapping[:attempts] @audit.append_info("Attached volume #{mapping[:volume_id]} using \"#{mapping[:mount_points].first}\".") Log.info("Waiting for volume #{mapping[:volume_id]} to appear using \"#{mapping[:mount_points].first}\". "\ "Retrying in #{VolumeManagement::VOLUME_RETRY_SECONDS} seconds...") end EM.add_timer(VolumeManagement::VOLUME_RETRY_SECONDS) { manage_planned_volumes(&block) } end end elsif mapping = mappings.find { |mapping| is_unmanageable_volume?(mapping) } strand("State of volume #{mapping[:volume_id]} was unmanageable: #{mapping[:volume_status]}") else # all volumes are managed and have been assigned and so we can proceed. block.call if block end rescue Exception => e strand(e) end end req.errback do |res| strand("Failed to retrieve planned volume mappings", res) end req.run end
ruby
{ "resource": "" }
q3799
RightScale.VolumeManagementHelper.detach_planned_volume
train
def detach_planned_volume(mapping) payload = {:agent_identity => @agent_identity, :device_name => mapping[:device_name]} Log.info("Detaching volume #{mapping[:volume_id]} for management purposes.") req = RetryableRequest.new("/storage_valet/detach_volume", payload, :retry_delay => VolumeManagement::VOLUME_RETRY_SECONDS) req.callback do |res| # don't set :volume_status here as that should only be queried mapping[:management_status] = 'detached' mapping[:attempts] = nil yield if block_given? end req.errback do |res| unless InstanceState.value == 'stranded' # volume could already be detaching or have been deleted # which we can't see because of latency; go around again # and check state of volume later. Log.error("Failed to detach volume #{mapping[:volume_id]} (#{res})") mapping[:attempts] ||= 0 mapping[:attempts] += 1 # retry indefinitely so long as core api instructs us to retry or else fail after max attempts. if mapping[:attempts] >= VolumeManagement::MAX_VOLUME_ATTEMPTS strand("Exceeded maximum of #{VolumeManagement::MAX_VOLUME_ATTEMPTS} attempts detaching volume #{mapping[:volume_id]} with error: #{res}") else yield if block_given? end end end req.run end
ruby
{ "resource": "" }