id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
3,700
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.call
def call words = stems_for(remove_stopwords_in(@words)) score_words(frequencies_for(words)) scores.key(scores.values.max) end
ruby
def call words = stems_for(remove_stopwords_in(@words)) score_words(frequencies_for(words)) scores.key(scores.values.max) end
[ "def", "call", "words", "=", "stems_for", "(", "remove_stopwords_in", "(", "@words", ")", ")", "score_words", "(", "frequencies_for", "(", "words", ")", ")", "scores", ".", "key", "(", "scores", ".", "values", ".", "max", ")", "end" ]
Main method that initiates scoring emotions
[ "Main", "method", "that", "initiates", "scoring", "emotions" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L18-L23
3,701
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.method_missing
def method_missing(emotion) return scores[emotion] || 0 if scores.keys.include? emotion raise NoMethodError, "#{emotion} is not defined" end
ruby
def method_missing(emotion) return scores[emotion] || 0 if scores.keys.include? emotion raise NoMethodError, "#{emotion} is not defined" end
[ "def", "method_missing", "(", "emotion", ")", "return", "scores", "[", "emotion", "]", "||", "0", "if", "scores", ".", "keys", ".", "include?", "emotion", "raise", "NoMethodError", ",", "\"#{emotion} is not defined\"", "end" ]
MethodMissing to implement metods that are the names of each emotion that will returen the score of that specific emotion for the text
[ "MethodMissing", "to", "implement", "metods", "that", "are", "the", "names", "of", "each", "emotion", "that", "will", "returen", "the", "score", "of", "that", "specific", "emotion", "for", "the", "text" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L28-L32
3,702
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.ambiguous_score
def ambiguous_score unq_scores = scores.values.uniq scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero? end
ruby
def ambiguous_score unq_scores = scores.values.uniq scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero? end
[ "def", "ambiguous_score", "unq_scores", "=", "scores", ".", "values", ".", "uniq", "scores", "[", ":ambiguous", "]", "=", "1", "if", "unq_scores", ".", "length", "==", "1", "&&", "unq_scores", ".", "first", ".", "zero?", "end" ]
Last part of the scoring process If all scores are empty ambiguous is scored as 1
[ "Last", "part", "of", "the", "scoring", "process", "If", "all", "scores", "are", "empty", "ambiguous", "is", "scored", "as", "1" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L38-L41
3,703
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.score_emotions
def score_emotions(emotion, term, frequency) return unless SadPanda::Bank::EMOTIONS[emotion].include?(term) scores[emotion] += frequency end
ruby
def score_emotions(emotion, term, frequency) return unless SadPanda::Bank::EMOTIONS[emotion].include?(term) scores[emotion] += frequency end
[ "def", "score_emotions", "(", "emotion", ",", "term", ",", "frequency", ")", "return", "unless", "SadPanda", "::", "Bank", "::", "EMOTIONS", "[", "emotion", "]", ".", "include?", "(", "term", ")", "scores", "[", "emotion", "]", "+=", "frequency", "end" ]
Increments the score of an emotion if the word exist in that emotion bank
[ "Increments", "the", "score", "of", "an", "emotion", "if", "the", "word", "exist", "in", "that", "emotion", "bank" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L45-L49
3,704
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.set_emotions
def set_emotions(word, frequency) SadPanda::Bank::EMOTIONS.keys.each do |emotion| score_emotions(emotion, word, frequency) end end
ruby
def set_emotions(word, frequency) SadPanda::Bank::EMOTIONS.keys.each do |emotion| score_emotions(emotion, word, frequency) end end
[ "def", "set_emotions", "(", "word", ",", "frequency", ")", "SadPanda", "::", "Bank", "::", "EMOTIONS", ".", "keys", ".", "each", "do", "|", "emotion", "|", "score_emotions", "(", "emotion", ",", "word", ",", "frequency", ")", "end", "end" ]
Iterates all emotions for word in text
[ "Iterates", "all", "emotions", "for", "word", "in", "text" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L52-L56
3,705
mattThousand/sad_panda
lib/sad_panda/emotion.rb
SadPanda.Emotion.score_words
def score_words(word_frequencies) word_frequencies.each do |word, frequency| set_emotions(word, frequency) end score_emoticons ambiguous_score end
ruby
def score_words(word_frequencies) word_frequencies.each do |word, frequency| set_emotions(word, frequency) end score_emoticons ambiguous_score end
[ "def", "score_words", "(", "word_frequencies", ")", "word_frequencies", ".", "each", "do", "|", "word", ",", "frequency", "|", "set_emotions", "(", "word", ",", "frequency", ")", "end", "score_emoticons", "ambiguous_score", "end" ]
Logic to score all unique words in the text
[ "Logic", "to", "score", "all", "unique", "words", "in", "the", "text" ]
2ccb1496529d5c5a453d3822fa44b746295f3962
https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L68-L76
3,706
jpettersson/autoversion
lib/autoversion/dsl.rb
Autoversion.DSL.parse_file
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
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
[ "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" ]
Parse the specified file with the provided matcher. The first returned match will be used as the version.
[ "Parse", "the", "specified", "file", "with", "the", "provided", "matcher", "." ]
15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7
https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L30-L40
3,707
jpettersson/autoversion
lib/autoversion/dsl.rb
Autoversion.DSL.update_file
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
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
[ "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" ]
Update a file naively matching the specified matcher and replace any matching lines with the new version.
[ "Update", "a", "file", "naively", "matching", "the", "specified", "matcher", "and", "replace", "any", "matching", "lines", "with", "the", "new", "version", "." ]
15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7
https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L44-L64
3,708
jpettersson/autoversion
lib/autoversion/dsl.rb
Autoversion.DSL.update_files
def update_files paths, matcher, currentVersion, nextVersion paths.each do |path| update_file path, matcher, currentVersion, nextVersion end end
ruby
def update_files paths, matcher, currentVersion, nextVersion paths.each do |path| update_file path, matcher, currentVersion, nextVersion end end
[ "def", "update_files", "paths", ",", "matcher", ",", "currentVersion", ",", "nextVersion", "paths", ".", "each", "do", "|", "path", "|", "update_file", "path", ",", "matcher", ",", "currentVersion", ",", "nextVersion", "end", "end" ]
Convenience function for update_file to apply to multiple files.
[ "Convenience", "function", "for", "update_file", "to", "apply", "to", "multiple", "files", "." ]
15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7
https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L67-L71
3,709
rightscale/right_link
scripts/bundle_runner.rb
RightScale.BundleRunner.echo
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
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
[ "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" ]
Echo what is being requested === Parameters options(Hash):: Options specified === Return true:: Always return true
[ "Echo", "what", "is", "being", "requested" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/bundle_runner.rb#L105-L131
3,710
rightscale/right_link
scripts/bundle_runner.rb
RightScale.BundleRunner.to_forwarder_options
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
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
[ "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" ]
Map arguments options into forwarder actor compatible options === Parameters options(Hash):: Arguments options === Return result(Hash):: Forwarder actor compatible options hash
[ "Map", "arguments", "options", "into", "forwarder", "actor", "compatible", "options" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/bundle_runner.rb#L210-L227
3,711
xlucas/ruyml
lib/ruyml.rb
Ruyml.Data.render
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
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
[ "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" ]
Create RUYML data from a YAML hash. Underlying hashes will be accessed as instances of this class. Other types are kept untouched and returned as is. Renders RUYML data using the given template. Rendered data is either written to an optional output file path or to stdout.
[ "Create", "RUYML", "data", "from", "a", "YAML", "hash", ".", "Underlying", "hashes", "will", "be", "accessed", "as", "instances", "of", "this", "class", ".", "Other", "types", "are", "kept", "untouched", "and", "returned", "as", "is", ".", "Renders", "RUYML", "data", "using", "the", "given", "template", ".", "Rendered", "data", "is", "either", "written", "to", "an", "optional", "output", "file", "path", "or", "to", "stdout", "." ]
1935cdb62531abf4578082ecd02416f2e67ea760
https://github.com/xlucas/ruyml/blob/1935cdb62531abf4578082ecd02416f2e67ea760/lib/ruyml.rb#L25-L34
3,712
vinibaggio/outpost
lib/outpost/application.rb
Outpost.Application.add_scout
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
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
[ "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" ]
New instance of a Outpost-based class. @see Application#using
[ "New", "instance", "of", "a", "Outpost", "-", "based", "class", "." ]
9fc19952e742598d367dde3fd143c3eaa594720b
https://github.com/vinibaggio/outpost/blob/9fc19952e742598d367dde3fd143c3eaa594720b/lib/outpost/application.rb#L113-L123
3,713
vinibaggio/outpost
lib/outpost/application.rb
Outpost.Application.notify
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
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
[ "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" ]
Runs all notifications associated with an Outpost-based class.
[ "Runs", "all", "notifications", "associated", "with", "an", "Outpost", "-", "based", "class", "." ]
9fc19952e742598d367dde3fd143c3eaa594720b
https://github.com/vinibaggio/outpost/blob/9fc19952e742598d367dde3fd143c3eaa594720b/lib/outpost/application.rb#L145-L153
3,714
rightscale/right_link
lib/instance/audit_proxy.rb
RightScale.AuditProxy.append_output
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
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
[ "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" ]
Append output to current audit section === Parameters text(String):: Output to append to audit entry === Return true:: Always return true === Raise ApplicationError:: If audit id is missing from passed-in options
[ "Append", "output", "to", "current", "audit", "section" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L146-L163
3,715
rightscale/right_link
lib/instance/audit_proxy.rb
RightScale.AuditProxy.internal_send_audit
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
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
[ "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" ]
Actually send audits to core agent and log failures === Parameters options[:kind](Symbol):: One of :status, :new_section, :info, :error, :output options[:text](String):: Text to be audited options[:category](String):: Optional, must be one of RightScale::EventCategories::CATEGORIES === Return true:: Always return true
[ "Actually", "send", "audits", "to", "core", "agent", "and", "log", "failures" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L217-L241
3,716
rightscale/right_link
lib/instance/audit_proxy.rb
RightScale.AuditProxy.flush_buffer
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
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
[ "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" ]
Send any buffered output to auditor === Return Always return true
[ "Send", "any", "buffered", "output", "to", "auditor" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L247-L265
3,717
ahuth/emcee
lib/emcee/document.rb
Emcee.Document.htmlify_except
def htmlify_except(nodes) nodes.reduce(to_html) do |output, node| output.gsub(node.to_html, node.to_xhtml) end end
ruby
def htmlify_except(nodes) nodes.reduce(to_html) do |output, node| output.gsub(node.to_html, node.to_xhtml) end end
[ "def", "htmlify_except", "(", "nodes", ")", "nodes", ".", "reduce", "(", "to_html", ")", "do", "|", "output", ",", "node", "|", "output", ".", "gsub", "(", "node", ".", "to_html", ",", "node", ".", "to_xhtml", ")", "end", "end" ]
Generate an html string for the current document, but replace the provided nodes with their xhtml strings.
[ "Generate", "an", "html", "string", "for", "the", "current", "document", "but", "replace", "the", "provided", "nodes", "with", "their", "xhtml", "strings", "." ]
0c846c037bffe912cb111ebb973e50c98d034995
https://github.com/ahuth/emcee/blob/0c846c037bffe912cb111ebb973e50c98d034995/lib/emcee/document.rb#L59-L63
3,718
rightscale/right_link
scripts/reenroller.rb
RightScale.Reenroller.run
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
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
[ "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" ]
Trigger re-enrollment === Return true:: Always return true
[ "Trigger", "re", "-", "enrollment" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/reenroller.rb#L43-L85
3,719
rightscale/right_link
scripts/reenroller.rb
RightScale.Reenroller.process_running?
def process_running?(pid) return false unless pid Process.getpgid(pid) != -1 rescue Errno::ESRCH false end
ruby
def process_running?(pid) return false unless pid Process.getpgid(pid) != -1 rescue Errno::ESRCH false end
[ "def", "process_running?", "(", "pid", ")", "return", "false", "unless", "pid", "Process", ".", "getpgid", "(", "pid", ")", "!=", "-", "1", "rescue", "Errno", "::", "ESRCH", "false", "end" ]
Checks whether process with given pid is running === Parameters pid(Fixnum):: Process id to be checked === Return true:: If process is running false:: Otherwise
[ "Checks", "whether", "process", "with", "given", "pid", "is", "running" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/reenroller.rb#L143-L148
3,720
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.start
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
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
[ "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", "=~", "/", "/", "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" ]
Run daemon or run one agent communication check If running as a daemon, store pid in same location as agent except suffix the agent identity with '-rchk'. === Parameters options(Hash):: Run options :time_limit(Integer):: Time limit for last communication and interval for daemon checks, defaults to PING_INTERVAL_MULTIPLIER times agent's ping interval or to DEFAULT_TIME_LIMIT :max_attempts(Integer):: Maximum number of communication check attempts, defaults to DEFAULT_MAX_ATTEMPTS :retry_interval(Integer):: Number of seconds to wait before retrying communication check, defaults to DEFAULT_RETRY_INTERVAL, reset to :time_limit if exceeds it :daemon(Boolean):: Whether to run as a daemon rather than do a one-time communication check :log_path(String):: Log file directory, defaults to one used by agent :stop(Boolean):: Whether to stop the currently running daemon and then exit :ping(Boolean):: Try communicating now regardless of whether have communicated within the configured time limit, ignored if :daemon true :verbose(Boolean):: Whether to display debug information === Return true:: Always return true
[ "Run", "daemon", "or", "run", "one", "agent", "communication", "check", "If", "running", "as", "a", "daemon", "store", "pid", "in", "same", "location", "as", "agent", "except", "suffix", "the", "agent", "identity", "with", "-", "rchk", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L164-L222
3,721
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.check
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
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
[ "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" ]
Perform required checks === Return true:: Always return true
[ "Perform", "required", "checks" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L269-L328
3,722
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.check_communication
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
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
[ "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" ]
Check communication, repeatedly if necessary === Parameters attempt(Integer):: Number of attempts thus far must_try(Boolean):: Try communicating regardless of whether required based on time limit === Return true:: Always return true
[ "Check", "communication", "repeatedly", "if", "necessary" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L338-L365
3,723
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.time_since_last_communication
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
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
[ "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" ]
Get elapsed time since last communication === Return (Integer):: Elapsed time
[ "Get", "elapsed", "time", "since", "last", "communication" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L371-L375
3,724
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.try_communicating
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
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
[ "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" ]
Ask instance agent to try to communicate === Parameters attempt(Integer):: Number of attempts thus far === Return true:: Always return true
[ "Ask", "instance", "agent", "to", "try", "to", "communicate" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L384-L403
3,725
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.reenroll!
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
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
[ "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" ]
Trigger re-enroll This will normally cause the checker to exit === Return true:: Always return true
[ "Trigger", "re", "-", "enroll", "This", "will", "normally", "cause", "the", "checker", "to", "exit" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L410-L432
3,726
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.error
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
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
[ "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" ]
Handle error by logging message and optionally aborting execution === Parameters description(String):: Description of context where error occurred error(Exception|String):: Exception or error message abort(Boolean):: Whether to abort execution === Return true:: If do not abort
[ "Handle", "error", "by", "logging", "message", "and", "optionally", "aborting", "execution" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L484-L501
3,727
rightscale/right_link
scripts/agent_checker.rb
RightScale.AgentChecker.elapsed
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
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
[ "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" ]
Convert elapsed time in seconds to displayable format === Parameters time(Integer|Float):: Elapsed time === Return (String):: Display string
[ "Convert", "elapsed", "time", "in", "seconds", "to", "displayable", "format" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L510-L528
3,728
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.run_recipe_command
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
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
[ "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" ]
Run recipe command implementation === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:options](Hash):: Pass-through options sent to forwarder or instance_scheduler with a :tags value indicating tag-based routing instead of local execution === Return true:: Always return true
[ "Run", "recipe", "command", "implementation" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L120-L131
3,729
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.run_right_script_command
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
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
[ "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" ]
Run RightScript command implementation === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:options](Hash):: Pass-through options sent to forwarder or instance_scheduler with a :tags value indicating tag-based routing instead of local execution === Return true:: Always return true
[ "Run", "RightScript", "command", "implementation" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L142-L153
3,730
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.send_retryable_request_command
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
def send_retryable_request_command(opts) options = opts[:options] options[:timeout] ||= opts[:timeout] send_retryable_request(opts[:type], opts[:conn], opts[:payload], options) end
[ "def", "send_retryable_request_command", "(", "opts", ")", "options", "=", "opts", "[", ":options", "]", "options", "[", ":timeout", "]", "||=", "opts", "[", ":timeout", "]", "send_retryable_request", "(", "opts", "[", ":type", "]", ",", "opts", "[", ":conn", "]", ",", "opts", "[", ":payload", "]", ",", "options", ")", "end" ]
Send a retryable request to a single target with a response expected, retrying multiple times at the application layer in case failures or errors occur. === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:type](String):: Request type opts[:payload](String):: Request data, optional opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout opts[:options](Hash):: Request options === Return true:: Always return true
[ "Send", "a", "retryable", "request", "to", "a", "single", "target", "with", "a", "response", "expected", "retrying", "multiple", "times", "at", "the", "application", "layer", "in", "case", "failures", "or", "errors", "occur", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L197-L201
3,731
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.get_instance_state_agent_command
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
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
[ "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" ]
Get Instance State value for Agent type === Parameters opts[:conn](EM::Connection):: Connection used to send reply === Return true:: Always return true
[ "Get", "Instance", "State", "value", "for", "Agent", "type" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L234-L239
3,732
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.get_instance_state_run_command
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
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
[ "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" ]
Get Instance State value for Run type === Parameters opts[:conn](EM::Connection):: Connection used to send reply === Return true:: Always return true
[ "Get", "Instance", "State", "value", "for", "Run", "type" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L248-L263
3,733
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.get_tags_command
def get_tags_command(opts) AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) } end
ruby
def get_tags_command(opts) AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) } end
[ "def", "get_tags_command", "(", "opts", ")", "AgentTagManager", ".", "instance", ".", "tags", "(", "opts", ")", "{", "|", "tags", "|", "CommandIO", ".", "instance", ".", "reply", "(", "opts", "[", ":conn", "]", ",", "tags", ")", "}", "end" ]
Get tags command === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout === Return true:: Always return true
[ "Get", "tags", "command" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L298-L300
3,734
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.add_tag_command
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
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
[ "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" ]
Add given tag === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:tag](String):: Tag to be added opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout === Return true:: Always return true
[ "Add", "given", "tag" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L311-L316
3,735
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.remove_tag_command
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
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
[ "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" ]
Remove given tag === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:tag](String):: Tag to be removed opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout === Return true:: Always return true
[ "Remove", "given", "tag" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L327-L332
3,736
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.query_tags_command
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
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
[ "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" ]
Query for instances with given tags === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:tags](String):: Tags to be used in query opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout === Return true:: Always return true
[ "Query", "for", "instances", "with", "given", "tags" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L343-L348
3,737
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.audit_create_entry_command
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
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
[ "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" ]
Create an audit entry. === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:summary](String):: Initial audit summary; must be present in order to avoid a blank summary! opts[:category](String):: One of the categories enumerated by RightScale::EventCategories opts[:user_email](String):: Optional; email of user who caused the audit event === Return result(RightScale::OperationResult):: result; if successful, payload == an integer audit ID
[ "Create", "an", "audit", "entry", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L360-L370
3,738
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.audit_update_status_command
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
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
[ "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" ]
Update audit summary === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:title](Hash):: Chef attributes hash === Return true:: Always return true
[ "Update", "audit", "summary" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L380-L383
3,739
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.set_inputs_patch_command
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
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
[ "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" ]
Update inputs patch to be sent back to core after cook process finishes === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:patch](Hash):: Patch to be forwarded to core === Return true:: Always return true
[ "Update", "inputs", "patch", "to", "be", "sent", "back", "to", "core", "after", "cook", "process", "finishes" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L445-L449
3,740
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.send_push
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
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
[ "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" ]
Helper method to send a request to one or more targets with no response expected See Sender for details
[ "Helper", "method", "to", "send", "a", "request", "to", "one", "or", "more", "targets", "with", "no", "response", "expected", "See", "Sender", "for", "details" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L468-L474
3,741
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.send_request
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
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
[ "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" ]
Helper method to send a request to a single target agent with a response expected The request is retried if the response is not received in a reasonable amount of time The request is timed out if not received in time, typically configured to 2 minutes The request is allowed to expire per the agent's configured time-to-live, typically 1 minute See Sender for details
[ "Helper", "method", "to", "send", "a", "request", "to", "a", "single", "target", "agent", "with", "a", "response", "expected", "The", "request", "is", "retried", "if", "the", "response", "is", "not", "received", "in", "a", "reasonable", "amount", "of", "time", "The", "request", "is", "timed", "out", "if", "not", "received", "in", "time", "typically", "configured", "to", "2", "minutes", "The", "request", "is", "allowed", "to", "expire", "per", "the", "agent", "s", "configured", "time", "-", "to", "-", "live", "typically", "1", "minute", "See", "Sender", "for", "details" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L481-L489
3,742
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.send_retryable_request
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
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
[ "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" ]
Helper method to send a retryable request to a single target with a response expected, retrying at the application layer until the request succeeds or the timeout elapses; default timeout is 'forever'. See RetryableRequest for details
[ "Helper", "method", "to", "send", "a", "retryable", "request", "to", "a", "single", "target", "with", "a", "response", "expected", "retrying", "at", "the", "application", "layer", "until", "the", "request", "succeeds", "or", "the", "timeout", "elapses", ";", "default", "timeout", "is", "forever", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L496-L514
3,743
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.run_request
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
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
[ "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" ]
Send scheduling request for recipe or RightScript If it returns with a bundle, schedule the bundle for execution === Parameters type(String):: Type of request conn(EM::Connection):: Connection used to send reply payload(Hash):: Request parameters === Return true:: Always return true
[ "Send", "scheduling", "request", "for", "recipe", "or", "RightScript", "If", "it", "returns", "with", "a", "bundle", "schedule", "the", "bundle", "for", "execution" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L526-L540
3,744
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.get_shutdown_request_command
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
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
[ "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" ]
Get shutdown request command === Parameters opts[:conn](EM::Connection):: Connection used to send reply === Return true:: Always return true
[ "Get", "shutdown", "request", "command" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L561-L566
3,745
rightscale/right_link
lib/instance/instance_commands.rb
RightScale.InstanceCommands.set_shutdown_request_command
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
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
[ "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" ]
Set reboot timeout command === Parameters opts[:conn](EM::Connection):: Connection used to send reply opts[:level](String):: shutdown request level opts[:immediately](Boolean):: shutdown immediacy or nil === Return true:: Always return true
[ "Set", "reboot", "timeout", "command" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L577-L582
3,746
streamio/streamio-rb
lib/streamio/video.rb
Streamio.Video.add_transcoding
def add_transcoding(parameters) response = self.class.resource.post("#{id}/transcodings", parameters) reload response.code.to_i == 201 end
ruby
def add_transcoding(parameters) response = self.class.resource.post("#{id}/transcodings", parameters) reload response.code.to_i == 201 end
[ "def", "add_transcoding", "(", "parameters", ")", "response", "=", "self", ".", "class", ".", "resource", ".", "post", "(", "\"#{id}/transcodings\"", ",", "parameters", ")", "reload", "response", ".", "code", ".", "to_i", "==", "201", "end" ]
Adds a transcoding to the video instance and reloads itself to reflect the changed transcodings array. @param [Hash] parameters The parameters to pass in when creating the transcoding. @option parameters [String] :encoding_profile_id Id of the Encoding Profile to be used for the transcoding. @return [Boolean] Indicating wether the transcoding was successfully created.
[ "Adds", "a", "transcoding", "to", "the", "video", "instance", "and", "reloads", "itself", "to", "reflect", "the", "changed", "transcodings", "array", "." ]
7285a065e2301c7f2aafe5fbfad9332680159852
https://github.com/streamio/streamio-rb/blob/7285a065e2301c7f2aafe5fbfad9332680159852/lib/streamio/video.rb#L16-L20
3,747
rightscale/right_link
scripts/server_importer.rb
RightScale.ServerImporter.http_get
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
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
[ "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" ]
Performs an HTTP get request with built-in retries and redirection based on HTTP responses. === Parameters attempts(int):: number of attempts === Return result(String):: body of response or nil
[ "Performs", "an", "HTTP", "get", "request", "with", "built", "-", "in", "retries", "and", "redirection", "based", "on", "HTTP", "responses", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/server_importer.rb#L179-L218
3,748
rightscale/right_link
scripts/server_importer.rb
RightScale.ServerImporter.safe_parse_http_uri
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
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
[ "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" ]
Handles some cases which raise exceptions in the URI class. === Parameters path(String):: URI to parse === Return uri(URI):: parsed URI === Raise URI::InvalidURIError:: on invalid URI
[ "Handles", "some", "cases", "which", "raise", "exceptions", "in", "the", "URI", "class", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/server_importer.rb#L230-L256
3,749
greyblake/mago
lib/mago/detector.rb
Mago.Detector.process_file
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
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
[ "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" ]
Process a file and add a result to the report. @param path [String] @return [void]
[ "Process", "a", "file", "and", "add", "a", "result", "to", "the", "report", "." ]
ed75d35200cbce2b43e3413eb5aed4736d940577
https://github.com/greyblake/mago/blob/ed75d35200cbce2b43e3413eb5aed4736d940577/lib/mago/detector.rb#L49-L64
3,750
rightscale/right_link
lib/instance/shutdown_request.rb
RightScale.ShutdownRequest.process
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
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
[ "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" ]
Processes shutdown requests by communicating the need to shutdown an instance with the core agent, if necessary. === Parameters errback(Proc):: error handler or nil audit(Audit):: audit for shutdown action, if needed, or nil. === Block block(Proc):: continuation block for successful handling of shutdown or nil === Return always true
[ "Processes", "shutdown", "requests", "by", "communicating", "the", "need", "to", "shutdown", "an", "instance", "with", "the", "core", "agent", "if", "necessary", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/shutdown_request.rb#L147-L185
3,751
rightscale/right_link
lib/instance/shutdown_request.rb
RightScale.ShutdownRequest.fail
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
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
[ "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" ]
Handles any shutdown failure. === Parameters audit(Audit):: Audit or nil errback(Proc):: error handler or nil msg(String):: Error message that will be audited and logged res(RightScale::OperationResult):: Operation result with additional information === Return always true
[ "Handles", "any", "shutdown", "failure", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/shutdown_request.rb#L204-L217
3,752
arman000/marty
lib/marty/monkey.rb
Netzke::Basepack::DataAdapters.ActiveRecordAdapter.predicates_for_and_conditions
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
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
[ "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" ]
The following is a hack to get around Netzke's broken handling of filtering on PostgreSQL enums columns.
[ "The", "following", "is", "a", "hack", "to", "get", "around", "Netzke", "s", "broken", "handling", "of", "filtering", "on", "PostgreSQL", "enums", "columns", "." ]
4437c9db62352be4d1147ea011ebb54350b20d98
https://github.com/arman000/marty/blob/4437c9db62352be4d1147ea011ebb54350b20d98/lib/marty/monkey.rb#L111-L147
3,753
rightscale/right_link
lib/instance/cook/audit_stub.rb
RightScale.AuditStub.send_command
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
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
[ "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" ]
Helper method used to send command client request to RightLink agent === Parameters cmd(String):: Command name content(String):: Audit content options(Hash):: Audit options or nil === Return true:: Always return true
[ "Helper", "method", "used", "to", "send", "command", "client", "request", "to", "RightLink", "agent" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/audit_stub.rb#L130-L139
3,754
Darkside73/webpacked
lib/webpacked/helper.rb
Webpacked.Helper.webpacked_tags
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
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
[ "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" ]
Return include tags for entry points by given asset kind. Also common file could be included
[ "Return", "include", "tags", "for", "entry", "points", "by", "given", "asset", "kind", ".", "Also", "common", "file", "could", "be", "included" ]
353bd50f4a03ee14c69e75dcf9a7da8ccb297e9f
https://github.com/Darkside73/webpacked/blob/353bd50f4a03ee14c69e75dcf9a7da8ccb297e9f/lib/webpacked/helper.rb#L18-L26
3,755
Darkside73/webpacked
lib/webpacked/helper.rb
Webpacked.Helper.asset_tag
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
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
[ "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" ]
Return include tags for entry point by given asset kind. No extra common file included even if it exists
[ "Return", "include", "tags", "for", "entry", "point", "by", "given", "asset", "kind", ".", "No", "extra", "common", "file", "included", "even", "if", "it", "exists" ]
353bd50f4a03ee14c69e75dcf9a7da8ccb297e9f
https://github.com/Darkside73/webpacked/blob/353bd50f4a03ee14c69e75dcf9a7da8ccb297e9f/lib/webpacked/helper.rb#L30-L38
3,756
rightscale/right_link
lib/instance/executable_sequence_proxy.rb
RightScale.ExecutableSequenceProxy.cook_path
def cook_path relative_path = File.join(File.dirname(__FILE__), '..', '..', 'bin', 'cook_runner') return File.normalize_path(relative_path) end
ruby
def cook_path relative_path = File.join(File.dirname(__FILE__), '..', '..', 'bin', 'cook_runner') return File.normalize_path(relative_path) end
[ "def", "cook_path", "relative_path", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'..'", ",", "'..'", ",", "'bin'", ",", "'cook_runner'", ")", "return", "File", ".", "normalize_path", "(", "relative_path", ")", "end" ]
Path to 'cook_runner' ruby script === Return path(String):: Path to ruby script used to run Chef
[ "Path", "to", "cook_runner", "ruby", "script" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/executable_sequence_proxy.rb#L200-L203
3,757
rightscale/right_link
lib/instance/executable_sequence_proxy.rb
RightScale.ExecutableSequenceProxy.report_failure
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
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
[ "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" ]
Report cook process execution failure === Parameters title(String):: Title used to update audit status msg(String):: Optional, extended failure message === Return true:: Always return true
[ "Report", "cook", "process", "execution", "failure" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/executable_sequence_proxy.rb#L301-L307
3,758
rightscale/right_link
lib/clouds/clouds/azure.rb
RightScale::Clouds.Azure.get_updated_userdata
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
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
[ "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" ]
Parses azure user metadata into a hash. === Parameters data(String):: raw data === Return result(Hash):: Hash-like leaf value
[ "Parses", "azure", "user", "metadata", "into", "a", "hash", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/clouds/azure.rb#L118-L129
3,759
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.run
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
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
[ "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" ]
Initialize parameter gatherer === Parameters bundle<RightScale::ExecutableBundle>:: the bundle for which to gather inputs options[:listen_port]:: Command server listen port options[:cookie]:: Command protocol cookie === Return true:: Always return true Retrieve from RightNet and process credential values in bundle's executables. == Returns: @return [TrueClass] true on success and false on error
[ "Initialize", "parameter", "gatherer" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L62-L101
3,760
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.handle_response
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
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
[ "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" ]
Handle a RightNet response to our retryable request. Could be success, failure or unexpected.
[ "Handle", "a", "RightNet", "response", "to", "our", "retryable", "request", ".", "Could", "be", "success", "failure", "or", "unexpected", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L106-L135
3,761
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.count_remaining
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
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
[ "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" ]
Return the number of credentials remaining to be gathered
[ "Return", "the", "number", "of", "credentials", "remaining", "to", "be", "gathered" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L138-L141
3,762
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.substitute_parameters
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
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
[ "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" ]
Do the actual substitution of credential values into the bundle
[ "Do", "the", "actual", "substitution", "of", "credential", "values", "into", "the", "bundle" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L149-L160
3,763
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.report_failure
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
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
[ "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" ]
Report a failure by setting some attributes that our caller will query, then updating our Deferrable disposition so our caller gets notified via errback.
[ "Report", "a", "failure", "by", "setting", "some", "attributes", "that", "our", "caller", "will", "query", "then", "updating", "our", "Deferrable", "disposition", "so", "our", "caller", "gets", "notified", "via", "errback", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L170-L179
3,764
rightscale/right_link
lib/instance/cook/external_parameter_gatherer.rb
RightScale.ExternalParameterGatherer.send_retryable_request
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
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
[ "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" ]
Use the command protocol to send a retryable request. This class cannot reuse Cook's implementation of the command-proto request wrappers because we must gather credentials concurrently for performance reasons. The easiest way to do this is simply to open a new command proto socket for every distinct request we make.
[ "Use", "the", "command", "protocol", "to", "send", "a", "retryable", "request", ".", "This", "class", "cannot", "reuse", "Cook", "s", "implementation", "of", "the", "command", "-", "proto", "request", "wrappers", "because", "we", "must", "gather", "credentials", "concurrently", "for", "performance", "reasons", ".", "The", "easiest", "way", "to", "do", "this", "is", "simply", "to", "open", "a", "new", "command", "proto", "socket", "for", "every", "distinct", "request", "we", "make", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/external_parameter_gatherer.rb#L185-L191
3,765
rightscale/right_link
lib/instance/cook/cookbook_repo_retriever.rb
RightScale.CookbookRepoRetriever.should_be_linked?
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
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
[ "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" ]
Should there be a link created for this cookbook? === Parameters repo_sha (String) :: unique identifier of the cookbook repository position (String) :: repo relative ppath of the cookbook === Returns true if there is a cookbook in the given repo that should be checekd out
[ "Should", "there", "be", "a", "link", "created", "for", "this", "cookbook?" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cookbook_repo_retriever.rb#L59-L63
3,766
rightscale/right_link
lib/instance/cook/cookbook_repo_retriever.rb
RightScale.CookbookRepoRetriever.checkout_cookbook_repos
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
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
[ "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" ]
Checkout the given repo and link each dev cookbook to it's matching repose path === Parameters callback (Proc) :: to be called for each repo checked out see RightScraper::Scraper.scrape for details === Return true
[ "Checkout", "the", "given", "repo", "and", "link", "each", "dev", "cookbook", "to", "it", "s", "matching", "repose", "path" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cookbook_repo_retriever.rb#L94-L129
3,767
rightscale/right_link
lib/instance/cook/cookbook_repo_retriever.rb
RightScale.CookbookRepoRetriever.link
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
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
[ "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" ]
Creates a symlink from the checked out cookbook to the expected repose download location === Parameters repo_sha (String) :: unique identifier of the cookbook repository position (String) :: repo relative ppath of the cookbook === Returns true if link was created, false otherwise
[ "Creates", "a", "symlink", "from", "the", "checked", "out", "cookbook", "to", "the", "expected", "repose", "download", "location" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/cookbook_repo_retriever.rb#L139-L150
3,768
rightscale/right_link
lib/instance/cook/agent_connection.rb
RightScale.AgentConnection.send_command
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
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
[ "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" ]
Set command client cookie and initialize responses parser Send command to running agent === Parameters options(Hash):: Hash of options and command name options[:name]:: Command name options[:...]:: Other command specific options, passed through to agent === Return true:: Always return true
[ "Set", "command", "client", "cookie", "and", "initialize", "responses", "parser", "Send", "command", "to", "running", "agent" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/agent_connection.rb#L58-L66
3,769
rightscale/right_link
lib/instance/cook/agent_connection.rb
RightScale.AgentConnection.stop
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
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
[ "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" ]
Stop command client, wait for all pending commands to finish prior to calling given callback === Return true:: Always return true === Block called once all pending commands have completed
[ "Stop", "command", "client", "wait", "for", "all", "pending", "commands", "to", "finish", "prior", "to", "calling", "given", "callback" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/cook/agent_connection.rb#L85-L95
3,770
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.uuid_to_uid
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
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
[ "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" ]
Map a universally-unique integer RightScale user ID to a locally-unique Unix UID.
[ "Map", "a", "universally", "-", "unique", "integer", "RightScale", "user", "ID", "to", "a", "locally", "-", "unique", "Unix", "UID", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L40-L47
3,771
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.pick_username
def pick_username(ideal) name = ideal i = 0 while user_exists?(name) i += 1 name = "#{ideal}_#{i}" end name end
ruby
def pick_username(ideal) name = ideal i = 0 while user_exists?(name) i += 1 name = "#{ideal}_#{i}" end name end
[ "def", "pick_username", "(", "ideal", ")", "name", "=", "ideal", "i", "=", "0", "while", "user_exists?", "(", "name", ")", "i", "+=", "1", "name", "=", "\"#{ideal}_#{i}\"", "end", "name", "end" ]
Pick a username that does not yet exist on the system. If the given username does not exist, it is returned; else we add a "_1" suffix and continue incrementing the number until we arrive at a username that does not yet exist. === Parameters ideal(String):: the user's ideal (chosen) username === Return username(String):: username with possible postfix
[ "Pick", "a", "username", "that", "does", "not", "yet", "exist", "on", "the", "system", ".", "If", "the", "given", "username", "does", "not", "exist", "it", "is", "returned", ";", "else", "we", "add", "a", "_1", "suffix", "and", "continue", "incrementing", "the", "number", "until", "we", "arrive", "at", "a", "username", "that", "does", "not", "yet", "exist", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L59-L69
3,772
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.create_user
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
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
[ "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" ]
Ensure that a given user exists and that his group membership is correct. === Parameters username(String):: preferred username of RightScale user uuid(String):: RightScale user's UUID superuser(Boolean):: whether the user should have sudo privileges === Block If a block is given AND the user needs to be created, yields to the block with the to-be-created account's username, before creating it. This gives the caller a chance to provide interactive feedback to the user. === Return username(String):: user's actual username (may vary from preferred username) === Raise (LoginManager::SystemConflict):: if an existing non-RightScale-managed UID prevents us from creating a user
[ "Ensure", "that", "a", "given", "user", "exists", "and", "that", "his", "group", "membership", "is", "correct", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L88-L109
3,773
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.manage_user
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
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
[ "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" ]
If the given user exists and is RightScale-managed, then ensure his login information and group membership are correct. If force == true, then management tasks are performed irrespective of the user's group membership status. === Parameters uuid(String):: RightScale user's UUID superuser(Boolean):: whether the user should have sudo privileges force(Boolean):: if true, performs group management even if the user does NOT belong to 'rightscale' === Options :force:: if true, then the user will be updated even if they do not belong to the RightScale group :disable:: if true, then the user will be prevented from logging in === Return username(String):: if the user exists, returns his actual username false:: if the user does not exist
[ "If", "the", "given", "user", "exists", "and", "is", "RightScale", "-", "managed", "then", "ensure", "his", "login", "information", "and", "group", "membership", "are", "correct", ".", "If", "force", "==", "true", "then", "management", "tasks", "are", "performed", "irrespective", "of", "the", "user", "s", "group", "membership", "status", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L127-L142
3,774
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.add_user
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
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
[ "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" ]
Create a Unix user with the "useradd" command. === Parameters username(String):: username uid(String):: account's UID expired_at(Time):: account's expiration date; default nil shell(String):: account's login shell; default nil (use systemwide default) === Raise (RightScale::LoginManager::SystemConflict):: if the user could not be created for some reason === Return true:: always returns true
[ "Create", "a", "Unix", "user", "with", "the", "useradd", "command", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L177-L202
3,775
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.modify_user
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
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
[ "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" ]
Modify a user with the "usermod" command. === Parameters username(String):: username uid(String):: account's UID locked(true,false):: if true, prevent the user from logging in shell(String):: account's login shell; default nil (use systemwide default) === Return true:: always returns true
[ "Modify", "a", "user", "with", "the", "usermod", "command", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L214-L241
3,776
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.modify_group
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
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
[ "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" ]
Adds or removes a user from an OS group; does nothing if the user is already in the correct membership state. === Parameters group(String):: group name operation(Symbol):: :add or :remove username(String):: username to add/remove === Raise Raises ArgumentError === Return result(Boolean):: true if user was added/removed; false if
[ "Adds", "or", "removes", "a", "user", "from", "an", "OS", "group", ";", "does", "nothing", "if", "the", "user", "is", "already", "in", "the", "correct", "membership", "state", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L257-L291
3,777
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.uid_exists?
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
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
[ "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" ]
Check if user with specified Unix UID exists in the system, and optionally whether he belongs to all of the specified groups. === Parameters uid(String):: account's UID === Return exist_status(Boolean):: true if exists; otherwise false
[ "Check", "if", "user", "with", "specified", "Unix", "UID", "exists", "in", "the", "system", "and", "optionally", "whether", "he", "belongs", "to", "all", "of", "the", "specified", "groups", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L314-L329
3,778
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.group_exists?
def group_exists?(name) groups = Set.new Etc.group { |g| groups << g.name } groups.include?(name) end
ruby
def group_exists?(name) groups = Set.new Etc.group { |g| groups << g.name } groups.include?(name) end
[ "def", "group_exists?", "(", "name", ")", "groups", "=", "Set", ".", "new", "Etc", ".", "group", "{", "|", "g", "|", "groups", "<<", "g", ".", "name", "}", "groups", ".", "include?", "(", "name", ")", "end" ]
Check if group with specified name exists in the system. === Parameters name(String):: group's name === Block If a block is given, it will be yielded to with various status messages suitable for display to the user. === Return exist_status(Boolean):: true if exists; otherwise false
[ "Check", "if", "group", "with", "specified", "name", "exists", "in", "the", "system", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L342-L346
3,779
rightscale/right_link
lib/instance/login_user_manager.rb
RightScale.LoginUserManager.find_sbin
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
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
[ "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" ]
Search through some directories to find the location of a binary. Necessary because different Linux distributions put their user-management utilities in slightly different places. === Parameters cmd(String):: name of command to search for, e.g. 'usermod' === Return path(String):: the absolute path to the command === Raise (LoginManager::SystemConflict):: if the command can't be found
[ "Search", "through", "some", "directories", "to", "find", "the", "location", "of", "a", "binary", ".", "Necessary", "because", "different", "Linux", "distributions", "put", "their", "user", "-", "management", "utilities", "in", "slightly", "different", "places", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/login_user_manager.rb#L398-L406
3,780
rightscale/right_link
lib/clouds/metadata_formatters/flat_metadata_formatter.rb
RightScale.FlatMetadataFormatter.recursive_flatten_metadata
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
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
[ "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" ]
Recursively flattens metadata. === Parameters tree_metadata(Hash):: metadata to flatten flat_metadata(Hash):: flattened metadata or {} metadata_path(Array):: array of metadata path elements or [] path_index(int):: path array index to update or 0 === Returns flat_metadata(Hash):: flattened metadata
[ "Recursively", "flattens", "metadata", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/metadata_formatters/flat_metadata_formatter.rb#L74-L89
3,781
rightscale/right_link
lib/clouds/metadata_formatters/flat_metadata_formatter.rb
RightScale.FlatMetadataFormatter.flatten_metadata_path
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
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
[ "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" ]
Flattens a sequence of metadata keys into a simple key string distinguishing the path to a value stored at some depth in a tree of metadata. === Parameters metadata_path(Array):: array of metadata path elements === Returns flat_path(String):: flattened path
[ "Flattens", "a", "sequence", "of", "metadata", "keys", "into", "a", "simple", "key", "string", "distinguishing", "the", "path", "to", "a", "value", "stored", "at", "some", "depth", "in", "a", "tree", "of", "metadata", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/clouds/metadata_formatters/flat_metadata_formatter.rb#L100-L106
3,782
rightscale/right_link
lib/instance/right_scripts_cookbook.rb
RightScale.RightScriptsCookbook.script_path
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
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
[ "def", "script_path", "(", "nickname", ")", "base_path", "=", "nickname", ".", "gsub", "(", "/", "/", ",", "'_'", ")", "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" ]
Produce file name for given script nickname === Parameters nickname(String):: Script nick name === Return path(String):: Path to corresponding recipe
[ "Produce", "file", "name", "for", "given", "script", "nickname" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/right_scripts_cookbook.rb#L96-L104
3,783
rightscale/right_link
lib/instance/right_scripts_cookbook.rb
RightScale.RightScriptsCookbook.cache_dir
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
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
[ "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" ]
Path to cache directory for given script === Parameters script(Object):: script object of some kind (e.g. RightScale::RightScriptInstantiation) === Return path(String):: Path to directory used for attachments and source
[ "Path", "to", "cache", "directory", "for", "given", "script" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/right_scripts_cookbook.rb#L159-L169
3,784
edap/yourub
lib/yourub/meta_search.rb
Yourub.MetaSearch.search
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
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
[ "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" ]
Search through the youtube API, executing multiple queries where necessary @param criteria [Hash] @example client = Yourub::Client.new client.search(country: "DE", category: "sports", order: 'date')
[ "Search", "through", "the", "youtube", "API", "executing", "multiple", "queries", "where", "necessary" ]
467f597447505bb9669599682562c778d11941a9
https://github.com/edap/yourub/blob/467f597447505bb9669599682562c778d11941a9/lib/yourub/meta_search.rb#L12-L29
3,785
edap/yourub
lib/yourub/meta_search.rb
Yourub.MetaSearch.get_views
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
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
[ "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" ]
return the number of times a video was watched @param video_id[Integer] @example client = Yourub::Client.new client.get_views("G2b0OIkTraI")
[ "return", "the", "number", "of", "times", "a", "video", "was", "watched" ]
467f597447505bb9669599682562c778d11941a9
https://github.com/edap/yourub/blob/467f597447505bb9669599682562c778d11941a9/lib/yourub/meta_search.rb#L36-L41
3,786
edap/yourub
lib/yourub/meta_search.rb
Yourub.MetaSearch.get
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
def get(video_id) params = {:id => video_id, :part => 'snippet,statistics'} request = Yourub::REST::Videos.list(self,params) Yourub::Result.format(request).first end
[ "def", "get", "(", "video_id", ")", "params", "=", "{", ":id", "=>", "video_id", ",", ":part", "=>", "'snippet,statistics'", "}", "request", "=", "Yourub", "::", "REST", "::", "Videos", ".", "list", "(", "self", ",", "params", ")", "Yourub", "::", "Result", ".", "format", "(", "request", ")", ".", "first", "end" ]
return an hash containing the metadata for the given video @param video_id[Integer] @example client = Yourub::Client.new client.get("G2b0OIkTraI")
[ "return", "an", "hash", "containing", "the", "metadata", "for", "the", "given", "video" ]
467f597447505bb9669599682562c778d11941a9
https://github.com/edap/yourub/blob/467f597447505bb9669599682562c778d11941a9/lib/yourub/meta_search.rb#L48-L52
3,787
gregwebs/hamlet.rb
lib/hamlet/parser.rb
Hamlet.Parser.parse_text_block
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
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
[ "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" ]
This is fundamentally broken Can keep this for multi-lie html comment perhaps But don't lookahead on text otherwise
[ "This", "is", "fundamentally", "broken", "Can", "keep", "this", "for", "multi", "-", "lie", "html", "comment", "perhaps", "But", "don", "t", "lookahead", "on", "text", "otherwise" ]
3ed5548e0164fa0622841746f0898fda88cbae42
https://github.com/gregwebs/hamlet.rb/blob/3ed5548e0164fa0622841746f0898fda88cbae42/lib/hamlet/parser.rb#L173-L235
3,788
ahuth/emcee
lib/emcee/directive_processor.rb
Emcee.DirectiveProcessor.render
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
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
[ "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" ]
Implement `render` so that it uses our own header pattern.
[ "Implement", "render", "so", "that", "it", "uses", "our", "own", "header", "pattern", "." ]
0c846c037bffe912cb111ebb973e50c98d034995
https://github.com/ahuth/emcee/blob/0c846c037bffe912cb111ebb973e50c98d034995/lib/emcee/directive_processor.rb#L10-L31
3,789
rightscale/right_link
spec/spec_helper.rb
RightScale.SpecHelper.cleanup_state
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
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
[ "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" ]
Cleanup files generated by instance state
[ "Cleanup", "files", "generated", "by", "instance", "state" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/spec_helper.rb#L160-L169
3,790
rightscale/right_link
spec/spec_helper.rb
RightScale.SpecHelper.delete_if_exists
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
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
[ "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" ]
Test and delete if exists
[ "Test", "and", "delete", "if", "exists" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/spec_helper.rb#L197-L206
3,791
rightscale/right_link
spec/spec_helper.rb
RightScale.SpecHelper.setup_script_execution
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
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
[ "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" ]
Setup location of files generated by script execution
[ "Setup", "location", "of", "files", "generated", "by", "script", "execution" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/spec/spec_helper.rb#L209-L213
3,792
pixeltrix/prowler
lib/prowler/application.rb
Prowler.Application.verify
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
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
[ "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" ]
Verify the configured API key is valid
[ "Verify", "the", "configured", "API", "key", "is", "valid" ]
29931ce04336cc58f45732af00f33b5821cda431
https://github.com/pixeltrix/prowler/blob/29931ce04336cc58f45732af00f33b5821cda431/lib/prowler/application.rb#L77-L80
3,793
albertosaurus/pg_comment
lib/pg_comment/schema_dumper.rb
PgComment.SchemaDumper.tables_with_comments
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
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
[ "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" ]
Support for dumping comments
[ "Support", "for", "dumping", "comments" ]
9a8167832a284b0676f6ac9529c81f3349ba293d
https://github.com/albertosaurus/pg_comment/blob/9a8167832a284b0676f6ac9529c81f3349ba293d/lib/pg_comment/schema_dumper.rb#L11-L22
3,794
albertosaurus/pg_comment
lib/pg_comment/schema_dumper.rb
PgComment.SchemaDumper.dump_comments
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
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
[ "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" ]
Dumps the comments on a particular table to the stream.
[ "Dumps", "the", "comments", "on", "a", "particular", "table", "to", "the", "stream", "." ]
9a8167832a284b0676f6ac9529c81f3349ba293d
https://github.com/albertosaurus/pg_comment/blob/9a8167832a284b0676f6ac9529c81f3349ba293d/lib/pg_comment/schema_dumper.rb#L25-L41
3,795
rightscale/right_link
scripts/command_helper.rb
RightScale.CommandHelper.send_command
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
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
[ "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" ]
Creates a command client and sends the given payload. === Parameters @param [Hash] cmd as a payload hash @param [TrueClass, FalseClass] verbose flag @param [TrueClass, FalseClass] timeout or nil === Block @yield [response] callback for response @yieldparam response [Object] response of any type
[ "Creates", "a", "command", "client", "and", "sends", "the", "given", "payload", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/command_helper.rb#L48-L60
3,796
rightscale/right_link
scripts/command_helper.rb
RightScale.CommandHelper.default_logger
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
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
[ "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" ]
Default logger for printing to console
[ "Default", "logger", "for", "printing", "to", "console" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/command_helper.rb#L146-L155
3,797
rightscale/right_link
scripts/ohai_runner.rb
RightScale.OhaiRunner.run
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
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
[ "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" ]
Activates RightScale environment before running ohai === Return true:: Always return true
[ "Activates", "RightScale", "environment", "before", "running", "ohai" ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/ohai_runner.rb#L29-L36
3,798
rightscale/right_link
lib/instance/volume_management.rb
RightScale.VolumeManagementHelper.manage_planned_volumes
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
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
[ "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" ]
Manages planned volumes by caching planned volume state and then ensuring volumes have been reattached in a predictable order for proper assignment of local drives. === Parameters block(Proc):: continuation callback for when volume management is complete. === Return result(Boolean):: true if successful
[ "Manages", "planned", "volumes", "by", "caching", "planned", "volume", "state", "and", "then", "ensuring", "volumes", "have", "been", "reattached", "in", "a", "predictable", "order", "for", "proper", "assignment", "of", "local", "drives", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/volume_management.rb#L52-L138
3,799
rightscale/right_link
lib/instance/volume_management.rb
RightScale.VolumeManagementHelper.detach_planned_volume
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
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
[ "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" ]
Detaches the planned volume given by its mapping. === Parameters mapping(Hash):: details of planned volume
[ "Detaches", "the", "planned", "volume", "given", "by", "its", "mapping", "." ]
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/volume_management.rb#L144-L174